Setup .env & config/database.php:
- Config/database.php file gets the database settings from .env file
- eg:
- ‘host’ => env(‘DB_HOST’, ‘localhost’)
- eg:
- To set DB settings dynamically in .env file, use the code from the following link in your controller:
- http://laravel-tricks.com/tricks/change-the-env-dynamically
- I have put the changeEnv function in Controllers.php file with conditions to choose between dev and prod db hosts
- Using a constructor in the working controller to set the database name for that controller
Setting controller method:
- 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:
- Route instance has options to call controller methods directly:
-
Route::get('index','UsersController@index');
-
Viewing the user info:
- In users/index.blade.php :
-
@foreach ($users as $user) <p>This user id is - {{ $user->user_id}}</p> @endforeach
-