Laravel Stub Customization

Saurabh Mahajan
2 min readSep 24, 2020

--

If you have been developing with Laravel, you would have definitely used Artisan Console make commands. They are used to create a variety of classes like Controller, Model, Request, Jobs, Migrations etc. These make commands comes up with a variety of arguments and options so as to customize the Class created.

Have you ever wondered how Laravel creates these files. It turns out Laravel uses what are known as Stub files.

Laravel Stub

These Stub Files can be seen as the Template File of the Final File to be generated. As an example, Stub File corresponding to the Request File looks like below:

<?phpnamespace {{ namespace }};use Illuminate\Foundation\Http\FormRequest;class {{ class }} extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}

So when you create a New Request File using the below command:

php artisan make:request PostRequest

Laravel will fetch the stub file corresponding to make:request. And then it will go on replacing all the constants defined between {{}}, based on the arguments and options.

These Stub Files are located in the Laravel Framework itself. However, if you want to customize them, you can publish them using the following command.

php artisan stub:publish

This will create a stubs directory at the root of your project and move all the stub files here.

For eg, whenever I create a Request File, I always change the authorize() method to return true instead of false, as I handle all the authorizations in Policy instead of Request File. So rather than to manually change the Request File created using the make:request command, instead I change the stub file itself so that this method returns true. This way whenever, I create a Request File I don’t have to make that change manually.

If you often find yourself changing the file generated from the make command, you should also consider changing the stub file.

--

--