Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel create model from custom stub when using php artisan

When I use php artisan make:model CustomNamespace\TestModel, I get a model based on default stub as this :

namespace App\Models\CustomNamespace;
use Illuminate\Database\Eloquent\Model;
class TestModel extends Model
{
    //
}

But what I want to create is a dynamic Model based on my own stub to get something like this:

namespace App\Models\CustomNamespace;

use App\Models\MyParent;
/**
 * Put a dynamic doc here
 */
class MyModel extends MyParent
{
    /*put custom methods here*/
}

I've checked Laravel docs and other tutos but nothing on this, could you help guys ?

like image 879
4givN Avatar asked Jan 22 '18 15:01

4givN


2 Answers

Since Laravel 7, you can apply stub customization by running:

php artisan stub:publish

This command will publish all the stub files that are used for the artisan make commands in the stubs directory of the application root, and give you the ability to change them according to your project's needs.

One of them is stubs/model.stub:

<?php

namespace {{ namespace }};

use Illuminate\Database\Eloquent\Model;

class {{ class }} extends Model
{
    //
}

Change it to:

<?php

namespace {{ namespace }};

use App\Models\MyParent;

/**
 * Put your documentation here
 */
class {{ class }} extends MyParent
{
    /* Put your custom methods here */
}

You can read a bit more about stub customization in this blog post.

like image 114
piscator Avatar answered Nov 08 '22 17:11

piscator


Create a new command, extend the Illuminate\Foundation\Console\ModelMakeCommand class and override the getStub() method:

protected function getStub()
{
    if ($this->option('pivot')) {
        return __DIR__.'/stubs/pivot.model.stub';
    }

    return storage_path('/stubs/my-own-model.stub');
}
like image 30
Alexey Mezenin Avatar answered Nov 08 '22 17:11

Alexey Mezenin