Laravel's Artisan command-line interface is one of the framework's most powerful features. It automates repetitive tasks, generates boilerplate code, and provides tools for debugging and optimization. Whether you're a beginner or experienced developer, mastering Artisan will significantly improve your productivity.
Introduction
Artisan is Laravel's built-in CLI tool, named after skilled craftspeople who create things with their hands. Just as an artisan shapes raw materials into finished products, Laravel's Artisan shapes your commands into working code, migrations, and optimized applications.
Every Laravel installation includes Artisan out of the box. You access it through the php artisan command from your project root. The tool provides over 80 built-in commands and allows you to create custom commands for your specific needs.
To see all available commands, run:
php artisan list
For help with any specific command, use the help option:
php artisan help migrate
Application Management
Generating Application Keys
Every Laravel application needs a unique encryption key for secure sessions and encrypted data. Generate one with:
php artisan key:generate
This command creates a random 32-character key and updates your .env file's APP_KEY value. The --ansi flag adds colored output for better readability:
php artisan key:generate --ansi
Never share your application key or commit it to version control. Each environment (local, staging, production) should have its own unique key.
Running the Development Server
Laravel includes a built-in development server that eliminates the need for external web server configuration:
php artisan serve
By default, this starts a server at http://localhost:8000. You can customize the host and port:
php artisan serve --host=127.0.0.1 --port=8080
For development across multiple devices on a network, bind to all interfaces:
php artisan serve --host=0.0.0.0
Creating Storage Symlinks
Laravel stores uploaded files in the storage/app/public directory, but web servers serve files from public/. Create a symbolic link between them:
php artisan storage:link
This creates public/storage pointing to storage/app/public, making uploaded files accessible via URLs like /storage/images/photo.jpg.
Code Generation Commands
Artisan's make commands generate boilerplate code following Laravel conventions. These commands save time and ensure consistency across your codebase.
Creating Controllers
Generate a new controller:
php artisan make:controller UserController
For a resource controller with all CRUD methods:
php artisan make:controller PostController --resource
For an API resource controller (without create/edit methods):
php artisan make:controller Api/ArticleController --api
Creating Models
Generate an Eloquent model:
php artisan make:model Product
Create a model with migration, factory, seeder, and controller:
php artisan make:model Order -mfsc
The flags mean:
-mcreates a migration-fcreates a factory-screates a seeder-ccreates a controller
Creating Middleware
Middleware filters HTTP requests entering your application:
php artisan make:middleware EnsureUserIsAdmin
This creates app/Http/Middleware/EnsureUserIsAdmin.php. Register it in bootstrap/app.php or apply it to specific routes.
Example middleware implementation:
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->is_admin) {
abort(403, 'Access denied.');
}
return $next($request);
}
Creating Policies
Policies organize authorization logic around models:
php artisan make:policy PostPolicy
Associate it with a model:
php artisan make:policy PostPolicy --model=Post
This generates methods for common actions like view, create, update, and delete:
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
Creating Form Requests
Form requests encapsulate validation logic:
php artisan make:request StoreUserRequest
Define rules in the generated class:
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'unique:users'],
];
}
Creating Events and Listeners
Generate an event:
php artisan make:event OrderShipped
Generate a listener:
php artisan make:listener SendShipmentNotification --event=OrderShipped
Creating Jobs
For queued background tasks:
php artisan make:job ProcessPodcast
Creating Commands
Create custom Artisan commands:
php artisan make:command SendWeeklyReport
Define the signature and logic:
protected $signature = 'report:weekly {--email= : Email address to send to}';
public function handle(): int
{
$email = $this->option('email') ?? 'default@example.com';
// Send report logic
$this->info("Report sent to {$email}");
return Command::SUCCESS;
}
Database Commands
Running Migrations
Migrations version-control your database schema. Run pending migrations:
php artisan migrate
In production, use the --force flag to bypass the confirmation prompt:
php artisan migrate --force
The --graceful flag prevents errors if there's nothing to migrate:
php artisan migrate --graceful --ansi
Rolling Back Migrations
Reverse the last batch of migrations:
php artisan migrate:rollback
Rollback a specific number of batches:
php artisan migrate:rollback --step=3
Reset all migrations:
php artisan migrate:reset
Fresh Migrations
Drop all tables and re-run all migrations:
php artisan migrate:fresh
Combine with seeding for development:
php artisan migrate:fresh --seed
Creating Migrations
Generate a new migration:
php artisan make:migration create_products_table
For adding columns to existing tables:
php artisan make:migration add_status_to_orders_table --table=orders
Database Seeding
Run all seeders:
php artisan db:seed
Run a specific seeder:
php artisan db:seed --class=UserSeeder
Caching and Optimization
Laravel provides several caching mechanisms to improve performance in production.
Configuration Caching
Cache all configuration files into a single file:
php artisan config:cache
Clear the configuration cache:
php artisan config:clear --ansi
Route Caching
Cache route definitions for faster registration:
php artisan route:cache
Clear the route cache:
php artisan route:clear
View Caching
Pre-compile all Blade templates:
php artisan view:cache
Clear compiled views:
php artisan view:clear
Event Caching
Cache the event-to-listener mappings:
php artisan event:cache
Complete Optimization
Run all optimization commands at once:
php artisan optimize
Clear all caches:
php artisan optimize:clear
This clears compiled classes, cached config, routes, views, and events. Use this when deploying or troubleshooting caching issues.
Route Management
Listing Routes
View all registered routes:
php artisan route:list
Filter by name:
php artisan route:list --name=admin
Filter by path:
php artisan route:list --path=api/users
Filter by method:
php artisan route:list --method=POST
Show route middleware:
php artisan route:list -v
Output as JSON for programmatic use:
php artisan route:list --json
Testing
Running Tests
Execute your test suite:
php artisan test
Run tests in parallel for faster execution:
php artisan test --parallel
Run a specific test file:
php artisan test tests/Feature/UserTest.php
Filter by test name:
php artisan test --filter=user_can_login
Stop on first failure:
php artisan test --stop-on-failure
Creating Tests
Generate a feature test:
php artisan make:test UserRegistrationTest
Generate a unit test:
php artisan make:test OrderCalculatorTest --unit
Interactive Shell
Using Tinker
Tinker is Laravel's REPL (Read-Eval-Print Loop) for interacting with your application:
php artisan tinker
Inside Tinker, you can:
Query the database:
>>> User::where('role', 'admin')->count()
=> 5
Create records:
>>> User::factory()->create(['name' => 'Test User'])
Test methods:
>>> app(UserService::class)->calculateDiscount($user)
=> 15.0
Dispatch jobs:
>>> dispatch(new ProcessOrder($order))
Test mail:
>>> Mail::raw('Test', fn($m) => $m->to('test@example.com'))
Exit Tinker with exit or Ctrl+D.
Package Management
Discovering Packages
After installing packages via Composer, Laravel auto-discovers service providers. Manually trigger discovery:
php artisan package:discover --ansi
Publishing Assets
Publish package assets, configs, or views:
php artisan vendor:publish
Publish specific tags:
php artisan vendor:publish --tag=laravel-assets --ansi --force
The --force flag overwrites existing files.
Publish a specific provider's assets:
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
Queue Management
Processing Jobs
Start a queue worker:
php artisan queue:work
Process jobs from a specific queue:
php artisan queue:work --queue=high,default
Limit memory usage:
php artisan queue:work --memory=128
Stop after processing one job (useful with Supervisor):
php artisan queue:work --once
Retrying Failed Jobs
View failed jobs:
php artisan queue:failed
Retry a specific job:
php artisan queue:retry 5
Retry all failed jobs:
php artisan queue:retry all
Clear failed jobs:
php artisan queue:flush
Scheduling
Running the Scheduler
Add this cron entry to run Laravel's scheduler every minute:
* * * * * cd /path-to-project && php artisan schedule:run >> /dev/null 2>&1
View scheduled tasks:
php artisan schedule:list
Test the scheduler locally:
php artisan schedule:work
Maintenance Mode
Enabling Maintenance Mode
Put your application into maintenance mode:
php artisan down
With a custom message:
php artisan down --message="Upgrading Database"
Allow specific IPs:
php artisan down --allow=192.168.1.1
Generate a secret bypass token:
php artisan down --secret="bypass-token"
Users can access the site at yoursite.com/bypass-token to get a cookie that bypasses maintenance mode.
Disabling Maintenance Mode
Bring the application back online:
php artisan up
Debugging Commands
Viewing Application Information
Display Laravel version and environment:
php artisan about
This shows PHP version, Laravel version, environment, debug mode, cache status, and driver configurations.
Inspecting Models
View model information:
php artisan model:show User
This displays the model's table, attributes, relationships, and observers.
Listing Events
See all registered events and listeners:
php artisan event:list
Custom Commands
Creating your own Artisan commands extends the CLI for your specific needs.
Basic Structure
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class GenerateReport extends Command
{
protected $signature = 'report:generate
{type : The type of report}
{--period=monthly : Reporting period}
{--email=* : Email recipients}';
protected $description = 'Generate and send reports';
public function handle(): int
{
$type = $this->argument('type');
$period = $this->option('period');
$emails = $this->option('email');
$this->info("Generating {$period} {$type} report...");
$this->withProgressBar(range(1, 100), function ($i) {
usleep(10000); // Simulate work
});
$this->newLine();
$this->info('Report generated successfully!');
return Command::SUCCESS;
}
}
Interactive Input
public function handle(): int
{
$name = $this->ask('What is your name?');
$password = $this->secret('What is your password?');
if ($this->confirm('Do you wish to continue?')) {
$choice = $this->choice('Select environment', ['local', 'staging', 'production'], 0);
$this->info("Selected: {$choice}");
}
return Command::SUCCESS;
}
Output Formatting
public function handle(): int
{
// Styled output
$this->info('Information message');
$this->comment('Comment message');
$this->question('Question message');
$this->error('Error message');
$this->warn('Warning message');
$this->newLine(2);
// Tables
$this->table(
['Name', 'Email'],
User::all(['name', 'email'])->toArray()
);
return Command::SUCCESS;
}
Common Command Flags
Many Artisan commands share common flags:
| Flag | Description |
|---|---|
--ansi |
Force ANSI colored output |
--no-ansi |
Disable ANSI colored output |
-q, --quiet |
Suppress all output |
-v, --verbose |
Increase output verbosity |
-vv |
More verbose output |
-vvv |
Maximum verbosity for debugging |
--env |
Specify the environment |
-n, --no-interaction |
Skip interactive prompts |
Best Practices
Development Workflow
- Use
makecommands consistently to generate boilerplate - Run
php artisan testbefore committing code - Use
tinkerfor quick experiments and debugging - Keep commands atomic and focused on single tasks
Production Deployment
- Always run
php artisan config:cachein production - Run
php artisan route:cachefor applications without closure routes - Run
php artisan view:cacheto pre-compile templates - Use
php artisan optimizeto run all optimizations at once - Run migrations with
--forceto bypass prompts
Troubleshooting
- Clear all caches with
php artisan optimize:clearwhen experiencing unexpected behavior - Use
-vvvflag for maximum debugging information - Check
php artisan aboutto verify environment configuration - Use
php artisan route:listto debug routing issues
Conclusion
Laravel Artisan transforms command-line interaction from a chore into a productivity multiplier. From generating code scaffolds to managing database migrations, from running tests to optimizing production deployments, Artisan provides tools for every stage of development.
The key to mastering Artisan is consistent usage. Start with the make commands to generate code, use migrate commands for database management, and explore the optimization commands as you move toward production. Create custom commands for repetitive project-specific tasks.
As your Laravel expertise grows, Artisan will become an indispensable part of your workflow. The time invested in learning these commands pays dividends across every project you build.