What is Laravel Stub

What is Laravel Stub

Laravel stubs are helper modules that enable us to customize the default Artisan generated classes.

For example, when you need to send data to a database, you are supposed to indicate fields that are $fillable or $guarded. This can be very time-consuming when it comes to creating an Enterprise system that involves hundreds of tables, as you will need to make these changes for each and every model.

With stubs, you can simply indicate that you want all models to have $guarded = []. This should be done before you start creating the models.

Example

To publish stubs we need to run the following command:

php artisan stub:publish

A new stubs directory would be added to your project. In the stubs directory, there are files that can also be used for customization. in this example, we will be editing the model.stub file.

Let’s now add $guarded=[] to the model stub:

<?php
namespace {{ namespace }};
use Illuminate\Database\Eloquent\Model;
class {{ class }} extends Model
{
 // let us make customize it
protected $guarded = [];
}

Now that we have added the $guarded=[] property to the stub for the model, we run the command to create a new TestModel:

php artisan:make:model TestModel

You will notice that the code above has protected $guarded=[];, and any other model you create will come with this property.

Conclusion

Laravel stubs enable easy customization of created class properties, which increases the speed of development.
 

Enjoy this article ? drop a comment below and add your own contribution.

Maye Jacob

Jacob Olorunmaye

Verified Expert
Passionate Backend Developer | Expert in PHP, Laravel, JavaScript, and Golang 🚀 | Crafting seamless, scalable solutions for the digital era

Leave a Reply

Your email address will not be published. Required fields are marked *