I want to include some commented code above my resource controllers class declarations, ideally to be added when generating the controller using php artisan make:controller MyController -resource
. Namely, I want to add the path aliases at the top of each controller file:
/*
Verb URI Action Route Name desc
GET /photos index photos.index Display a listing of the resource.
GET /photos/create create photos.create Show the form for creating a new resource.
POST /photos store photos.store Store a newly created resource in storage.
GET /photos/{photo} show photos.show Display the specified resource.
GET /photos/{photo}/edit edit photos.edit Show the form for editing the specified resource.
PUT/PATCH /photos/{photo} update photos.update Update the specified resource in storage.
DELETE /photos/{photo} destroy photos.destroy Remove the specified resource from storage.
*/
This is purely a convenience example, but there have been other times when I want to add other stuff to the models and migrations I am generating with artisan. Can this be done? Would I need to recompile the artisan binaries?
It's a bit tricky but if you know how to find your way around the container you should be fine.
First you have to overwrite the ArtisanServiceProvider
by extending the default one and change this method.
/**
* Register the command.
*
* @return void
*/
protected function registerControllerMakeCommand()
{
$this->app->singleton('command.controller.make', function ($app) {
return new ControllerMakeCommand($app['files']);
});
}
By doing this you simply allow yourself to assign a custom ControllerMakeCommand
in the container.
Then you simply copy that class as well and change code you want.
In your case the stub file.
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
$stub = null;
if ($this->option('parent')) {
$stub = '/stubs/controller.nested.stub';
} elseif ($this->option('model')) {
$stub = '/stubs/controller.model.stub';
} elseif ($this->option('invokable')) {
$stub = '/stubs/controller.invokable.stub';
} elseif ($this->option('resource')) {
$stub = '/stubs/controller.stub';
}
if ($this->option('api') && is_null($stub)) {
$stub = '/stubs/controller.api.stub';
} elseif ($this->option('api') && ! is_null($stub) && ! $this->option('invokable')) {
$stub = str_replace('.stub', '.api.stub', $stub);
}
$stub = $stub ?? '/stubs/controller.plain.stub';
return __DIR__.$stub;
}
And of course you have to copy the stub file and edit it according to your needs.