Laravel
Laravel cheat sheet with Eloquent ORM, routing, Blade templates, middleware, authentication, and Artisan commands with code examples.
Other PHP Sheets
Setup & Artisan
Installation and Artisan commands
Installing Laravel and initial setup
# Install Laravel via Composer
composer create-project laravel/laravel myapp
cd myapp
# Or using Laravel installer
composer global require laravel/installer
laravel new myapp
# Start development server
php artisan serve
# Environment setup
cp .env.example .env
php artisan key:generate
# Database setup
php artisan migrate
php artisan db:seedEssential Artisan CLI commands
# Make commands
php artisan make:controller UserController
php artisan make:model User -m # With migration
php artisan make:migration create_users_table
php artisan make:seeder UserSeeder
php artisan make:factory UserFactory
php artisan make:middleware AuthMiddleware
php artisan make:request StoreUserRequest
# List routes
php artisan route:list
php artisan route:list --path=api
# Tinker (REPL)
php artisan tinker
>>> User::all();
>>> User::find(1);Routing
Defining routes and route handling
Defining routes and HTTP verbs
// routes/web.php
// Basic routes
Route::get('/', function () {
return view('welcome');
});
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);
// Route parameters
Route::get('/users/{id}', function ($id) {
return User::find($id);
});
// Optional parameters
Route::get('/posts/{id?}', function ($id = null) {
return $id ?? 'All posts';
});RESTful resource routing and API routes
// Resource routes (all CRUD operations)
Route::resource('posts', PostController::class);
// Partial resource routes
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
// API routes (routes/api.php)
Route::apiResource('posts', PostController::class);
// Nested resources
Route::resource('posts.comments', CommentController::class);Controllers
Controller patterns and request handling
Controller structure and request handling
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$users = User::paginate(15);
return view('users.index', compact('users'));
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
]);
$user = User::create($validated);
return redirect()->route('users.show', $user);
}
}Creating and using middleware
// Apply middleware to routes
Route::get('/admin', function () {
//
})->middleware('auth', 'admin');
// Middleware groups
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});
// Controller middleware
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
}
}Eloquent ORM
Database models and relationships
Eloquent model basics and querying
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'body', 'user_id'];
// Basic queries
$posts = Post::all();
$post = Post::find(1);
$post = Post::where('status', 'published')->first();
$posts = Post::where('views', '>', 100)->get();
// Create, update, delete
$post = Post::create(['title' => 'New Post']);
$post->update(['title' => 'Updated']);
$post->delete();
}Defining and using Eloquent relationships
// One to Many
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Usage
$user = User::find(1);
$posts = $user->posts;
$post = Post::find(1);
$author = $post->user;Query scopes and collection methods
// Local scope
class Post extends Model
{
public function scopePublished($query)
{
return $query->where('status', 'published');
}
public function scopePopular($query, $views = 100)
{
return $query->where('views', '>', $views);
}
}
// Usage
$posts = Post::published()->get();
$posts = Post::popular(500)->published()->get();Migrations & Schema
Database migrations and schema building
Creating and managing database migrations
// Create migration
php artisan make:migration create_posts_table
// Migration structure
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->foreignId('user_id')->constrained();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}Blade Templates
Blade templating engine and components
Blade syntax and directives
{{-- Comment --}}
{{-- Output --}}
{{ $variable }}
{!! $html !!} {{-- Unescaped --}}
{{-- Directives --}}
@if($user)
<p>{{ $user->name }}</p>
@elseif($guest)
<p>Guest</p>
@else
<p>No user</p>
@endif
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeachBlade layouts, components, and slots
{{-- Layout file: layouts/app.blade.php --}}
<!DOCTYPE html>
<html>
<head>
<title>@yield('title', 'Default Title')</title>
</head>
<body>
@section('sidebar')
Default sidebar
@show
<div class="container">
@yield('content')
</div>
</body>
</html>
{{-- Child view --}}
@extends('layouts.app')
@section('title', 'Page Title')
@section('content')
<p>Page content</p>
@endsectionAuthentication & Authorization
User authentication and authorization
User authentication with Laravel
// Check authentication
if (Auth::check()) {
// User is logged in
}
// Get authenticated user
$user = Auth::user();
$user = auth()->user();
$user = $request->user();
// Login
Auth::login($user);
Auth::loginUsingId(1);
// Logout
Auth::logout();Gates and policies for authorization
// Gates
Gate::define('edit-post', function ($user, $post) {
return $user->id === $post->user_id;
});
if (Gate::allows('edit-post', $post)) {
// User can edit
}
// Policies
php artisan make:policy PostPolicy --model=Post
// In controller
$this->authorize('update', $post);API Development
Building APIs with Laravel
Building RESTful APIs
// API routes (routes/api.php)
Route::apiResource('posts', PostController::class);
// API resource (transformation)
php artisan make:resource PostResource
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'author' => new UserResource($this->user),
];
}
}API authentication with Laravel Sanctum
// Install Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
// User model
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
// Create token
$token = $user->createToken('token-name');
return $token->plainTextToken;Testing
Testing Laravel applications
Writing and running tests
// Feature test
public function test_homepage_returns_successful_response()
{
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Welcome');
}
// Unit test
public function test_user_has_full_name()
{
$user = new User(['first_name' => 'John', 'last_name' => 'Doe']);
$this->assertEquals('John Doe', $user->fullName());
}
// Run tests
php artisan test
php artisan test --filter=UserTestAdvanced Features
Queues, events, caching, and more
Background job processing
// Create job
php artisan make:job ProcessPayment
// Dispatch job
ProcessPayment::dispatch($order);
ProcessPayment::dispatch($order)->delay(now()->addMinutes(10));
// Job class
class ProcessPayment implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function handle()
{
// Process payment
}
}Caching strategies in Laravel
// Store in cache
Cache::put('key', 'value', $seconds);
Cache::put('key', 'value', now()->addMinutes(10));
// Get from cache
$value = Cache::get('key');
$value = Cache::get('key', 'default');
// Remember pattern
$users = Cache::remember('users', 3600, function () {
return User::all();
});