Posts Learn Components Snippets Categories Tags Tools About

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


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.

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()

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


        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 () {

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

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


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

Sponsors 👑

+ Add Yours