Table of contents

create model in laravel

In this post, I will show you an example of how to create a model in the Laravel 8, and 9 applications. I will give you an example so that it will easier to you to follow and understand. Laravel has a built-in command to run that will generate the Model for your Laravel 8 and 9 applications.

 

After following this tutorial for creating a model in Laravel using the artisan command surely it will be easier for you from now on. Laravel artisan can run in any operating system like Ubuntu and CMD in Windows.

 

What is a Model in Laravel Application?

The Model is a PHP class that performs business logic and database manipulation like - retrieving, inserting, updating, and deleting data.

 

Create Model in Laravel

In the Laravel application we just simply run a command to create a model in Laravel 8. See the following example below:

php artisan make:model Employee

 

create model in laravel

Now you will see the generated model in your Models directory:

app/Models/Employee.php

<?php

namespace App\Models;

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

class Employee extends Model
{
    use HasFactory;
}

 

Setup Model Properties

Now let's, add protected $table = ""; and protected $fillable = []; to our model and defined each values.

 

protected $table: Define model table name

protected $fillable: Fields that are mas-assignable

 

See below on how to setup:

<?php

namespace App\Models;

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

class Employee extends Model
{
    /**
     * @var string $table
     */
    protected $table = 'employees';

    /**
     * @var array $fillable
     */
    protected $fillable = [
        'field_name_1',
        'field_name_2'
    ];

    use HasFactory;
}

 

Additional Options to Create Model in Laravel Application

 

If you would like to generate database migration then apply this command:

php artisan make:model Employee --migration

 

Generate model with Factory.

php artisan make:model Employee --factory
php artisan make:model Employee -f

 

Generate model with Seeder.

php artisan make:model Employee --seed
php artisan make:model Employee -s

 

Generate model with Controller.

php artisan make:model Employee --controller
php artisan make:model Employee -c

 

Generate model with Policy.

php artisan make:model Employee --policy

 

Generate model with migration, factory, seeder, and controller.

php artisan make:model Employee -mfsc

 

Generate model with migration, factory, seeder, policy, and controller.

php artisan make:model Employee --all

 

Generate a pivot model.

php artisan make:model Member --pivot

 

That's it. Now you have an idea already on how to create a model in Laravel 8, and 9 using the artisan command.