📖 Guide
Laravel — Complete Reference
Laravel PHP framework cheat sheet for routing, Eloquent, Blade, Artisan, and more.
93 commands across 10 categories
Artisan CommandsRoutingControllersEloquent ORMMigrationsBlade TemplatesMiddlewareValidationAuthenticationCommon Helpers
Artisan Commands
| Command | Description |
|---|---|
php artisan serve | Start local development server on port 8000 |
php artisan make:model Post -mcr | Create model with migration, controller, and resource |
php artisan make:controller PostController --resource | Create resource controller with CRUD methods |
php artisan migrate | Run pending database migrations |
php artisan migrate:rollback | Rollback the last batch of migrations |
php artisan db:seed | Run database seeders |
php artisan route:list | List all registered routes |
php artisan tinker | Interactive REPL for your application |
php artisan cache:clear | Clear the application cache |
php artisan config:cache | Cache configuration for faster loading |
Routing
| Command | Description |
|---|---|
Route::get('/posts', [PostController::class, 'index']); | Define GET route to controller method |
Route::post('/posts', [PostController::class, 'store']); | Define POST route |
Route::put('/posts/{id}', [PostController::class, 'update']); | Define PUT route with parameter |
Route::delete('/posts/{id}', [PostController::class, 'destroy']); | Define DELETE route |
Route::resource('posts', PostController::class); | Register all CRUD routes at once |
Route::get('/user/{id?}', fn ($id = 1) => ...); | Optional route parameter with default |
Route::prefix('admin')->group(function () { ... }); | Group routes with URL prefix |
Route::middleware('auth')->group(function () { ... }); | Group routes with middleware |
Route::get('/home', fn () => view('home'))->name('home'); | Named route for URL generation |
Controllers
| Command | Description |
|---|---|
return view('posts.index', ['posts' => $posts]); | Return view with data |
return response()->json($data); | Return JSON response |
return redirect()->route('posts.index'); | Redirect to named route |
return redirect()->back()->with('status', 'Done!'); | Redirect back with flash message |
$request->input('name') | Get input value from request |
$request->all() | Get all request input as array |
$request->validate(['name' => 'required|max:255']); | Inline validation in controller |
$request->file('avatar')->store('avatars'); | Store uploaded file |
abort(404); | Throw HTTP 404 exception |
Eloquent ORM
| Command | Description |
|---|---|
Post::all() | Get all records |
Post::find(1) | Find record by primary key |
Post::findOrFail(1) | Find or throw 404 exception |
Post::where('status', 'published')->get() | Query with where clause |
Post::where('views', '>', 100)->orderBy('created_at', 'desc')->get() | Chain query conditions |
Post::create(['title' => 'New Post', 'body' => '...']); | Create and save record (mass assignment) |
$post->update(['title' => 'Updated']); | Update existing record |
$post->delete(); | Delete a record |
Post::with('comments')->get() | Eager load relationships |
Post::paginate(15) | Paginate results (15 per page) |
Migrations
| Command | Description |
|---|---|
php artisan make:migration create_posts_table | Create a new migration file |
$table->id(); | Auto-incrementing primary key |
$table->string('title'); | VARCHAR column |
$table->text('body'); | TEXT column for long content |
$table->integer('votes')->default(0); | Integer column with default value |
$table->boolean('is_active')->default(true); | Boolean column |
$table->foreignId('user_id')->constrained()->onDelete('cascade'); | Foreign key with cascade delete |
$table->timestamps(); | Add created_at and updated_at columns |
$table->softDeletes(); | Add deleted_at for soft deletes |
$table->unique('email'); | Add unique constraint |
Blade Templates
| Command | Description |
|---|---|
{{ $variable }} | Echo escaped variable (XSS safe) |
{!! $html !!} | Echo unescaped HTML |
@if($condition) ... @elseif ... @else ... @endif | Conditional rendering |
@foreach($items as $item) ... @endforeach | Loop through collection |
@forelse($items as $item) ... @empty ... @endforelse | Loop with empty state fallback |
@extends('layouts.app') | Extend a parent layout |
@section('content') ... @endsection | Define section content |
@yield('content') | Output section in layout |
@include('partials.header') | Include a partial view |
@csrf | Insert CSRF token hidden field in forms |
Middleware
| Command | Description |
|---|---|
php artisan make:middleware CheckAge | Create new middleware |
return $next($request); | Pass request to next middleware |
Route::middleware('auth')->group(...); | Apply middleware to route group |
Route::get('/profile', ...)->middleware('auth'); | Apply middleware to single route |
->middleware('auth:sanctum') | API authentication with Sanctum |
->middleware('throttle:60,1') | Rate limit: 60 requests per minute |
->middleware('verified') | Require email verification |
Validation
| Command | Description |
|---|---|
'name' => 'required|string|max:255' | Required string with max length |
'email' => 'required|email|unique:users' | Required unique email |
'password' => 'required|min:8|confirmed' | Password with confirmation field |
'age' => 'nullable|integer|between:1,120' | Optional integer in range |
'avatar' => 'image|mimes:jpg,png|max:2048' | Image upload validation (max 2MB) |
'tags' => 'array' | Must be an array |
'tags.*' => 'string|max:50' | Validate each array element |
'start_date' => 'date|after:today' | Date must be in the future |
@error('name') {{ $message }} @enderror | Display validation error in Blade |
Authentication
| Command | Description |
|---|---|
composer require laravel/breeze --dev | Install Breeze authentication starter kit |
php artisan breeze:install | Scaffold auth views and routes |
Auth::check() | Check if user is authenticated |
Auth::user() | Get currently authenticated user |
Auth::id() | Get authenticated user's ID |
auth()->login($user); | Manually log in a user |
auth()->logout(); | Log out the current user |
@auth ... @endauth | Blade directive — show if authenticated |
@guest ... @endguest | Blade directive — show if not authenticated |
Common Helpers
| Command | Description |
|---|---|
route('posts.show', ['post' => 1]) | Generate URL from named route |
url('/posts') | Generate full URL to path |
config('app.name') | Get configuration value |
env('APP_DEBUG', false) | Get environment variable with default |
collect([1, 2, 3])->map(fn ($i) => $i * 2) | Create and manipulate collection |
Str::slug('Hello World')e.g. 'hello-world' | Generate URL slug |
Str::uuid() | Generate a UUID string |
now() | Get current Carbon datetime instance |
cache()->remember('key', 60, fn () => ...) | Cache result for 60 seconds |
logger('Debug message', ['context' => $data]); | Write to log file |
📖 Free, searchable command reference. Bookmark this page for quick access.