Laravel: The Architect's Toolkit

Build robust applications with the world's most loved PHP framework.

Chapter 1: The Master Architect's Studio

You've learned how to make bricks (HTML), how to paint them (CSS), and how to build a simple room (PHP). But what if you want to build a whole Kingdom?

**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

When a visitor knocks on your castle's front door, where do they go first?

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)

Routes are the roads of your kingdom. They tell the visitor where to go.
php
// 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

You don't want just anyone walking into the vault. You need a guard.

**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?"

php
Route::get('/vault', function () {
    return "Behold, the gold!";
})->middleware('auth');

Chapter 5: CSRF Protection

Some villains try to forge the King's signature. Laravel has a magic seal called **CSRF**.

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)

Instead of putting all logic on the road, we put it in rooms called Controllers.
php
// Generate with: php artisan make:controller KnightController
public function index() {
    $knights = Knight::all();
    return view('knights.index', compact('knights'));
}

Chapter 7: Requests & Responses

When a guest asks for something (Request), you must give them an answer (Response).

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)

**Blade** is the magic painting tool. It makes HTML fun and powerful.
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

Why build the same "Alert Box" 10 times? Build it once as a **Component**.

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)

Migrations are PHP files that describe your database tables.
php
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

A Knight has exactly one Horse.
php
// 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

A Castle has many Knights.
php
// In Castle.php
public function knights() {
    return $this->hasMany(Knight::class);
}

Chapter 15: Many-to-Many Relationships

A Knight can join many Guilds, and a Guild has many Knights. We need a "Pivot Table" to connect them.
php
// In Knight.php
public function guilds() {
    return $this->belongsToMany(Guild::class);
}

Chapter 16: Polymorphic Relationships

Imagine a "Comment" system. Both a **Post** and a **Video** can have comments. Instead of making two comment tables, we make one "Polymorphic" table that can attach to anything.

**One-to-Many Polymorphic:** A single model can belong to multiple other models on a single association.

php
// 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.

php
// 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.

php
$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.

php
$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.

php
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    // The user is logged in...
    return redirect()->intended('dashboard');
}

Auth::logout();

Chapter 20: Gates & Policies

Authentication is "Who are you?". Authorization is "What can you do?".

**Gates** are great for simple actions. **Policies** are organized classes for Model-specific logic.

php
// 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.

bash
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.

php
// 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.

php
public function via($notifiable) {
    return ['mail', 'database', 'slack'];
}

// Triggering
$user->notify(new InvoicePaid($invoice));

Chapter 24: Heavy Lifters (Jobs/Queues)

Don't make the user wait for a slow task. Dispatch a **Job** to the background.

Laravel supports Redis, Amazon SQS, and Database as queue drivers. Background workers process these jobs independently of the web request.

php
// 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.

php
// 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.

php
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

The brain that resolves all dependencies.

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.

php
// 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.

php
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`.

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!

End_of_Module_01
Return to Archives