Laravel Command Reference
Welcome! This comprehensive guide contains all essential Laravel Artisan commands organized by category. Use the sidebar to navigate quickly or search for specific commands.
Routes
Route List
# List all routes
php artisan route:list
# Hide routes defined by third-party packages
php artisan route:list --except-vendor
Router HTTP Methods
# Basic HTTP methods
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
# Multiple HTTP methods
Route::methods(['GET', 'POST'], $uri, $callback);
# All HTTP methods
Route::match(['GET', 'POST'], $uri, $callback);
Route::any($uri, $callback);
Route::allMethods($uri, $callback);
Route Optional Parameters
Route::get('/user/{name?}', function ($name = null) {
return $name;
});
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
Regular Expression Constraints
Route::get('/user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Route::get('/user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->whereInteger('id');
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->whereAlpha('name');
Accessing Current Route
$route = Route::current();
$route = Route::currentRouteName();
$route = Route::currentRouteAction();
Redirect Routes
# Basic redirects
Route::redirect('/here', '/there');
Route::redirect('/here', '/there', 301);
Route::redirect('/here', '/there', 301, ['id' => 123]);
Route::permanentRedirect('/here', '/there');
# Route list with redirect filters
php artisan route:list --redirect
php artisan route:list --redirect --except-vendor
php artisan route:list --redirect --only-vendor
php artisan route:list --redirect --only=home
php artisan route:list --redirect --except=home
Controllers
Controllers handle the application logic and coordinate between models and views.
# Basic controller
php artisan make:controller UserController
# Controller with model binding
php artisan make:controller UserController --model=User
# Resource controller
php artisan make:controller UserController --resource
# API controller
php artisan make:controller UserController --api
# Invokable controller
php artisan make:controller UserController --invokable
# Combined options
php artisan make:controller UserController --model=User --resource
php artisan make:controller UserController --model=User --api
php artisan make:controller UserController --model=User --resource --api
php artisan make:controller UserController --model=User --api --invokable
php artisan make:controller UserController --model=Photo --force
Models
Models represent database tables and handle data operations using Eloquent ORM.
Creating Models
# Basic model
php artisan make:model Photo
# Model with migration, controller, and resource
php artisan make:model Photo --migration --controller --resource
php artisan make:model Photo -crm
# Model with additional options
php artisan make:model Photo --force
php artisan make:model Photo --table=photos
php artisan make:model Photo --table=photos --connection=mysql
php artisan make:model Photo --table=photos --connection=mysql --migration --controller --resource --force
Model Mass Assignment
# Fillable attributes (whitelist)
protected $fillable = ['name', 'email'];
# Guarded attributes (blacklist)
protected $guarded = []; // Empty means all attributes are guarded
# Hidden attributes (not included in JSON)
protected $hidden = ['password', 'remember_token'];
# Cast attributes to specific types
protected $casts = [
'email_verified_at' => 'datetime',
];
# Date attributes
protected $dates = ['deleted_at'];
# Eager loading relationships
protected $with = ['posts'];
# Count relationships
protected $withCount = ['posts'];
# Append accessors to JSON
protected $appends = ['full_name'];
Migrations
Migrations are version control for your database, allowing you to modify and share database schemas.
Migration Commands
# Run new migrations
php artisan migrate
# Rollback latest migration
php artisan migrate:rollback
# Rollback all migrations
php artisan migrate:reset
# Rollback all and re-migrate
php artisan migrate:refresh
# Rollback all, re-migrate and run seeders
php artisan migrate:refresh --seed
# Create a migration
php artisan make:migration create_users_table
# Create migration with specified table
php artisan make:migration create_users_table --table=users
# Create migration with specified columns
php artisan make:migration create_users_table --table=users --columns="name:string(255),email:string(255),password:string(255)"
CRUD Operations
Create
$newUser = User::create([
'name' => 'John Doe',
'email' => 'john@example.com'
]);
Read
$users = User::all();
$user = User::find(1);
$activeUsers = User::where('status', 'active')->get();
$tags = Product::where('name', 'Some Product')->first()->tags;
Update
$user = User::find(1);
$user->update(['name' => 'Updated Name']);
User::where('status', 'inactive')->update(['status' => 'active']);
Delete
$user = User::find(1);
$user->delete();
User::where('status', 'inactive')->delete();
Seeders
Seeders allow you to populate your database with test data for development and testing.
# Create seeder
php artisan make:seeder BooksTableSeeder
php artisan make:seeder BooksTableSeeder --class=BooksTableSeeder
php artisan make:seeder BooksTableSeeder --force
php artisan make:seeder BooksTableSeeder --database=mysql
# Run seeders
php artisan db:seed
php artisan db:seed --class=BooksTableSeeder
php artisan db:seed --class=BooksTableSeeder --force
php artisan db:seed --database=mysql
Form Requests
php artisan make:request StoreBlogPost
Middleware
php artisan make:middleware IsAdmin
Policies
# Basic policy
php artisan make:policy PostPolicy
# Policy with model
php artisan make:policy PostPolicy --model=Photo
Artisan Commands
# Create custom command
php artisan make:command SendEmails
php artisan make:command SendEmails --command=Command
Events
php artisan make:event OrderShipped
Jobs
# Create job
php artisan make:job SendReminderEmail
# Create synchronous job
php artisan make:job SendReminderEmail --sync
Event Listeners
# Basic listener
php artisan make:listener SendShipmentNotification
# Listener for specific event
php artisan make:listener SendShipmentNotification --event=Event
# Queued listener
php artisan make:listener SendShipmentNotification --queued
# Basic mail
php artisan make:mail OrderShipped
# Mail with markdown template
php artisan make:mail OrderShipped --markdown
# Force create mail
php artisan make:mail OrderShipped --force
Notifications
# Basic notification
php artisan make:notification InvoicePaid
# Notification with markdown
php artisan make:notification InvoicePaid --markdown
# Force create notification
php artisan make:notification InvoicePaid --force
Service Providers
php artisan make:provider DuskServiceProvider
Tests
# Feature test
php artisan make:test UserTest
# Unit test
php artisan make:test UserTest --unit
Broadcasting Channels
php artisan make:channel OrderChannel
Custom Exceptions
# Basic exception
php artisan make:exception UserNotFoundException
# Exception with render method
php artisan make:exception UserNotFoundException --render
# Exception with report method
php artisan make:exception UserNotFoundException --report
Model Factories
# Basic factory
php artisan make:factory PostFactory
# Factory for specific model
php artisan make:factory PostFactory --model=Post
Model Observers
# Basic observer
php artisan make:observer PostObserver
# Observer for specific model
php artisan make:observer PostObserver --model=Post
Validation Rules
php artisan make:rule Uppercase
API Resources
# Basic resource
php artisan make:resource PostResource
# Resource collection
php artisan make:resource PostResource --collection=Post
Application Management
Application Overview
# Show application information
php artisan about
php artisan about --only=environment
Maintenance Mode
# Enable maintenance mode
php artisan down
php artisan down --retry=60
php artisan down --render="maintenance"
php artisan down --redirect=/
php artisan down --secret="myapp"
# Disable maintenance mode
php artisan up
HTTP Client
Laravel HTTP Client provides a fluent, expressive API for making HTTP requests.
Basic HTTP Requests
# Basic GET request
$response = Http::get('https://api.quotable.io/random');
# GET with parameters
$response = Http::get('https://api.quotable.io/random', ['param' => 'value']);
Response Methods
Data Formats
$result = $response->json();
$result = $response->object();
$result = $response->collect();
$result = $response->array();
$result = $response->body();
$result = $response->text();
Response Info
$result = $response->status();
$result = $response->successful();
$result = $response->headers();
$result = $response->cookies();
Authentication
Authentication provides user login, registration, and session management out of the box.
Authentication Methods
# Get authenticated user
$user = auth()->user();
$user = Auth::user();
$id = Auth::id();
# Check authentication status
$isAuthenticated = Auth::check();
$isGuest = Auth::guest();
# Get user properties
$name = auth()->user()->name;
$email = Auth::user()->email;
Blade Authentication Directives
{{-- Only visible for guests (not logged in) --}}
@guest
Login
@endguest
{{-- Only visible for authenticated users (logged in) --}}
@auth
Welcome, {{ auth()->user()->name }}!
@endauth
Carbon Date Library
Carbon is a simple API extension for DateTime that makes working with dates and times much easier.
Import Carbon
use Carbon\Carbon;
Creating Dates
Current Date/Time
# Current time
$now = Carbon::now();
# Current time with timezone
$now = Carbon::now('Asia/Kolkata');
$now = Carbon::now('America/New_York');
# Specific dates
$today = Carbon::today();
$yesterday = Carbon::yesterday();
$tomorrow = Carbon::tomorrow();
Custom Dates
# Create specific date
$newYear = Carbon::create(2024, 1, 1, 0, 0, 0);
# Parse date string
$date = Carbon::parse('2024-06-27 12:00:00');
# From timestamp
$timestamp = Carbon::createFromTimestamp(1622499200);
Date Manipulation
# Add time
echo $now->addDays(5); // 5 days from now
echo $now->addWeeks(2); // 2 weeks from now
echo $now->addMonths(3); // 3 months from now
# Subtract time
echo $now->subDays(5); // 5 days ago
echo $now->subWeeks(2); // 2 weeks ago
echo $now->subMonths(3); // 3 months ago
# Start and end of periods
echo $now->startOfDay(); // Start of today
echo $now->endOfDay(); // End of today
echo $now->startOfMonth(); // Start of the month
echo $now->endOfMonth(); // End of the month
Date Formatting
# Standard formats
echo $now->format('Y-m-d H:i:s'); // 2024-06-27 12:00:00
echo $now->toDateString(); // 2024-06-27
echo $now->toFormattedDateString(); // Jun 27, 2024
echo $now->toTimeString(); // 12:00:00
echo $now->toDateTimeString(); // 2024-06-27 12:00:00
# Custom format
echo $now->format('l jS \of F Y h:i:s A'); // Wednesday 27th of June 2024 12:00:00 PM
Date Comparison & Human Readable
# Comparisons
if ($now->lt($tomorrow)) {
echo 'Now is before tomorrow';
}
if ($now->isSameDay($anotherDate)) {
echo 'Same day';
}
# Human readable
echo $now->diffForHumans(); // 1 second ago
echo $now->addDays(5)->diffForHumans(); // 5 days from now
# Age calculation
$birthDate = Carbon::createFromDate(2000, 6, 27);
echo $birthDate->age; // 24
Blade Directives
Blade is Laravel's powerful templating engine with intuitive syntax for displaying data and controlling flow.
Debugging Directives
{{-- Debug helpers --}}
@dump($perPage, $newGenre, $genres->toArray())
@dd($perPage, $newGenre, $genres->toArray())
Conditional Directives
If Statements
@if($user->isAdmin)
Admin User
@else
Regular User
@endif
@isset($products)
Products exist
@endisset
@empty($records)
No records found
@endempty
Switch Statements
@switch($role)
@case('admin')
Administrator
@break
@case('user')
Regular User
@break
@default
Unknown Role
@endswitch
Loop Directives
{{-- For loop --}}
@for ($i = 0; $i < 10; $i++)
{{ $i }}
@endfor
{{-- Foreach loop --}}
@foreach($products as $product)
{{ $product->name }}
@endforeach
{{-- Forelse loop (with empty state) --}}
@forelse($products as $product)
{{ $product->name }}
@empty
No products found
@endforelse
{{-- While loop --}}
@while (true)
{{-- Loop content --}}
@endwhile
Authentication & Raw PHP
{{-- Authentication checks --}}
@auth
User is authenticated
@endauth
@guest
User is not authenticated
@endguest
{{-- Raw PHP code --}}
@php
$counter = 1;
@endphp
{{-- Display JSON data --}}
@json($products, JSON_PRETTY_PRINT)
Laravel 11 New Features
Laravel 11 introduces new publishing commands and simplified project structure.
Publishing Commands
# Publish language files
php artisan lang:publish
php artisan lang:publish --existing
# Publish config files
php artisan config:publish
php artisan config:publish --all
# Install route files
php artisan install:api
php artisan install:broadcasting
Authentication Setup
Legacy Authentication (Before Laravel 6)
# Create Laravel project
composer create-project laravel/laravel my-app
# Generate auth scaffolding
php artisan make:auth
Modern Authentication (Laravel 6+)
# Create Laravel project
composer create-project laravel/laravel my-app
# Install Laravel UI
composer require laravel/ui
composer require laravel/ui --dev
# Generate UI scaffolding
php artisan ui vue
php artisan ui react
php artisan ui bootstrap
# Generate UI with auth
php artisan ui vue --auth
php artisan ui react --auth
php artisan ui bootstrap --auth
# Install and compile assets
npm install
npm run dev # Development
npm run watch # Watch for changes
npm run build # Production (Vite)
Note: Modern Laravel applications use Laravel Breeze, Jetstream, or Fortify for authentication instead of the legacy UI package.