Laravel Retrieving data from database

Setup .env & config/database.php:

  1. Config/database.php file gets the database settings from .env file
    • eg:
      • ‘host’ => env(‘DB_HOST’, ‘localhost’)
  2. To set DB settings dynamically in .env file, use the code from the following link in your controller:

Setting controller method:

  1. Call database table or view from your controller method in the following way:
    • public function index(){
       $users = DB::table('users')->get();
       return view('users/index', ['users' => $users]);

Setting routes in Routes/web.php:

  1. Route instance has options to call controller methods directly:
    • Route::get('index','UsersController@index');


Viewing the user info:

  1. In users/index.blade.php :
    •  @foreach ($users as $user)
      <p>This user id is - {{ $user->user_id}}</p>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s