DEV Community

Cover image for Laravel 7: Customize stubs
Zubair Mohsin
Zubair Mohsin

Posted on

Laravel 7: Customize stubs

In Laravel 7, you will be able to customize stubs.

Publishing stubs

In order to customize stub files, you need to publish them:

php artisan stub:publish

After running this command, a new directory will be added in your project.

stubs-directory

Let's have a look at most commonly used php artisan make:controller command stub file controller.plain.stub

<?php

namespace {{ namespace }};

use {{ rootNamespace }}Http\Controllers\Controller;
use Illuminate\Http\Request;

class {{ class }} extends Controller
{
    //
}
Enter fullscreen mode Exit fullscreen mode

You can make any kind of changes to this stub file.

Example

Let's say we want every controller to have an __invoke() function.

<?php

namespace {{ namespace }};

use {{ rootNamespace }}Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Inspiring;

class {{ class }} extends Controller
{
    public function __invoke()
    {

    }
}
Enter fullscreen mode Exit fullscreen mode

Now let's make a controller:

php artisan make:controller StubsTestController

Output:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class StubsTestController extends Controller
{
    public function __invoke()
    {

    }
}
Enter fullscreen mode Exit fullscreen mode

Happy Stubbing πŸ‘¨πŸ½β€πŸ’»β˜πŸ½

Let me know in comments how this can help you πŸ€“

Top comments (2)

Collapse
 
wmiriye profile image
Wes Miriye

I am a bit confused where everyone is getting the stub constants from. For example, something like $FIELD_BODY$ or $ROUTE_NAMED_PREFIX$.

Where is the documentation for stub variables? I am having trouble finding it.

Collapse
 
bertheyman profile image
Bert Heyman

Thanks for writing this article!

Quite nice that the stubs are available to customise.
Only thing I miss though would be a way of using more variables inside the stub. A table name for a model for example, could perhaps be guessed like this: Str::plural(Str::snake($this->argument('model'))).

But extra variables would make things too complex to keep compatible with the generating functions, so I guess for these use cases a custom generator function would be a better choice.