Laravel Framework

Introduction to Laravel & MVC Architecture

18 min Lesson 1 of 45

What is Laravel?

Laravel is a free, open-source PHP web application framework created by Taylor Otwell in 2011. It follows the Model-View-Controller (MVC) architectural pattern and provides an elegant, expressive syntax that makes web development faster and more enjoyable.

Why Laravel? Laravel is currently the most popular PHP framework, known for its elegant syntax, comprehensive documentation, and vibrant community. It powers thousands of applications worldwide, from small startups to enterprise solutions.

Key Features of Laravel

  • Eloquent ORM: Beautiful, simple ActiveRecord implementation for working with databases
  • Blade Templating: Powerful templating engine with template inheritance
  • Artisan Console: Command-line interface for common development tasks
  • Database Migrations: Version control for your database schema
  • Authentication & Authorization: Built-in user authentication scaffolding
  • Routing: Elegant, expressive routing system
  • Queue System: Unified API for background job processing
  • Event Broadcasting: Real-time event broadcasting with WebSockets
  • Testing: PHPUnit integration and testing helpers

Understanding MVC Architecture

MVC (Model-View-Controller) is a design pattern that separates application logic into three interconnected components. This separation helps organize code and makes applications more maintainable.

The MVC Pattern in Laravel

Request Flow in Laravel: User Request → Routes → Controller → Model → Database ↓ View ← Controller ↓ Response to User

1. Model (M)

Models represent your data and business logic. In Laravel, models typically interact with your database using Eloquent ORM.

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Article extends Model { // Define which attributes can be mass-assigned protected $fillable = ['title', 'content', 'author_id']; // Define relationship with User model public function author() { return $this->belongsTo(User::class, 'author_id'); } // Business logic methods public function publish() { $this->published_at = now(); $this->save(); } }

2. View (V)

Views handle the presentation layer. In Laravel, views are written using the Blade templating engine and stored in the resources/views directory.

<!-- resources/views/articles/show.blade.php --> <html> <head> <title>{{ $article->title }}</title> </head> <body> <h1>{{ $article->title }}</h1> <p>By {{ $article->author->name }}</p> <div>{!! $article->content !!}</div> </body> </html>

3. Controller (C)

Controllers handle user requests, interact with models, and return views. They act as intermediaries between models and views.

<?php namespace App\Http\Controllers; use App\Models\Article; use Illuminate\Http\Request; class ArticleController extends Controller { public function show($id) { // Retrieve article from database using Model $article = Article::with('author')->findOrFail($id); // Return view with data return view('articles.show', compact('article')); } public function store(Request $request) { // Validate incoming request $validated = $request->validate([ 'title' => 'required|max:255', 'content' => 'required', ]); // Create new article using Model $article = Article::create($validated); // Redirect with success message return redirect() ->route('articles.show', $article) ->with('success', 'Article created successfully!'); } }
Best Practice: Keep your controllers thin. Business logic should live in models, service classes, or action classes. Controllers should primarily handle HTTP concerns like validation, redirects, and response formatting.

Laravel Ecosystem

Laravel offers a rich ecosystem of official packages and tools that extend its functionality:

Official Laravel Packages

  • Laravel Breeze: Minimal authentication scaffolding (login, registration, password reset)
  • Laravel Jetstream: Robust authentication scaffolding with teams and 2FA
  • Laravel Sanctum: API token authentication for SPAs and mobile apps
  • Laravel Passport: Full OAuth2 server implementation
  • Laravel Horizon: Beautiful dashboard for monitoring Redis queues
  • Laravel Telescope: Elegant debug assistant for development
  • Laravel Octane: Supercharge performance with Swoole or RoadRunner
  • Laravel Sail: Docker development environment
  • Laravel Socialite: OAuth authentication with Facebook, Twitter, Google, etc.

Laravel Forge & Vapor

Laravel Forge: Server management and deployment platform for Laravel applications. It provisions and deploys applications on DigitalOcean, AWS, Linode, and more.

Laravel Vapor: Serverless deployment platform for Laravel, powered by AWS Lambda.

Laravel Directory Structure

Understanding Laravel's directory structure is crucial for navigating and organizing your application:

laravel-app/ ├── app/ # Application core code │ ├── Console/ # Artisan commands │ ├── Exceptions/ # Exception handler │ ├── Http/ │ │ ├── Controllers/ # Controllers │ │ ├── Middleware/ # HTTP middleware │ │ └── Requests/ # Form requests │ ├── Models/ # Eloquent models │ └── Providers/ # Service providers ├── bootstrap/ # Framework bootstrap files ├── config/ # Configuration files ├── database/ │ ├── factories/ # Model factories │ ├── migrations/ # Database migrations │ └── seeders/ # Database seeders ├── public/ # Web server document root │ ├── index.php # Entry point │ └── assets/ # Compiled assets ├── resources/ │ ├── css/ # Raw CSS files │ ├── js/ # Raw JavaScript files │ └── views/ # Blade templates ├── routes/ │ ├── web.php # Web routes │ ├── api.php # API routes │ └── console.php # Console routes ├── storage/ │ ├── app/ # Application files │ ├── framework/ # Framework files │ └── logs/ # Application logs ├── tests/ # Automated tests ├── vendor/ # Composer dependencies ├── .env # Environment configuration ├── artisan # Artisan CLI tool └── composer.json # Composer dependencies

Key Directories Explained

app/Http/Controllers: Contains all your controller classes that handle HTTP requests.

app/Models: Contains all your Eloquent model classes representing database tables.

resources/views: Contains all your Blade template files for rendering HTML.

routes/web.php: Defines all web routes for your application.

public/: The only directory accessible from the web. Contains index.php entry point and assets.

database/migrations: Version control for your database schema.

Security Note: Never commit your .env file to version control! It contains sensitive information like database credentials and API keys. Always use .env.example as a template.

Artisan Console Basics

Artisan is Laravel's command-line interface. It provides numerous helpful commands for development.

Common Artisan Commands

# View all available commands php artisan list # Start development server php artisan serve # Create a new controller php artisan make:controller ArticleController # Create a new model with migration php artisan make:model Article -m # Run database migrations php artisan migrate # Rollback last migration php artisan migrate:rollback # Create a new seeder php artisan make:seeder UserSeeder # Clear application cache php artisan cache:clear # Clear configuration cache php artisan config:clear # Create a symbolic link from public/storage to storage/app/public php artisan storage:link # Enter tinker REPL (interactive shell) php artisan tinker
Tinker Tip: Use php artisan tinker to interact with your application in a REPL environment. It's perfect for testing models, querying databases, and debugging without writing temporary routes.

Creating Custom Artisan Commands

You can create your own custom Artisan commands for repetitive tasks:

# Generate a new command php artisan make:command SendNewsletterCommand # This creates app/Console/Commands/SendNewsletterCommand.php

The Laravel Request Lifecycle

Understanding how Laravel processes a request helps you build better applications:

1. Entry Point (public/index.php) ↓ 2. Bootstrap Laravel Framework ↓ 3. Load Service Providers ↓ 4. Route the Request ↓ 5. Execute Middleware ↓ 6. Dispatch to Controller/Closure ↓ 7. Generate Response ↓ 8. Send Response to Browser

Service Providers

Service providers are the central place for bootstrapping your application. They register services, bind classes into the service container, and configure your application.

<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. */ public function register(): void { // Register bindings in the container $this->app->bind('App\Contracts\PaymentGateway', function ($app) { return new \App\Services\StripePaymentGateway(); }); } /** * Bootstrap any application services. */ public function boot(): void { // Perform actions after all services registered View::share('appName', config('app.name')); } }

Practice Exercise 1: Understanding MVC

Explain in your own words what each component does:

  1. What is the role of a Model in Laravel?
  2. What is the role of a View in Laravel?
  3. What is the role of a Controller in Laravel?
  4. Why is separating these concerns beneficial?

Practice Exercise 2: Directory Structure

Answer these questions about Laravel's structure:

  1. Where would you create a new controller class?
  2. Where would you define database table structure changes?
  3. Where would you store Blade template files?
  4. Why should the .env file never be committed to Git?

Practice Exercise 3: Artisan Commands

Research and write down what these Artisan commands do:

  1. php artisan make:model Post -mcr
  2. php artisan migrate:fresh --seed
  3. php artisan route:list
  4. php artisan optimize

Summary

In this lesson, you've learned:

  • What Laravel is and why it's one of the most popular PHP frameworks
  • The MVC architectural pattern and how it's implemented in Laravel
  • Laravel's rich ecosystem of official packages and tools
  • The directory structure and purpose of key directories
  • Basic Artisan console commands for development
  • The request lifecycle in Laravel

In the next lesson, we'll install Laravel and set up your development environment so you can start building your first Laravel application!