DEV Community

Cover image for Make your own Artisan script
Capsules Codes
Capsules Codes

Posted on • Updated on • Originally published at capsules.codes

Make your own Artisan script

TL;DR : How to use the php artisan command line without using the word artisan.

 
 

You can find a Laravel Project example on our Github Repository.

 
 

Every Laravel artisan will recognize the php artisan inspire command. But not everyone might realize that this command can be customized.

 
 

The unspeakable secret: modifying the artisan file at the root of the project.

 

mv ./artisan ./is-dead
Enter fullscreen mode Exit fullscreen mode

 
 

Incredible! The command php is-dead inspire will from now on work just as well as the initial php artisan inspire command.

 
 

We could put a stop to this drama right here, you might say, but we will go further.

 
 

Some of you may already know, but it's also possible to call the Artisan command via the Facade\Artisan as shown below in the console.php routes file

 

Artisan::command( 'inspire', function () {
    $this->comment( Inspiring::quote() );
})->purpose( 'Display an inspiring quote' );
Enter fullscreen mode Exit fullscreen mode

 
 

All that would then be needed is to copy the /vendor/laravel/framework/Illuminate/Support/Facades/Artisan.php file.

 

<?php

namespace Illuminate\Support\Facades;

use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;

class Artisan extends Facade
{
    protected static function getFacadeAccessor()
    {
        return ConsoleKernelContract::class;
    }
}
Enter fullscreen mode Exit fullscreen mode

 
 

And then modify the relevant information in a new file [ and folder ] in app/Facades/IsDead.php.

 

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;
use Illuminate\Contracts\Console\Kernel;

class IsDead extends Facade
{
    protected static function getFacadeAccessor() : string
    {
        return Kernel::class;
    }
}

Enter fullscreen mode Exit fullscreen mode

 
 

To then be able to use it in your code, you need to inject the alias into the list of aliases in the configuration file config/app.php.

 

'aliases' => Facade::defaultAliases()->merge( [
        'IsDead' => App\Facades\IsDead::class
    ] )->toArray(),
Enter fullscreen mode Exit fullscreen mode

 
 

Let's modify the inspire method in routes/console.php so we can read it in tinker.

 

use Illuminate\Foundation\Inspiring;
use App\\Facades\IsDead;

IsDead::command( 'inspire', function () {
   echo Inspiring::quotes()->random();
})->purpose( 'Display an inspiring quote' );
Enter fullscreen mode Exit fullscreen mode

 
 

Now, all that's left is to use it in php is-dead tinker.

 

IsDead::call( 'inspire' );
Enter fullscreen mode Exit fullscreen mode

 
 

Glad this helped.

 
 

Find out more on Capsules or X

Top comments (0)