Back to Course |
Laravel 11 Eloquent: Expert Level

Customize Model Default Template with Stubs

The default Eloquent Model is generated with a structure as below.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
use HasFactory;
}

And it has a trait HasFactory. What if you want to remove it because you won't use it in the project and want all new Models not to have it?

You can overwrite the default structure by publishing stubs.

php artisan stub:publish

Now, you have a new folder /stubs at the root of your project. You can change more than a Model stub if your project needs it. The Model stub looks as below.

stubs/model.stub:

<?php
 
namespace {{ namespace }};
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class {{ class }} extends Model
{
use HasFactory;
}

You can add and remove what you need from the stub.

stubs/model.stub:

<?php
 
namespace {{ namespace }};
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class {{ class }} extends Model
{
use HasFactory;
}

When you create a new Model using the artisan command, the HasFactory trait won't be added.

php artisan make:model Post

app/Models/Post.php:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
}