What is Model in Laravel | How to Create it | Connecting with Tables | Laravel 9

Introduction to Model in Laravel

What is Model?

1. Models are class based php files.

2. Laravel includes Eloquent, an object relational mapper (ORM) that makes it enjoyable and interact with your database.

3. Each database table has a corresponding "Model" that is used to interact with that table.

Note - Model creates from table and from tables it will be a database.

Commands to Make Model

It is only for model -
    php artisan make:model <ModelName>
Note- The name of model first letter should be capital because it will be a class and give the table name where you want to connect this model.

php artisan make:model Customers

go to Apps>Models>Customers> and assign table name and primary key as given below.

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customers extends Model
{
    use HasFactory;
    protected $table = "customers";
    protected $primaryKey = "customer_id";
}


after that go to phpmyadmin and insert dummy data in columns.



Now go to routes>web.php 

use App\Models\Customers;

Route::get('/customer', function(){
    $customers = Customers::all();
    echo "<pre>";
    print_r($customers->toArray());
});

toArray() is a function which returns the values in the array. If you don't use it no problem at all. It will be run safely.

print_r use for print the objects and the data inserted in database using phpmyadmin will be printed on url/customer.

Now run with - php artisan serve to load on development server.

Note - It will be work on MVC Mode pass the data to the controller and controller pass it to views it is all about how mvc works.

If you want to create Model and Migration in a single line command will be - Model with Migration: php artisan make:model <ModelName> --migration.

for example -

php artisan make:model Product --migration 

This command will create Mode and Migration both at a time. Senior developers mostly like these kind of commands because it is time saving.

Comments