Published on

Adding stubs to your Laravel project

Author

The project that I am currently working on is primarily not using Eloquent — instead, I’m using a JSON:API item class from a package, spiced up with some additional code I’ve mixed in.

I’m making lots of these models, so I did a quick source-dive into the framework to figure out how the make:something commands are implemented. Turns out, writing your own is really easy.

<?php
 
namespace App\Console\Commands;
 
use Illuminate\Console\GeneratorCommand;
 
class JsonModelMakeCommand extends GeneratorCommand
{
    protected $name = 'make:json-model';
    protected $description = 'Create a new JSON:API model';
    protected $type = 'Model';
 
    protected function getStub()
    {
        return $this->laravel->basePath('/stubs/json-model.stub');
    }
 
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Models';
    }
}

For the stub, you just have to create stubs/json-model.stub at the root of your project. It has a couple of substitution tokens. The {{ rootNamespace }} one is the App/ namespace — that concern is the code I added.

<?php
 
namespace {{ namespace }};
 
use {{ rootNamespace }}Models\Concerns\ItemIsArrayable;
use Illuminate\Contracts\Support\Arrayable;
use Swis\JsonApi\Client\Item;
 
class {{ class }} extends Item implements Arrayable
{
    use ItemIsArrayable;
 
    protected $type = '{{ class }}';
}

You should add a note to the README about your new make command, so other developers notice it.

It’s worth noting that Laravel 7 added stub customization. What I showed above takes things a step beyond into new types classes that the framework does not have out of the box. If I had entirely eschewed using Eloquent, I could have updated the model stub instead of adding a whole new command.