Understand Laravel architecture, the MVC pattern, and the modern PHP ecosystem powered by Composer.
Understand Laravel architecture, the MVC pattern, and the modern PHP ecosystem powered by Composer.
Laravel is a powerful, elegant PHP framework designed for building modern web applications. Created by Taylor Otwell in 2011, Laravel has become the most popular PHP framework, powering millions of websites and applications worldwide.
Laravel is a free, open-source PHP web framework that follows the Model-View-Controller (MVC) architectural pattern. It provides a robust set of tools and features that make web development faster, easier, and more enjoyable.
Laravel's philosophy is built on several core principles:
1✓ Elegant Syntax - Write beautiful, expressive code
2✓ Powerful ORM (Eloquent) - Work with databases naturally
3✓ Built-in Authentication - Secure user systems out of the box
4✓ Robust Ecosystem - Extensive packages and tools
5✓ Active Community - Large, helpful developer community
6✓ Comprehensive Documentation - Well-written, detailed docs
7✓ Modern Features - Queues, broadcasting, events, and moreLaravel follows the Model-View-Controller (MVC) pattern, which separates application logic into three interconnected components:
The Model represents the application's data and business logic. In Laravel, models typically interact with the database using Eloquent ORM.
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class User extends Model
8{
9 // Define which attributes are mass-assignable
10 protected $fillable = [
11 'name',
12 'email',
13 'password',
14 ];
15
16 // Define relationships
17 public function posts()
18 {
19 return $this->hasMany(Post::class);
20 }
21
22 // Business logic methods
23 public function isAdmin(): bool
24 {
25 return $this->role === 'admin';
26 }
27}Responsibilities:
Views handle the presentation of data. Laravel uses the Blade templating engine to create dynamic, reusable views.
1<!-- resources/views/users/profile.blade.php -->
2@extends('layouts.app')
3
4@section('content')
5 <div class="profile">
6 <h1>{{ $user->name }}</h1>
7 <p>Email: {{ $user->email }}</p>
8
9 @if($user->isAdmin())
10 <span class="badge">Administrator</span>
11 @endif
12
13 <h2>Recent Posts</h2>
14 @foreach($user->posts as $post)
15 <article>
16 <h3>{{ $post->title }}</h3>
17 <p>{{ $post->excerpt }}</p>
18 </article>
19 @endforeach
20 </div>
21@endsectionResponsibilities:
Controllers handle HTTP requests, interact with models, and return responses (often views).
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\User;
6use Illuminate\Http\Request;
7
8class UserController extends Controller
9{
10 public function show(User $user)
11 {
12 // Laravel automatically finds the user by ID (Route Model Binding)
13
14 // Load the user's posts
15 $user->load('posts');
16
17 // Return the view with data
18 return view('users.profile', [
19 'user' => $user
20 ]);
21 }
22
23 public function update(Request $request, User $user)
24 {
25 // Validate input
26 $validated = $request->validate([
27 'name' => 'required|string|max:255',
28 'email' => 'required|email|unique:users,email,' . $user->id,
29 ]);
30
31 // Update the model
32 $user->update($validated);
33
34 // Redirect with success message
35 return redirect()
36 ->route('users.show', $user)
37 ->with('success', 'Profile updated successfully!');
38 }
39}Responsibilities:
1┌─────────┐ ┌────────────┐ ┌───────┐ ┌──────┐
2│ Request │─────>│ Router │─────>│ Ctrl │─────>│Model │
3└─────────┘ └────────────┘ └───────┘ └──────┘
4 │ │
5 │ │
6 v │
7┌──────────┐ ┌──────────┐ ┌───────┐ │
8│ Response │<────│ View │<─────│ Ctrl │<──────────┘
9└──────────┘ └──────────┘ └───────┘
10
11Flow:
121. User makes HTTP request
132. Router matches request to controller method
143. Controller requests data from Model
154. Model interacts with database
165. Controller passes data to View
176. View renders HTML
187. Response sent back to userLaravel is more than just a framework - it's a complete ecosystem of tools and packages.
Laravel's elegant database abstraction layer.
1// Simple, expressive database queries
2$users = User::where('active', true)
3 ->orderBy('created_at', 'desc')
4 ->take(10)
5 ->get();
6
7// Relationships are intuitive
8$user = User::with('posts', 'comments')->find(1);Powerful, intuitive templating engine.
1@if(auth()->check())
2 <p>Welcome, {{ auth()->user()->name }}!</p>
3@else
4 <a href="{{ route('login') }}">Login</a>
5@endifCommand-line interface for common tasks.
1# Create a new controller
2php artisan make:controller UserController
3
4# Run database migrations
5php artisan migrate
6
7# Clear application cache
8php artisan cache:clear
9
10# Start development server
11php artisan serveBuilt-in authentication system.
1// Register a new user
2Auth::attempt(['email' => $email, 'password' => $password]);
3
4// Check if user is authenticated
5if (Auth::check()) {
6 $user = Auth::user();
7}
8
9// Logout
10Auth::logout();API token authentication for SPAs and mobile apps.
Queue monitoring dashboard.
Debugging and insight tool for local development.
Full OAuth2 server implementation.
OAuth authentication with Facebook, Twitter, Google, GitHub, etc.
Subscription billing integration with Stripe and Paddle.
Docker-based development environment.
1# Start Laravel Sail
2./vendor/bin/sail up
3
4# Run Artisan commands
5./vendor/bin/sail artisan migrateLightweight development environment for macOS.
Pre-packaged Vagrant box with all tools needed.
Laravel relies heavily on Composer, PHP's dependency manager. Understanding Composer is essential for Laravel development.
Composer manages PHP project dependencies, similar to npm for JavaScript or pip for Python.
This file defines your project's dependencies:
1{
2 "name": "laravel/laravel",
3 "type": "project",
4 "require": {
5 "php": "^8.1",
6 "laravel/framework": "^11.0",
7 "guzzlehttp/guzzle": "^7.0"
8 },
9 "require-dev": {
10 "phpunit/phpunit": "^10.0",
11 "laravel/telescope": "^4.0"
12 },
13 "autoload": {
14 "psr-4": {
15 "App\\": "app/",
16 "Database\\Seeders\\": "database/seeders/"
17 }
18 }
19}1# Install all dependencies
2composer install
3
4# Update dependencies
5composer update
6
7# Add a new package
8composer require vendor/package
9
10# Add a development package
11composer require --dev vendor/package
12
13# Remove a package
14composer remove vendor/package
15
16# Dump autoload files
17composer dump-autoloadComposer follows PSR-4 autoloading standard:
1// File: app/Services/PaymentService.php
2namespace App\Services;
3
4class PaymentService
5{
6 // Class code...
7}
8
9// Autoloaded as: App\Services\PaymentService
10// No manual require/include needed!
11use App\Services\PaymentService;
12
13$payment = new PaymentService();Laravel:
Symfony:
Laravel:
CodeIgniter:
Laravel:
Yii:
Choose Laravel when you need:
1┌──────────────────────────────────────────────────┐
2│ HTTP Request │
3└────────────────────┬─────────────────────────────┘
4 │
5 v
6┌──────────────────────────────────────────────────┐
7│ public/index.php │
8│ (Entry Point) │
9└────────────────────┬─────────────────────────────┘
10 │
11 v
12┌──────────────────────────────────────────────────┐
13│ Bootstrap Application │
14│ (Load config, services, etc.) │
15└────────────────────┬─────────────────────────────┘
16 │
17 v
18┌──────────────────────────────────────────────────┐
19│ Service Providers │
20│ (Register services, bindings) │
21└────────────────────┬─────────────────────────────┘
22 │
23 v
24┌──────────────────────────────────────────────────┐
25│ Middleware │
26│ (Authentication, CSRF, etc.) │
27└────────────────────┬─────────────────────────────┘
28 │
29 v
30┌──────────────────────────────────────────────────┐
31│ Router │
32│ (Match route to controller) │
33└────────────────────┬─────────────────────────────┘
34 │
35 v
36┌──────────────────────────────────────────────────┐
37│ Controller │
38│ (Handle request, return response) │
39└────────────────────┬─────────────────────────────┘
40 │
41 v
42┌──────────────────────────────────────────────────┐
43│ HTTP Response │
44└──────────────────────────────────────────────────┘Laravel's service container is a powerful dependency injection container:
1// Binding in a Service Provider
2$this->app->singleton(PaymentGateway::class, StripeGateway::class);
3
4// Resolving from container (automatic injection)
5class OrderController extends Controller
6{
7 public function __construct(
8 private PaymentGateway $gateway
9 ) {
10 // Laravel automatically injects the bound implementation
11 }
12}Service providers are the central place for application bootstrapping:
1namespace App\Providers;
2
3use Illuminate\Support\ServiceProvider;
4
5class AppServiceProvider extends ServiceProvider
6{
7 public function register(): void
8 {
9 // Register bindings in the container
10 $this->app->singleton(Cache::class, function ($app) {
11 return new RedisCache($app->make('redis'));
12 });
13 }
14
15 public function boot(): void
16 {
17 // Perform application bootstrapping
18 View::share('appName', config('app.name'));
19 }
20}Facades provide a static interface to classes in the service container:
1// Using facade
2use Illuminate\Support\Facades\Cache;
3
4Cache::put('key', 'value', 3600);
5$value = Cache::get('key');
6
7// Equivalent to:
8app('cache')->put('key', 'value', 3600);1// Named Arguments (PHP 8.0+)
2User::create(
3 name: 'John Doe',
4 email: '[email protected]',
5 password: Hash::make('password')
6);
7
8// Constructor Property Promotion (PHP 8.0+)
9class UserService
10{
11 public function __construct(
12 private UserRepository $repository,
13 private EmailService $emailService
14 ) {}
15}
16
17// Enums (PHP 8.1+)
18enum UserRole: string
19{
20 case ADMIN = 'admin';
21 case USER = 'user';
22 case GUEST = 'guest';
23}
24
25// Readonly Properties (PHP 8.1+)
26class User extends Model
27{
28 public readonly string $email;
29}Laravel is a comprehensive, modern PHP framework that makes web development elegant and enjoyable. Key takeaways:
In the next lesson, we'll install Laravel and explore its project structure in detail.
Your progress is saved in this browser, on this device only.