Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 67 ยท Practice and Review

Laravel Cheat Sheet

A one-page Laravel 13 cheat sheet: Artisan commands, routing, validation rules, Eloquent, relationships, Blade, queues, caching and testing, with runnable stand-ins.

This page squeezes the whole Laravel course into one dense reference: the commands, methods and conventions you reach for every day, in short snippets you can scan in seconds. Keep it open while you build the projects, while you work through the practice exercises, or the evening before an interview.

Everything here targets Laravel 13 on PHP 8.4 or newer. Laravel itself cannot run on this site, so every framework snippet is a read-only block. The two live editors are plain-PHP stand-ins for ideas that confuse people most often: how validation rules written as strings are interpreted, and how a router turns a URL pattern into a match. Each section links to the lesson that explains the topic properly.

flowchart LR
    A["Request"] --> B["public/index.php"]
    B --> C["Middleware"]
    C --> D["Route"]
    D --> E["Controller"]
    E --> F["Model / Service"]
    E --> G["View or JSON"]
    G --> H["Response"]

The path of one request, from the front controller to the response (see the request lifecycle).

Artisan

Run php artisan list to see every command and php artisan help <command> for its options. Add --no-interaction in scripts.

Terminal
php artisan make:model Post -mfsc        # model + migration + factory + seeder + controller
php artisan make:model Post --all        # everything, including policy and form requests
php artisan make:controller PostController --resource --model=Post
php artisan make:migration add_slug_to_posts_table
php artisan make:request StorePostRequest
php artisan make:policy PostPolicy --model=Post
php artisan make:middleware EnsureIsAdmin
php artisan make:job SendWelcomeEmail
php artisan make:event OrderShipped
php artisan make:listener NotifyWarehouse --event=OrderShipped
php artisan make:mail InvoiceMail
php artisan make:notification InvoicePaid
php artisan make:command PruneDrafts
php artisan make:resource PostResource
php artisan make:test PostTest --pest

php artisan migrate                      # run pending migrations
php artisan migrate:rollback --step=1    # undo the last batch step
php artisan migrate:fresh --seed         # drop everything, migrate, seed (development only!)
php artisan migrate:status
php artisan db:seed

php artisan route:list                   # every route, with names and middleware
php artisan tinker                       # REPL inside your app
php artisan storage:link                 # public/storage -> storage/app/public
php artisan queue:work                   # process queued jobs
php artisan queue:failed
php artisan queue:retry all
php artisan schedule:work                # run the scheduler locally every minute
php artisan test --compact               # run the test suite
php artisan optimize                     # cache config, routes, views, events
php artisan optimize:clear               # remove those caches

Lessons: Artisan, Installation, Migrations.

Routing

Routes live in routes/web.php (sessions, CSRF) and routes/api.php (stateless, prefix /api).

PHP
use Illuminate\Support\Facades\Route;

Route::get('/', fn () => view('welcome'));
Route::post('/posts', [PostController::class, 'store']);
Route::match(['put', 'patch'], '/posts/{post}', [PostController::class, 'update']);
Route::view('/about', 'about');                       // a route that only renders a view
Route::redirect('/old', '/new', 301);

Route::get('/users/{id}', fn (string $id) => $id)->whereNumber('id');
Route::get('/blog/{slug?}', fn (?string $slug = null) => $slug);
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');

route('posts.show', ['post' => $post]);               // URL from a route name
to_route('posts.index');                              // redirect to a named route

Route::resource('posts', PostController::class);      // index, create, store, show, edit, update, destroy
Route::apiResource('posts', PostController::class);   // same without create and edit
Route::singleton('profile', ProfileController::class);

Route::middleware(['auth', 'verified'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/dashboard', DashboardController::class)->name('dashboard');
    });

Route::fallback(fn () => response()->view('404', status: 404));
  • with a type-hinted Post $post parameter is implicit model binding: Laravel loads the model by its key and answers 404 when it is missing. Use {post:slug} to bind by another column.
  • Route names make URLs refactor-safe: always link with route(), never with hard-coded paths.
  • php artisan route:cache speeds up production but breaks routes defined with closures, so use controllers in apps you cache.

Lessons: Routing basics, Groups and binding, Controllers, Middleware.

Try it: a router in 25 lines

The real router is far more capable, but the core idea is the same: compile placeholders into a regular expression and read the captures back as parameters. Optional parameters ({page?}) and named routes work the same way.

PHP A tiny router with parameters and names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Requests and responses

PHP
$request->input('name');                 // body or query string, with an optional default
$request->query('page', 1);              // query string only
$request->only(['title', 'body']);
$request->has('x');  $request->filled('x');  $request->boolean('active');
$request->file('avatar');  $request->user();  $request->ip();  $request->expectsJson();

return view('posts.show', compact('post'));
return response()->json(['ok' => true], 201);
return redirect()->route('posts.show', $post)->with('status', 'Saved!');
return back()->withErrors(['email' => 'Taken'])->withInput();
return response()->download($path);
abort(404);  abort_if(! $post->isPublished(), 403);

Lessons: Requests and responses, Sessions and flash.

Validation rules

PHP
$validated = $request->validate([
    'title'    => ['required', 'string', 'max:255'],
    'slug'     => ['required', 'alpha_dash', Rule::unique('posts', 'slug')->ignore($post)],
    'email'    => 'required|email',                       // pipe strings work too
    'age'      => ['nullable', 'integer', 'between:13,120'],
    'role'     => ['required', Rule::enum(Role::class)],
    'status'   => ['required', Rule::in(['draft', 'published'])],
    'password' => ['required', 'confirmed', Password::min(12)],
    'tags'     => ['array', 'max:5'],
    'tags.*'   => ['string', 'distinct', 'max:30'],
    'avatar'   => ['nullable', 'image', 'mimes:jpg,png', 'max:2048'],   // KB for files
    'ends_at'  => ['nullable', 'date', 'after:starts_at'],
]);
Rule Meaning
required, nullable, sometimes Must be present; may be null; validate only when the key exists
string, integer, numeric, boolean, array Type checks (integer accepts the string "5")
min:n, max:n, between:a,b, size:n Length for strings, value for numbers, count for arrays, KB for files
email, url, uuid, ip, json, regex:/.../ Format checks
in:a,b, not_in:a,b, exists:table,col, unique:table,col Membership and database checks
confirmed, same:field, different:field, accepted Comparing with other fields
required_if:field,value, required_with:field Conditional presence
date, after:x, before:x, date_format:Y-m-d Dates
file, image, mimes:..., mimetypes:..., dimensions:... Uploads
  • In a Blade view, @error('title') ... @enderror shows one field's message and old('title') refills the input.
  • For anything beyond a few rules, move them into a form request (php artisan make:request) with authorize() and rules().
  • Rules written as arrays can hold rule objects and closures; the pipe string cannot.

Lessons: Validation, Form requests and custom rules.

Try it: how pipe rules are read

Behind 'required|min:3|email' there is only a loop: split on |, split each rule on :, then call a small check for each name. This stand-in implements a handful of rules and collects every failing message, like Laravel's error bag.

PHP A validator that understands pipe rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Eloquent

PHP
class Post extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = ['title', 'slug', 'body', 'published_at'];

    protected function casts(): array
    {
        return ['published_at' => 'datetime', 'options' => 'array', 'status' => Status::class];
    }
}
PHP
Post::create(['title' => 'Hello']);          // needs $fillable
$post = Post::findOrFail($id);               // 404 in a route
$post->update(['title' => 'New']);
$post->delete();                             // soft delete when the trait is used
Post::updateOrCreate(['slug' => 'a'], ['title' => 'A']);
Post::firstOrCreate(['slug' => 'a'], ['title' => 'A']);
Post::upsert($rows, uniqueBy: ['slug'], update: ['title']);

Post::where('status', 'published')->orderByDesc('published_at')->limit(10)->get();
Post::query()->latest()->paginate(15);       // links via $posts->links()
Post::whereBelongsTo($user)->count();
Post::withTrashed()->find($id);   Post::onlyTrashed()->restore();
Post::chunkById(500, fn ($posts) => /* process */ null);
Convention Default
Table name Plural snake case: Post becomes posts
Primary key id, auto-incrementing
Timestamps created_at and updated_at, filled automatically
Foreign key Related model in snake case plus _id: user_id

Local scopes, accessors and casts keep query and formatting logic out of controllers. Mass assignment is blocked unless the column is listed in $fillable.

Lessons: Eloquent basics, Queries, Accessors and casts, Events and soft deletes, Collections.

Relationships

PHP
// users.id <- posts.user_id
class User extends Model { public function posts(): HasMany { return $this->hasMany(Post::class); } }
class Post extends Model { public function user(): BelongsTo { return $this->belongsTo(User::class); } }

public function profile(): HasOne { return $this->hasOne(Profile::class); }
public function roles(): BelongsToMany { return $this->belongsToMany(Role::class)->withPivot('expires_at')->withTimestamps(); }
public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); }
public function latestPost(): HasOne { return $this->hasOne(Post::class)->latestOfMany(); }
Type Foreign key lives on Read it with
hasOne / hasMany The other table $user->posts
belongsTo This table $post->user
belongsToMany A pivot table (role_user) $user->roles
hasManyThrough Two tables away $country->posts
morphOne / morphMany / morphToMany The other table (commentable_id, commentable_type) $post->comments
PHP
$user->posts()->create([...]);                       // set the foreign key for you
$user->roles()->attach($roleId);  $user->roles()->sync([1, 2, 3]);

User::with('posts.comments')->get();                 // eager load: 3 queries, not N+1
User::withCount('posts')->get();                     // adds posts_count
User::has('posts', '>=', 3)->get();
User::whereHas('posts', fn ($q) => $q->where('published', true))->get();
Model::preventLazyLoading(! app()->isProduction());  // throw on N+1 in development

Lessons: Relationships, Eager loading and N+1.

Blade

BLADE
{{ $title }}                       {{-- escaped --}}
{!! $trustedHtml !!}               {{-- raw: only for HTML you fully control --}}
@{{ vueOrAlpineSyntax }}           {{-- print braces literally --}}

@if ($posts->isEmpty()) ... @elseif (...) ... @else ... @endif
@forelse ($posts as $post)
    {{ $loop->iteration }}. {{ $post->title }}
@empty
    <p>No posts yet.</p>
@endforelse

@auth ... @endauth       @guest ... @endguest
@can('update', $post) ... @endcan
@isset($x)  @unless  @switch  @for  @while  @continue  @break

<x-layout title="Home">             {{-- anonymous or class component --}}
    <x-alert type="error" :message="$message" class="mt-4" />
</x-layout>

@props(['type' => 'info'])          {{-- first line of resources/views/components/alert.blade.php --}}
<div {{ $attributes->merge(['class' => "alert alert-$type"]) }}>{{ $slot }}</div>

<form method="POST" action="{{ route('posts.update', $post) }}">
    @csrf
    @method('PUT')
    <input name="title" value="{{ old('title', $post->title) }}">
    @error('title') <p>{{ $message }}</p> @enderror
</form>

@vite(['resources/css/app.css', 'resources/js/app.js'])
@include('partials.footer')   @stack('scripts')   @push('scripts') ... @endpush

Lessons: Blade, Layouts and components, Forms, CSRF and assets.

Queues, events, mail and scheduling

PHP
class SendWelcomeEmail implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public function backoff(): array { return [10, 60, 300]; }

    public function __construct(public User $user) {}

    public function handle(): void
    {
        Mail::to($this->user)->send(new WelcomeMail($this->user));
    }
}

SendWelcomeEmail::dispatch($user);                       // push to the queue
SendWelcomeEmail::dispatch($user)->onQueue('emails')->delay(now()->addMinutes(5));
Bus::chain([new A, new B])->dispatch();
Bus::batch([new A, new B])->then(fn () => null)->dispatch();

event(new OrderShipped($order));                         // listeners run (or queue themselves)
Mail::to($user)->queue(new InvoiceMail($order));
$user->notify(new InvoicePaid($invoice));                // channels come from via()

// routes/console.php
Schedule::command('posts:prune')->dailyAt('02:00')->onOneServer();
Schedule::job(new SendDigest)->weekdays()->at('08:00')->withoutOverlapping();
  • A queue worker keeps the old code in memory: restart workers after every deploy with php artisan queue:restart.
  • Production needs a real queue driver (Redis or database) plus a process supervisor, and one cron entry: * * * * * cd /path && php artisan schedule:run.
  • Dispatch inside a transaction with afterCommit so the worker never runs before the row exists.

Lessons: Queues, Events, Mail, Notifications, Scheduler.

Cache, config and auth in one glance

PHP
Cache::remember('stats', 600, fn () => Stats::compute());
Cache::forget('stats');
Cache::lock('import', 30)->block(5, fn () => runImport());
RateLimiter::for('api', fn (Request $r) => Limit::perMinute(60)->by($r->user()?->id ?: $r->ip()));

config('app.name');                // read config; env() belongs only inside config files
Auth::attempt(['email' => $email, 'password' => $password], remember: true);
Auth::user();  Auth::id();  Auth::check();  Auth::logout();
Gate::allows('update', $post);     $this->authorize('update', $post);
Hash::make($password);             Hash::check($plain, $hash);

Lessons: Caching, Configuration, Authentication, Gates and policies.

Testing with Pest

PHP
use App\Models\{Post, User};

it('lets an author publish a post', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->post('/posts', ['title' => 'Hello', 'body' => 'World'])
        ->assertRedirect('/posts');

    $this->assertDatabaseHas('posts', ['title' => 'Hello', 'user_id' => $user->id]);
});

it('rejects an empty title', function () {
    $this->actingAs(User::factory()->create())
        ->postJson('/api/posts', ['title' => ''])
        ->assertUnprocessable()
        ->assertJsonValidationErrors('title');
});

test('slugs are lowercase')->expect(fn () => Str::slug('Hello World'))->toBe('hello-world');

Mail::fake();  Queue::fake();  Event::fake();  Http::fake();  Storage::fake('public');
Mail::assertQueued(InvoiceMail::class);
$this->travel(2)->days();   $this->freezeTime();
  • Add pest()->extend(Tests\TestCase::class)->use(RefreshDatabase::class)->in('Feature') in tests/Pest.php so each feature test starts with a clean database.
  • Run one file with php artisan test --compact tests/Feature/PostTest.php or one test with --filter="rejects an empty title".

Lessons: Testing with Pest, HTTP and database tests, Faking and mocking.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command drops every table, runs all migrations again and runs the seeders?

    migrate:fresh drops all tables and re-runs every migration, and --seed then runs the seeders. Never run it against production data.
  2. 2. In the rule string 'required|min:3|email', what does the part after the colon in min:3 mean?

    Rules are separated by pipes, and a colon separates the rule name from its arguments, as the stand-in validator above shows.
  3. 3. A route is declared as Route::get('/posts/{post}', [PostController::class, 'show']) and the method signature is show(Post $post). What happens for an id that does not exist?

    Implicit route model binding loads the model by key and automatically returns a 404 when no row matches.
  4. 4. Why should you restart queue workers after a deployment?

    queue:work boots the framework once and reuses it, so it keeps running the code it loaded until you run php artisan queue:restart.

Summary

  • Generators (make:*), migrate, route:list, queue:work, schedule:work, test and optimize cover most of your Artisan use.
  • Routes map a verb and a URI pattern to a closure or controller action; name them and link with route().
  • Validation rules are strings or arrays of rules and rule objects; form requests keep them out of controllers.
  • Eloquent follows conventions for tables and keys; $fillable guards mass assignment and with() prevents N+1 queries.
  • Blade escapes {{ }} by default; use components, @csrf and old() in forms.
  • Queues, events, mail and notifications move slow work out of the request; restart workers after deploys.
  • Pest feature tests plus factories, actingAs, assertDatabaseHas and fakes cover most of an app.

Next, test your readiness for the next step in Laravel interview questions.