Home / Snippets / How to Run Artisan Command from Code in Laravel
How to Run Artisan Command from Code in Laravel cover

How to Run Artisan Command from Code in Laravel

4.3K

3 years ago

0 comments

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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this