Courses

Laravel 12 Eloquent: Expert Level

Customize Model Default Template with Stubs

Summary of this lesson:
- Publishing and customizing model stubs
- Modifying default model template structure
- Removing default traits like HasFactory
- Understanding stub customization options

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 }};
 
{{ factoryImport }}
use Illuminate\Database\Eloquent\Model;
 
class {{ class }} extends Model
{
{{ factory }}
}

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

stubs/model.stub:

<?php
 
namespace {{ namespace }};
 
{{ factoryImport }}
use Illuminate\Database\Eloquent\Model;
 
class {{ class }} extends Model
{
{{ factory }}
}

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
{
}

Code for this lesson can be found on GitHub.

Previous: Model Properties: Tables, Keys, Increments, Pages and Dates

No comments yet…

avatar
You can use Markdown