Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

How to Run Artisan Command from Code in Laravel

Learn how to run artisan command from the codebase in Laravel and automate your workflow

Created on Jul 13, 2021

110 views

Sometimes you might need to run an artisan command from the Laravel codebase itself and that's possible by using the "Artisan" facade helper. Let's say you have a command to "generate laravel sitemap" and you want it to be triggered from the "web routes" when you access a certain route, you can do it like the code example below.

Console Command
Create a console command by running the "artisan make:command" in your terminal.
php artisan make:command GenerateSitemap

The content of the console command class should be as follows. Anytime the you run "site:generate-sitemap" command, the generate sitemap jobs will be dispatched and the sitemap will be generated.
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateSitemap extends Command {
    protected $signature = 'site:generate-sitemap';

    protected $description = 'Generate sitemap file';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Generating sitemap');

        \App\Jobs\GenerateSitemap::dispatch();

        return 0;
    }
}

Route File
To call and execute it from the routes file you can use the "Artisan" facade.
# /routes/web.php

use Illuminate\Support\Facades\Artisan;

Route::get('/generate-sitemap, function () {
    Artisan::call("site:generate-sitemap");
});

When you define the artisan command like the code above, it will be equivalent to writing "php artisan site:generate-sitemap" on the terminal.
php artisan site:generate-sitemap

So now when you visit "/generate-sitemap" path, the console command will be run and the sitemap will be generated.

Related Tutorial

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More