Skip to content
Home
Laravel Guide: PHP Framework with Eloquent and Blade

Laravel Guide: PHP Framework with Eloquent and Blade

Backend Web Frameworks Backend Web Frameworks 8 min read 1551 words Beginner ExcellentWiki Editorial Team

Laravel is the most popular PHP framework, known for its elegant syntax, expressive tooling, and comprehensive ecosystem. Created by Taylor Otwell in 2011, Laravel has transformed PHP development by introducing modern conventions inspired by Rails and .NET. Laravel powers applications at BBC, Pfizer, and Crowdcube, and its ecosystem — Forge, Vapor, Nova, Horizon, Spark, and Cashier — provides a vertically integrated platform for the entire application lifecycle. Laravel’s adoption continues growing with over 100 million total downloads as of 2024.

Eloquent ORM and Database Management

Eloquent is Laravel’s Active Record ORM, providing an intuitive interface for database operations. Each database table has a corresponding Model class that handles queries, relationships, and serialization. Eloquent’s relationship system supports one-to-one, one-to-many, many-to-many, has-many-through, polymorphic relations, and many-to-many polymorphic relations. This comprehensive relationship API covers virtually every data modeling scenario.

The Eloquent query builder chains methods to construct SQL queries programmatically. Scopes encapsulate common query constraints — scopeActive() returns only active records. Local scopes are defined as methods on the model class, while global scopes apply automatically to all queries on that model. Accessors and mutators transform attribute values on read and write — getNameAttribute() automatically converts $model->name access. Casting handles type conversion — protected $casts = ['is_admin' => 'boolean', 'metadata' => 'array'].

Migrations track database schema changes in version-controlled PHP files. Each migration file contains up() and down() methods for applying and rolling back changes. Laravel’s schema builder supports all common database operations — creating tables, adding columns, indexes, foreign keys, and full-text indexes. The artisan migrate command applies pending migrations, and artisan migrate:rollback reverses the last batch. Laravel’s schema builder supports MySQL, PostgreSQL, SQLite, and SQL Server.

Blade Template Engine

Blade is Laravel’s template engine that compiles templates to plain PHP for performance. Blade provides template inheritance with @extends and @section directives, control structures with @if, @foreach, @while, and form handling with @csrf and @method. Blade components encapsulate reusable UI elements with slots and attributes. Components can be class-based with PHP logic or anonymous with only templates.

Blade’s control flow includes @auth and @guest directives for authentication state, @error for validation error display, and @production for environment-specific code. The @push and @stack directives manage CSS and JavaScript injection into layout sections. Blade components with @props provide type-safe component interfaces using PHP 8.1 enums for component variants.

Component-based architecture in Laravel mirrors frontend component patterns. PHP components handle logic and templating, while Livewire and Alpine.js provide interactivity without writing JavaScript. Livewire components render on the server and update via AJAX, providing dynamic UI with Laravel’s backend logic. Alpine.js adds client-side interactivity for UI transitions, dropdowns, and modals.

Artisan CLI

Artisan is Laravel’s command-line interface that handles code generation, database management, queue operations, and scheduled tasks. php artisan make:model User -m creates a model with a migration file. php artisan make:controller UserController --resource generates a RESTful controller with standard methods. Artisan commands follow a consistent naming convention and accept options for customization.

Custom Artisan commands extend the CLI for application-specific tasks. Commands define a $signature for input specification, $description for help text, and a handle() method for execution. Artisan’s scheduling system cron-jobs tasks without system-level crontab configuration — the schedule method in Kernel.php defines tasks with fluent methods like ->daily(), ->hourly(), and ->everyFiveMinutes().

Queues and Job Processing

Laravel’s queue system abstracts job processing across multiple backends — Redis, Amazon SQS, Beanstalkd, and database. Jobs are PHP classes implementing the ShouldQueue interface. The dispatch() helper dispatches jobs to the default queue. Queue workers process jobs in the background, with Horizon providing a dashboard for monitoring queue throughput, failed jobs, and worker health.

Job middleware adds cross-cutting concerns — rate limiting prevents API abuse, throttling limits concurrent job processing, and unique job enforcement prevents duplicate processing. Failed jobs are stored in the failed_jobs table for inspection and retry with configurable retry limits and delay intervals. Queue priority ensures critical jobs process before background tasks using separate queue names.

Authentication and Authorization

Laravel’s authentication system supports session-based and token-based authentication. Breeze and Jetstream provide scaffolded authentication with login, registration, password reset, and email verification. Jetstream adds team management, two-factor authentication, and profile photo uploads using Laravel’s built-in features.

Laravel Sanctum provides token-based authentication for SPAs and mobile apps with simple token management. Sanctum issues API tokens that can have specific abilities scoping access. Fortify implements all Laravel authentication features as a headless backend for custom frontend implementations. Policies and gates handle authorization with User model-centric permission checks using simple closures or policy classes.

Testing with PHPUnit and Pest

Laravel extends PHPUnit with helper methods for HTTP testing, database testing, and browser testing. HTTP tests simulate requests and assert on responses using methods like get(), post(), and assertStatus(). actingAs() authenticates users for protected routes for testing authenticated endpoints. Database assertions like assertDatabaseHas() verify model creation and deletion without loading Eloquent models into memory.

Pest is an alternative testing framework for Laravel that provides a simpler, more expressive syntax. Tests use closures instead of classes with higher-order expectations and snapshot testing. Pest’s it() and test() functions create readable test descriptions, while expect() provides fluent chained assertions. Pest integrates with PHPUnit under the hood, so existing PHPUnit tests continue working without modification.

Localization and Internationalization

Laravel’s localization system supports multiple languages through translation strings stored in resources/lang/ directories or JSON translation files. The __('messages.welcome') helper retrieves translations based on the current locale. The Lang facade manages locale switching — App::setLocale('fr') sets French translations for the current request.

Pluralization rules handle language-specific plural forms. The trans_choice() function selects the correct plural form based on count — trans_choice('messages.apples', $count). Laravel supports languages with complex pluralization rules including Russian (four forms) and Arabic (six forms).

Date and number formatting uses Laravel’s Carbon integration for timezone-aware date display. Number formatting with Number::format() handles locale-specific decimal and thousand separators. These localization features make Laravel well-suited for multilingual applications serving users in multiple countries.

Email and Notifications

Laravel’s notification system sends messages through multiple channels — email via SMTP, database for in-app notification storage, SMS via Nexmo or Twilio, Slack for team notifications, and custom channels for any delivery method. Notifications are PHP classes with via() method returning enabled channels and toMail() method building the email representation.

Mailables are PHP classes representing email types — OrderConfirmation, WelcomeMessage. Blade templates render email HTML with the same template engine used for web views. Markdown mailables generate responsive HTML emails from simple Markdown content using Laravel’s predefined notification templates. The notification system handles batching, queuing, and delivery failure retries with exponential backoff.

Broadcasting and Events

Laravel’s event system provides decoupled communication between application components. Events are simple PHP classes that can be listened to by multiple listeners. The Event::listen() method or Listeners directory classes handle events asynchronously through the queue system. Event discovery is automatic in Laravel — the framework scans listener directories.

Broadcasting events to the frontend uses Pusher, Ably, or Laravel’s WebSocket server (Laravel Reverb, introduced in Laravel 11). Events implement ShouldBroadcast and define the broadcast channel name. The frontend listens with Echo, Laravel’s JavaScript library that subscribes to channels and handles incoming events with callbacks.

Private and presence channels authenticate users before they can listen to channel events. Channel authorization routes verify that the authenticated user has permission to access the channel’s data. Presence channels track connected users and broadcast connection/disconnection events.

Eloquent ORM Power Features

Laravel’s Eloquent ORM provides advanced features beyond basic CRUD. Accessors and mutators transform attribute values when getting or setting. Relationships (hasMany, belongsToMany, morphMany) define database associations with lazy or eager loading. Scopes encapsulate common query constraints. The withCount method adds counts of related records. Global scopes apply filters to all queries for a model.

Task Scheduling and Queues

Laravel’s task scheduler (schedule in Kernel) provides cron-like scheduling within PHP. Define scheduled tasks in code, commit to version control, and run the schedule:run command every minute. Horizon provides a dashboard for monitoring Redis queues. Queues handle deferred tasks like email sending, PDF generation, and API calls with configurable retry logic.

FAQ

Is Laravel good for APIs? Yes. Laravel provides API resources for JSON transformation, Sanctum for token authentication, built-in rate limiting, and API versioning support. Lighthouse adds GraphQL support with schema-first development. Laravel’s queue system excels for async API processing.

How does Laravel compare to WordPress? Laravel is a framework for custom application development. WordPress is a CMS. Laravel gives you complete control over architecture, routing, and data models. WordPress provides a pre-built content management system with plugin extensibility. Laravel is for developers building custom applications; WordPress is for content managers building websites.

What database does Laravel support? MySQL, MariaDB, PostgreSQL, SQLite, and SQL Server. Laravel’s query builder and Eloquent ORM abstract away database differences, making it straightforward to support multiple database backends with the same codebase.

Does Laravel scale? Yes. Laravel with Octane (Swoole or RoadRunner), Redis caching, queue workers, and horizontal scaling handles millions of daily requests. Vapor provides serverless auto-scaling on AWS Lambda. Laravel’s architecture supports enterprise workloads with proper infrastructure.

What is Laravel Livewire? Livewire is a full-stack framework for Laravel that builds dynamic UIs without writing JavaScript. Components render HTML on the server and update via AJAX on user interactions. Livewire combines with Alpine.js for client-side polish, creating SPA-like experiences with server-side rendering.

Learn more about Laravel with our guides on ORM frameworks and backend framework comparison.

Section: Backend Web Frameworks 1551 words 8 min read Beginner 756 articles in section Report inaccuracy Back to top