Table of contents
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
Â
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.
Read next