Laravel: The Architect's Toolkit
Build robust applications with the world's most loved PHP framework.
Chapter 1: The Master Architect's Studio
**Laravel** is a PHP Framework. It's a magic studio that gives you all the tools and blueprints you need to build giant websites. It follows the **MVC (Model-View-Controller)** pattern, which is a way of organizing your code so it doesn't become a mess.
Chapter 2: The Request Life Cycle
The **Life Cycle** is the journey a request takes. It starts at `public/index.php`, goes through the **HTTP Kernel**, hits the **Service Providers**, and finally finds a **Route**. It's like a guest being checked by guards before they meet the King.
Chapter 3: Map of the City (Routing)
// Simple Road
Route::get('/hello', function () {
return 'Welcome, traveler!';
});
// Road with parameters
Route::get('/castle/{id}', function ($id) {
return "Entering Castle Number " . $id;
});
// Named roads
Route::get('/throne-room', function() { ... })->name('throne');
Chapter 4: Middleware Security
**Middleware** are guards that stand in front of your routes. They check things like: "Is this user logged in?" or "Is their age over 18?"
Route::get('/vault', function () {
return "Behold, the gold!";
})->middleware('auth');
Chapter 5: CSRF Protection
Every time you make a form, you must include a magic `` tag. It's a secret token that proves the form actually came from your website and not a hacker's fake site.
Chapter 6: The Magic Portal (Controllers)
// Generate with: php artisan make:controller KnightController
public function index() {
$knights = Knight::all();
return view('knights.index', compact('knights'));
}
Chapter 7: Requests & Responses
Laravel provides a `Request` object that contains everything: what the user typed in a form, their IP address, and even uploaded files.
Chapter 8: The Artist's Canvas (Blade)
@extends('layouts.app')
@section('content')
<h1>Welcome to the Castle</h1>
@foreach($items as $item)
<li>{{ $item }}</li>
@endforeach
@endsection
Chapter 9: Component Magic
Components are reusable pieces of UI. You define them once and use them everywhere like custom HTML tags: `<x-alert type="danger" />`.
Chapter 10: The Secret Vault (.env)
The `.env` file is where you store secrets: database passwords, API keys, and app settings. Never share this file!
Chapter 11: Database Blueprints (Migrations)
Schema::create('knights', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('castle_id')->constrained();
$table->timestamps();
});
Chapter 12: The Smart Librarian (Eloquent)
**Eloquent ORM** lets you talk to your database like it's a PHP object. `Knight::all()` gets every knight. `Knight::where('strength', '>', 10)->get()` gets only the strong ones.
Chapter 13: One-to-One Relationships
// In Knight.php
public function horse() {
return $this->hasOne(Horse::class);
}
// In Horse.php
public function knight() {
return $this->belongsTo(Knight::class);
}
Chapter 14: One-to-Many Relationships
// In Castle.php
public function knights() {
return $this->hasMany(Knight::class);
}
Chapter 15: Many-to-Many Relationships
// In Knight.php
public function guilds() {
return $this->belongsToMany(Guild::class);
}
Chapter 16: Polymorphic Relationships
**One-to-Many Polymorphic:** A single model can belong to multiple other models on a single association.
// In Comment.php
public function commentable() {
return $this->morphTo();
}
// In Post.php
public function comments() {
return $this->morphMany(Comment::class, 'commentable');
}
// In Video.php
public function comments() {
return $this->morphMany(Comment::class, 'commentable');
}
// The database table 'comments' needs:
// - commentable_id (integer)
// - commentable_type (string, e.g., 'App\Models\Post')
**Many-to-Many Polymorphic:** Think of "Tags". Both Posts and Videos can share the same Tags.
// In Tag.php
public function posts() {
return $this->morphedByMany(Post::class, 'tagable');
}
// In Post.php
public function tags() {
return $this->morphToMany(Tag::class, 'tagable');
}
Chapter 17: Collection Magic
When you get data from Eloquent, it's not a boring array—it's a **Collection Object** on steroids. You can chain dozens of methods to transform data without writing loops.
$names = User::all()
->filter(fn($user) => $user->active)
->sortBy('created_at')
->map(fn($user) => strtoupper($user->name))
->pluck('name'); // Just the names!
Chapter 18: The Sorting Room (Validation)
Never trust user input. Laravel's validation is powerful and expressive. You can use it in Controllers or dedicated **FormRequest** classes.
$validated = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'category_id' => 'exists:categories,id', // Must exist in DB
'email' => 'email:rfc,dns' // Real email check
]);
Chapter 19: The Guarded Gates (Auth)
Laravel provides high-level "Guards" and "Providers". Guards define how users are authenticated (Session vs Token). Providers define how users are retrieved from your database.
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// The user is logged in...
return redirect()->intended('dashboard');
}
Auth::logout();
Chapter 20: Gates & Policies
**Gates** are great for simple actions. **Policies** are organized classes for Model-specific logic.
// In AuthServiceProvider.php
Gate::define('update-post', function (User $user, Post $post) {
return $user->id === $post->user_id;
});
// Using a Policy in a Controller
public function update(Request $request, Post $post) {
$this->authorize('update', $post);
// Logic...
}
Chapter 21: The Magic Scroll (Artisan)
Artisan is more than just a generator. You can build your own custom commands to automate kingdom chores.
php artisan make:command SendWeeklyReport
php artisan list
php artisan tinker // Interactive REPL to talk to your DB
Chapter 22: The Messenger (Mail)
Laravel uses **Mailable** classes. You can use Markdown to write beautiful emails that automatically look good on all devices.
// Create the mailer
php artisan make:mail WelcomeMail
// Send it
Mail::to($request->user())->send(new WelcomeMail($user));
// Queue it (background)
Mail::to($request->user())->queue(new WelcomeMail($user));
Chapter 23: Notifications
Write one notification class, deliver it via Mail, SMS (Vonage/Twilio), Slack, and Database. Laravel handles the formatting for each channel.
public function via($notifiable) {
return ['mail', 'database', 'slack'];
}
// Triggering
$user->notify(new InvoicePaid($invoice));
Chapter 24: Heavy Lifters (Jobs/Queues)
Laravel supports Redis, Amazon SQS, and Database as queue drivers. Background workers process these jobs independently of the web request.
// Dispatching a Job
ProcessVideo::dispatch($video)->onQueue('high');
// In ProcessVideo.php (The Job)
public function handle() {
// Heavy computation here...
}
Chapter 25: The Town Crier (Events)
**Events** allow you to "Broadcast" that something happened. **Listeners** then "Subscribe" to those events to react.
// In EventServiceProvider.php
protected $listen = [
OrderPlaced::class => [
SendOrderEmail::class,
UpdateInventory::class,
],
];
// Firing
event(new OrderPlaced($order));
Chapter 26: The Hidden Spy (Observers)
**Observers** are perfect for logic that should ALWAYS run when a model changes, like generating a UUID or clearing a cache.
class UserObserver {
public function creating(User $user) {
$user->activation_token = Str::random(40);
}
}
// Register in AppServiceProvider
User::observe(UserObserver::class);
Chapter 27: Service Providers
Every "Service" in Laravel (Auth, DB, Mail) is registered via a Service Provider. They have two main methods:
- register(): ONLY bind things into the Service Container. No logic.
- boot(): Everything else. You can access other services here because they are all registered by now.
Chapter 28: The Service Container
Instead of manually creating objects (`new Tool()`), you ask the Container for them. This allows you to "Swap" a tool for a "Fake" one during testing.
// Binding
app()->bind('SmsService', function ($app) {
return new TwilioService(config('services.twilio.key'));
});
// Resolving (In a Controller)
public function send(SmsService $sms) {
$sms->send('Hello!');
}
Chapter 29: The Magic API Bridge
Use **API Resources** to avoid exposing raw DB columns. They act as a transformation layer between your Models and the JSON response.
public function toArray($request) {
return [
'id' => $this->id,
'user_name' => $this->name,
'secret_data' => $this->when($request->user()->isAdmin(), 'HIDDEN'),
];
}
Chapter 30: Task Scheduling
The scheduler runs every minute on your server via a single Cron entry. You define the frequency inside `routes/console.php` or `app/Console/Kernel.php`.
Schedule::command('emails:send')->daily();
Schedule::job(new Heartbeat)->everyFiveMinutes();
Schedule::call(function () {
DB::table('recent_users')->delete();
})->weekly();
Need to clean your database every night at 3 AM? Use the **Scheduler**. No more messing with server Cron jobs!
The Kingdom is Built
You have completed the Architect's Handbook. You are no longer just a builder; you are a Master of the Craft. Go forth and create something legendary!