How to Create and Load Model in Laravel

A model is a PHP class where perform data logic and database manipulation like – retrieve data, insert, update, and delete.

In Laravel models classes are stored in app/ directory.

This mainly loads from the controller.

In this tutorial, I show how you create and load Model in the controller and fetch records from MySQL database in Laravel.

How to create and load Model in Laravel


Contents

  1. Table structure
  2. Database Configuration
  3. Model
  4. Controller
  5. Route
  6. View
  7. Output
  8. Conclusion

 


1. Table structure

I am using users table in the example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

3. Model

Create Model –

  • Open Command Prompt.
  • Navigate to your project directory.
  • Execute php artisan make:model Page. Here, I created Page model.
  • This will create a new file Page.php in app/ directory.

How to create and load Model in Laravel

Load DB Class and create method –

  • Navigate to app/ directory and open Page.php.
  • Import DB class use DB;.
  • Create single static method getuserData().
  • Fetch all records from the users table using DB::table('users')->orderBy('id','asc')->get().
  • Return $value.

NOTE – To use DB for database manipulation need to import DB class with use DB;.

Completed Code

<?php

namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;

class Page extends Model {
  public static function getuserData(){
    $value=DB::table('users')->orderBy('id', 'asc')->get();
    return $value;
  }
}

4. Controller

Create Controller –

  • Open Command Prompt.
  • Navigate to project directory.
  • Now, execute php artisan make:controller PagesController. Here, I created PagesController.

How to create and load Model in Laravel

Load Model –

  • Navigate to app/Http/Controllers/ directory and open PagesController.php.
  • Import Page Model from App namespace with use App\Page outside of class.
  • Create an index() method where call getuserData() method of Page model Page::getuserData() to fetch users data.
  • Store in $userData variable and pass to index view.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Page;

class PagesController extends Controller{
 
  public function index(){
 
    // Read value from Model method
    $userData = Page::getuserData();

    // Pass to view
    return view('index')->with("userData",$userData);
  }

}

5. Route

Open web.php file in route/ directory.

Defined single route.

Completed Code

<?php

// Controller-name@method-name
Route::get('/', 'PagesController@index'); // localhost:8000/

6. View

Create a new file index.blade.php in resources/views/ directory.

Read values from $userData using @foreach and create new rows.

Completed Code

<!doctype html>
<html>
  <body>
    <table border='1' style='border-collapse: collapse;'>
      <tr>
        <th>Username</th>
        <th>Name</th>
        <th>Email</th>
      </tr>
      @foreach($userData as $user)
      <tr>
        <td>{{ $user->username }}</td>
        <td>{{ $user->name }}</td>
        <td>{{ $user->email }}</td>
      </tr>
      @endforeach
    </table>
  </body>
</html>

7. Output

It gives following output –

How to create and load Model in Laravel


8. Conclusion

Before calling Model method from the controller first import Model class with use. Similarly, for using DB in the model need to import DB class.

If you found this tutorial helpful then don't forget to share.