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>

Laravel folder structure

  • Routes – /app/Http/routes.php
  • Controllers – /app/Http/Controllers
  • Models – /app/modelname.php
  • Views – /resources/views/
  • Database
    • Migrations – /database/migrations
    • Seeds – /database/seeds
    • sqlite database storage – /storage
  • APP URL & DB Configuration – /.env
  • Composer file -/composer.json
  • All downloads by composer – /vendor/
  • App Configuration, Providers & Aliases – /config/app.php

Laravel Tutorial 2

Database configuration:

  • Specify the database being used in config/database.php
  • If you’re using sqlite, create an “database.sqlite” file in either databses or storage. We do not need to edit the “.env” file
    • Setting the path for database.sqlite
      • folder names are referenced with “_path” Eg: storage folder as “storage_path()”, database folder as “database_path()”
      • If the file is in the storage folder then you can write “storage_path(‘database.sqlite’)”, else if it is in the database folder then you can write “database_path(‘database.sqlite’)”
  • If you’re using mysql change the authentication details and edit the “.env” file


First we will need to set up database schema.

  • Migrations are version control for databases
  • Usually you create tables using GUI but these migrations help you create tables in the app. It will help the team to work with tables without using GUI but with code
  • Creating a migration doesn’t create the table. It will need to be migrated to get the tables created
  • You want to make a migration: Check these commands
    • php artisan make:migration nameofmigration
    • php artisan migrate — This will create the tables  in the database
  • You can roll back using Down functions in the migration class



  • Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in database/seeds. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc.
  • Adding some data to the tables for viewing something on the browser
  • Use “php artisan make:seeder UsersTableSeeder”
  • Add insert statements in the run method
  • DB::table(‘words’)->insert([ ‘word’=>’Modest’, ‘meaning’=>’Refusing to take any credit’, ‘language’=>’English’ ]);

  • Running Seeders:
    • php artisan db:seed
    • php artisan db:seed –class=UsersTableSeeder (for sepcific seeders)


  • To work with our database we need models
  • php artisan make:model User
  • model gets created in /app folder – ‘user.php’


  • To start hitting the browsers we need to set up some Controllers and Routes to point to them.
  • php artisan make:controller UsersController
  • controller gets created in /app/Http/Controllers folder


  • Routes location:
    • Laravel 5.2.45
      • app/http/routes.php is the main routes file
    • Laravel 5.4.26
      • /routes/web.php is the main routes file
    • User php artisan –version” to know version of Laravel
  • You can return a view by writing
    • Route::get(‘/’, function () { return view(‘welcome’); });
  • You can return resources from controller
    • Route:resource(‘users’,’UsersController’);
  • command prompt – php artisan route:list to view all the routes
  • You can do nested resources (joining tables)
  • Calling a function in a controller:
    • Route::get(‘about’,’UsersController@index’);
    • you should have index function in the UsersController.php page
      • public function index(){ return ‘Welcome to My Dictionary’; }
      • this will return the welcome message string when you navigate to /app/about
    • Returning a view:
      • Do not worry about the extension of the view or path of the view while referencing a view
      • can name the view like ‘folder.view’
    • Routing a model
      • Route::model(‘words’,’Word’);
  • app/users – which got both GET & POST works everywhere except Firefox

Route Model binding:

  • route() helper function with a named route
  • routes.php ‘explicit binding’ –
    • Route::bind(‘words’, function($value) {
      return App\Word::where(‘userid’,$value)->first();
    • which lets you use App/users/1 and shows all the details on the page



  • To have consistent layouts across follow –
  • Reading & showing data is done – you don’t need to write any database queries to get the data from the database – it is done by Laravel




  • Creating a “Create User” link in the index.blade.php file
  • {{ HTML::linkRoute(‘create’, ‘Add Word’) }}
    • In Laravel 5.0 HTML & Form helpers not added by default anymore
    • add “laravelcollective/html” in the required array of the composer file
    • Add the following in config/app.php file
      • add providers – “Collective\Html\HtmlServiceProvider::class”
      • add alliases – ‘Form’ => Collective\Html\FormFacade::class‘Html’ => Collective\Html\HtmlFacade::class,

Create & Edit View:

  • create.blade.php & edit.blade.php needs to be created
  • <!-- /resources/views/projects/create.blade.php -->
        <h2>Create Project</h2>
        {!! Form::model(new App\Project, ['route' => ['']]) !!}
            @include('projects/partials/_form', ['submit_text' => 'Create Project'])
        {!! Form::close() !!}
    <!-- /resources/views/projects/edit.blade.php -->
        <h2>Edit Project</h2>
        {!! Form::model($project, ['method' => 'PATCH', 'route' => ['projects.update', $project->slug]]) !!}
            @include('projects/partials/_form', ['submit_text' => 'Edit Project'])
        {!! Form::close() !!}
  • Form View: /_form.blade.php
    • {!! Form::label(‘name’, ‘Name:’) !!} {!! Form::text(‘name’) !!}

      {!! Form::label(‘slug’, ‘Slug:’) !!} {!! Form::text(‘slug’) !!}

      {!! Form::label(‘completed’, ‘Completed:’) !!} {!! Form::checkbox(‘completed’) !!}

      {!! Form::label(‘description’, ‘Description:’) !!} {!! Form::textarea(‘description’) !!}

      {!! Form::submit($submit_text) !!}

  • Fixing mass assignment exception by addin – protected $guarded = []; to model “user.php” in app folder
  • You can start adding users
  • Note – If the primary key is not ‘id’ for a table it won’t update. You’ll have to change the the primary key in your model (Eloquent ORM (Object Reference Model)). Eg -> protected $primarykey=’userid’;
  • CRUD operations done
  • Flash Messages:
    • These are the messages that can be shown after a successful request

Things to do:

  • How to remove /public/app etc and make it /app without giving access to .env file?
  • How to add bootstrap & styling?
  • How to add JS if required?
  • How to move this localhost built app to a new server?

Whole Project Reference:

Github Repo:

Laravel Installation

  • Installing Laravel using composer
    Laravel is a PHP framework

    • Open command prompt (Windows)
    • Change directory and go to your webserver root directory (where you put all your website files)
    • Creating a new project in 2 ways:
      1. Execute this command “composer create-project laravel/laravel laravelApp”
      2. execute “laravel new laravelApp”
        1. this only works when laravel is installed globally
    • laravelApp is the new project name, you can your own project name, if the name is not specified new project will be created as laravel (name of the framework)
    • Above command executes laravel framework and all its dependencies
    • You’ll see a secure key provided on the screen on successful installation
    • On successful installation:
      • if you have local server running:
        • Navigate to “yourserver/laravelApp/public” to see welcome page(it shows ‘Laravel’)
      • if you want to use PHP built in environment