Skip to main content

Overview

LaraCMS includes custom Artisan commands to help with common administrative tasks. Commands are located in app/Console/Commands/ and can be run from the command line.

Available Commands

AssignSuperAdmin

Assigns the Super Admin role to a user by email address. Location: app/Console/Commands/AssignSuperAdmin.php

Command Signature

php artisan app:assign-super-admin {email}

Parameters

  • email (required) - The email address of the user to assign Super Admin role

Usage Examples

# Assign Super Admin role to a user
php artisan app:assign-super-admin [email protected]

Command Implementation

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Spatie\Permission\Models\Role;

class AssignSuperAdmin extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'app:assign-super-admin {email}';

    /**
     * The console command description.
     */
    protected $description = 'Assign the Super Admin role to a user by email';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $email = $this->argument('email');

        // Find the user by email
        $user = User::where('email', $email)->first();

        if (!$user) {
            $this->error("User with email {$email} not found.");
            return;
        }

        // Ensure the Super Admin role exists
        $role = Role::firstOrCreate(['name' => 'Super Admin']);

        // Check if the user already has the role
        if ($user->hasRole($role)) {
            $this->info("User {$user->email} already has the Super Admin role.");
            return;
        }

        // Assign the role
        $user->assignRole($role);

        $this->info("User {$user->email} has been assigned the Super Admin role.");
    }
}

What It Does

  1. Finds user by the provided email address
  2. Creates role if “Super Admin” role doesn’t exist
  3. Checks existing role to prevent duplicate assignments
  4. Assigns role using Spatie Laravel Permission package
  5. Provides feedback with success or error messages

Output Messages

Success:
User [email protected] has been assigned the Super Admin role.
User Not Found:
User with email [email protected] not found.
Already Has Role:
User [email protected] already has the Super Admin role.

GenerateSitemap

Generates an XML sitemap for your LaraCMS site. Location: app/Console/Commands/GenerateSitemap.php

Command Signature

php artisan sitemap:generate

Parameters

None - uses configuration from config/sitemap.php and config/app.php

Usage Examples

# Generate sitemap
php artisan sitemap:generate

# Schedule sitemap generation (add to scheduler)
php artisan schedule:run

Command Implementation

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;
use Psr\Http\Message\UriInterface;

class GenerateSitemap extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     */
    protected $description = 'Generate the sitemap.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        SitemapGenerator::create(config('app.url'))
            // Prevent crawling of admin, auth, and verification URLs
            ->shouldCrawl(function (UriInterface $url) {
                $path = $url->getPath();

                return !(
                    str_starts_with($path, '/admin') ||
                    str_starts_with($path, '/login') ||
                    str_starts_with($path, '/register') ||
                    str_starts_with($path, '/confirm-password') ||
                    str_starts_with($path, '/verify-email')
                );
            })

            // Extra safety: Don't include them in sitemap if crawled anyway
            ->hasCrawled(function (Url $url) {
                $path = $url->path();

                if (
                    str_starts_with($path, 'admin') ||
                    str_starts_with($path, 'login') ||
                    str_starts_with($path, 'register') ||
                    str_starts_with($path, 'confirm-password') ||
                    str_starts_with($path, 'verify-email')
                ) {
                    return null; // Skip this URL
                }

                return $url; // Keep
            })

            ->writeToFile(public_path('sitemap.xml'));

        $this->info('Sitemap generated successfully.');
    }
}

What It Does

  1. Crawls your site starting from the app URL (defined in config/app.php)
  2. Filters out protected URLs:
    • /admin - Admin dashboard
    • /login - Login page
    • /register - Registration page
    • /confirm-password - Password confirmation
    • /verify-email - Email verification
  3. Generates XML sitemap with all public pages
  4. Writes to file at public/sitemap.xml

Output

Success:
Sitemap generated successfully.
The sitemap will be available at https://yourdomain.com/sitemap.xml

Sitemap Configuration

Configure sitemap options in config/sitemap.php:
return [
    'guzzle_options' => [
        RequestOptions::COOKIES => true,
        RequestOptions::CONNECT_TIMEOUT => 10,
        RequestOptions::TIMEOUT => 10,
        RequestOptions::ALLOW_REDIRECTS => false,
    ],

    'execute_javascript' => false,
    'chrome_binary_path' => null,
    'crawl_profile' => Profile::class,
];

Scheduling Sitemap Generation

Automatically regenerate the sitemap daily by adding to app/Console/Kernel.php:
protected function schedule(Schedule $schedule)
{
    $schedule->command('sitemap:generate')->daily();
}

Creating Custom Commands

Generate a New Command

php artisan make:command YourCommandName
This creates a new command file in app/Console/Commands/.

Command Template

namespace App\Console\Commands;

use Illuminate\Console\Command;

class YourCommandName extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'app:your-command {argument} {--option=}';

    /**
     * The console command description.
     */
    protected $description = 'Brief description of your command';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $argument = $this->argument('argument');
        $option = $this->option('option');

        // Command logic here

        $this->info('Command executed successfully!');
    }
}

Command Best Practices

1. Use Descriptive Signatures

Make command signatures clear and follow Laravel conventions:
protected $signature = 'app:assign-super-admin {email}';

2. Provide Clear Descriptions

protected $description = 'Assign the Super Admin role to a user by email';

3. Handle Errors Gracefully

if (!$user) {
    $this->error("User not found.");
    return 1; // Return error code
}

4. Provide User Feedback

Use info(), error(), warn(), and comment() methods:
$this->info('Operation successful');
$this->error('Something went wrong');
$this->warn('This is a warning');
$this->comment('Additional information');

5. Use Arguments and Options

// Required argument
protected $signature = 'app:command {user}';

// Optional argument
protected $signature = 'app:command {user?}';

// Argument with default
protected $signature = 'app:command {user=admin}';

// Option
protected $signature = 'app:command {--force}';

// Option with value
protected $signature = 'app:command {--queue=default}';

6. Confirm Destructive Actions

if ($this->confirm('Do you wish to continue?')) {
    // Proceed with action
}

Common Command Patterns

Database Operations

public function handle()
{
    $users = User::where('active', false)->get();
    
    $bar = $this->output->createProgressBar($users->count());
    $bar->start();

    foreach ($users as $user) {
        // Process user
        $bar->advance();
    }

    $bar->finish();
    $this->newLine();
    $this->info('Processing complete!');
}

User Input

public function handle()
{
    $name = $this->ask('What is your name?');
    $password = $this->secret('What is the password?');
    $role = $this->choice('Select a role', ['Admin', 'User'], 0);
}

Table Output

public function handle()
{
    $users = User::all();
    
    $this->table(
        ['ID', 'Name', 'Email'],
        $users->map(fn($user) => [
            $user->id,
            $user->name,
            $user->email,
        ])
    );
}

Running Commands

Locally

php artisan sitemap:generate
php artisan app:assign-super-admin [email protected]

In Production

php artisan sitemap:generate --env=production

Via Scheduler

Add to app/Console/Kernel.php:
protected function schedule(Schedule $schedule)
{
    $schedule->command('sitemap:generate')->daily();
    $schedule->command('backup:clean')->daily()->at('01:00');
    $schedule->command('backup:run')->daily()->at('02:00');
}
Run the scheduler:
php artisan schedule:work
Or add to crontab:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Testing Commands

use Tests\TestCase;
use Illuminate\Support\Facades\Artisan;

class CommandTest extends TestCase
{
    public function test_assign_super_admin_command()
    {
        $user = User::factory()->create();
        
        Artisan::call('app:assign-super-admin', [
            'email' => $user->email
        ]);
        
        $this->assertTrue($user->fresh()->hasRole('Super Admin'));
    }
}

Next Steps

Build docs developers (and LLMs) love