MasterPHP.in
Laravel Tutorial

Features of Laravel


Laravel's popularity is not accidental. It earned its place as the world's most used PHP framework because of the features it ships with. Each feature solves a real problem that developers face when building web applications — and solves it elegantly.

In this lesson, you will get a solid understanding of each major feature, what it does, and why it matters. You will go deep on each of these in their dedicated lessons later in this course. For now, the goal is to understand the full picture of what Laravel brings to the table.


1. MVC Architecture

Laravel is built on the Model-View-Controller (MVC) pattern. This is a way of organizing your code into three clearly separated responsibilities:

  • Model — Handles data and database interaction. A model represents a table in your database and contains the logic for reading and writing data.
  • View — Handles what the user sees. Views are HTML templates that display data to the browser.
  • Controller — Handles the logic between the two. It receives a request, talks to the model, and sends the right data to the view.

Here is a simple example of how a request flows through MVC in Laravel:

// routes/web.php — the URL triggers a controller method
Route::get('/products', [ProductController::class, 'index']);

// app/Http/Controllers/ProductController.php — the controller
public function index()
{
    $products = Product::all(); // Model fetches data
    return view('products.index', compact('products')); // View displays it
}

// resources/views/products/index.blade.php — the view
@foreach ($products as $product)
    <p>{{ $product->name }} — ₹{{ $product->price }}</p>
@endforeach

Without MVC, it is common to see PHP files where database queries, business logic, and HTML all sit in the same file. This becomes nearly impossible to maintain as the application grows. MVC enforces a clean separation that keeps your codebase organized from day one.


2. Blade Templating Engine

Blade is Laravel's built-in templating engine for writing dynamic HTML views. It is simple, fast, and far more readable than mixing raw PHP tags inside HTML.

Blade compiles down to plain PHP behind the scenes, so there is no performance penalty. Every Blade file uses the .blade.php extension.

Outputting variables:

<h1>Welcome, {{ $user->name }}</h1>

The double curly braces automatically escape the output to prevent XSS attacks. If you intentionally need unescaped output, you use {!! !!} — but that is rarely needed.

Conditionals:

@if ($user->isAdmin())
    <p>You have admin access.</p>
@else
    <p>You are a regular user.</p>
@endif

Loops:

@forelse ($products as $product)
    <li>{{ $product->name }}</li>
@empty
    <p>No products found.</p>
@endforelse

Layouts and reusable components are where Blade really shines. You define a master layout once and extend it across every page, so your header, footer, and navigation are written once and never repeated:

{{-- resources/views/layouts/app.blade.php --}}
<html>
<body>
    @include('partials.navbar')
    @yield('content')
    @include('partials.footer')
</body>
</html>

{{-- resources/views/home.blade.php --}}
@extends('layouts.app')

@section('content')
    <h1>Home Page</h1>
@endsection

This layout inheritance system eliminates duplicated HTML across pages and makes updating your site's structure a single-file change.


3. Eloquent ORM

Eloquent is Laravel's Object-Relational Mapper. It maps your database tables to PHP classes called models, so you interact with your database using clean PHP code rather than raw SQL strings.

Each database table has a corresponding model. The users table maps to a User model, the products table maps to a Product model, and so on.

Basic operations:

// Fetch all records
$users = User::all();

// Find a specific record by ID
$user = User::find(1);

// Find with a condition — throws 404 if not found
$user = User::findOrFail(1);

// Query with conditions
$activeUsers = User::where('status', 'active')
                   ->orderBy('created_at', 'desc')
                   ->get();

// Create a new record
User::create([
    'name' => 'Rohan',
    'email' => 'rohan@example.com',
    'password' => bcrypt('secret'),
]);

// Update a record
$user = User::find(1);
$user->name = 'Rohan Sharma';
$user->save();

// Delete a record
User::find(1)->delete();

Relationships are one of Eloquent's most powerful features. You can define how models relate to each other and then access related data naturally:

// A user has many posts
class User extends Model {
    public function posts() {
        return $this->hasMany(Post::class);
    }
}

// Access all posts by a user — no JOIN query needed
$posts = User::find(1)->posts;

Eloquent supports all standard relationship types: one-to-one, one-to-many, many-to-many, and polymorphic relationships. You will cover all of these in the Eloquent section of this course.


4. Artisan CLI

Artisan is Laravel's built-in command-line interface. It is one of the biggest time-savers in the framework. Instead of manually creating files and writing boilerplate, you run a command and the file is generated instantly with the correct structure.

Commonly used Artisan commands:

# Generate application files
php artisan make:model Product
php artisan make:controller ProductController
php artisan make:migration create_products_table
php artisan make:seeder ProductSeeder
php artisan make:middleware CheckAdmin
php artisan make:request StoreProductRequest

# Database operations
php artisan migrate              # Run pending migrations
php artisan migrate:rollback     # Undo last migration batch
php artisan db:seed              # Run seeders to populate test data

# Cache management
php artisan cache:clear
php artisan config:clear
php artisan view:clear

# Development
php artisan serve                # Start local dev server at localhost:8000
php artisan tinker               # Open an interactive PHP shell

Artisan is also extensible — you can write your own custom commands for things like sending scheduled reports, cleaning up old records, or syncing data from an external API. Any repetitive task you would otherwise run manually can become an Artisan command.


5. Database Migrations

Migrations are Laravel's version control system for your database. Instead of making changes to your database manually through phpMyAdmin or a SQL client, you write migration files in PHP that describe the changes. These files can be run, rolled back, and shared with your team.

Creating a migration:

php artisan make:migration create_products_table

The generated migration file:

public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description')->nullable();
        $table->decimal('price', 8, 2);
        $table->string('status')->default('active');
        $table->timestamps(); // adds created_at and updated_at
    });
}

public function down(): void
{
    Schema::dropIfExists('products');
}

Run the migration with php artisan migrate and the table is created. Roll it back with php artisan migrate:rollback if something went wrong.

The biggest advantage of migrations is team collaboration. When a developer adds a new column to a table, they create a migration for it and commit it to the repository. Every other developer on the team simply runs php artisan migrate and their local database is updated automatically — no manual SQL scripts, no "I forgot to tell you about the new column" problems.


6. Routing

Laravel's routing system is clean and expressive. All of your application's URLs are defined in route files, making it easy to see every entry point into your application at a glance.

// Basic route
Route::get('/about', function () {
    return view('about');
});

// Route to a controller method
Route::get('/products', [ProductController::class, 'index']);
Route::post('/products', [ProductController::class, 'store']);
Route::get('/products/{id}', [ProductController::class, 'show']);
Route::put('/products/{id}', [ProductController::class, 'update']);
Route::delete('/products/{id}', [ProductController::class, 'destroy']);

// All 7 RESTful routes in a single line
Route::resource('products', ProductController::class);

// Protected route — requires login
Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

Laravel also supports named routes, route groups, route model binding (automatically fetching a model from the database based on a URL parameter), and API versioning. The routing system is one of the most appreciated parts of the framework by developers coming from plain PHP.


7. Built-In Authentication

Building a secure login and registration system from scratch is time-consuming and easy to get wrong. Laravel provides complete authentication scaffolding that you can set up in minutes.

With the Laravel Breeze or Jetstream starter kits, you get:

  • User registration with email and password
  • Secure login and logout
  • Password reset via email
  • Email verification
  • Remember me functionality
  • Session management

For API-based authentication — such as for a mobile app or a React/Vue frontend — Laravel Sanctum provides token-based authentication that integrates seamlessly.


8. Built-In Security Features

Laravel protects your application against the most common web security vulnerabilities automatically:

CSRF Protection — Every form submission is validated with a CSRF token. You just add @csrf to your Blade form and Laravel handles the rest:

<form method="POST" action="/products">
    @csrf
    <input type="text" name="name">
    <button type="submit">Save</button>
</form>

SQL Injection Protection — Eloquent and the query builder use PDO prepared statements. User input is never interpolated directly into SQL queries.

XSS Protection — Blade's {{ }} syntax escapes all output automatically. A user cannot inject malicious scripts through your views.

Password Hashing — Laravel uses bcrypt for hashing passwords. The Hash facade makes this straightforward:

$hashed = Hash::make('userpassword');
Hash::check('userpassword', $hashed); // true


9. Queues and Background Jobs

Some tasks take too long to run during a web request — sending emails, generating PDF reports, resizing uploaded images, or calling external APIs. Making the user wait for these is a poor experience.

Laravel's queue system lets you push these tasks to a background worker that processes them separately, so the user gets an instant response while the heavy work happens in the background.

// Dispatch a job to the queue
SendWelcomeEmail::dispatch($user);

// The job runs in the background
class SendWelcomeEmail implements ShouldQueue
{
    public function handle(): void
    {
        Mail::to($this->user)->send(new WelcomeMail());
    }
}

Laravel supports multiple queue backends including Redis, Amazon SQS, and database queues — you switch between them with a single config change.


10. Caching

Performance matters. Laravel provides a unified caching API that works with drivers like Redis, Memcached, and file-based cache. You can cache expensive database queries or computation results and serve them instantly on repeat requests.

// Cache a database query result for 60 minutes
$products = Cache::remember('products.all', 3600, function () {
    return Product::all();
});

// Clear a cached value
Cache::forget('products.all');

Caching the right things can reduce your database load dramatically and make your application feel significantly faster for users.


11. Task Scheduling

Most applications need to run tasks on a schedule — sending a weekly email digest, clearing old records from the database, generating daily reports. Laravel's task scheduler lets you define all of these in one place using a clean, readable syntax:

// app/Console/Kernel.php
protected function schedule(Schedule $schedule): void
{
    $schedule->command('reports:generate')->dailyAt('08:00');
    $schedule->command('db:cleanup')->weekly();
    $schedule->job(new SendWeeklyNewsletter)->weekly()->mondays()->at('9:00');
}

You add a single cron entry to your server and Laravel handles all the scheduling logic from there.


12. File Storage

Laravel provides a clean API for working with files whether they are stored locally on the server, on Amazon S3, or any other cloud storage provider. The same code works regardless of where the files actually live — you switch the driver in configuration, not in your application logic.

// Store an uploaded file
$path = $request->file('avatar')->store('avatars', 's3');

// Retrieve a file URL
$url = Storage::disk('s3')->url($path);

// Delete a file
Storage::delete($path);

Frequently Asked Questions

No. Laravel follows a pick-what-you-need approach. You can use only routing, controllers, and views for a simple site without touching queues, broadcasting, or task scheduling. As your application grows and needs more, those features are ready when you need them.
No. Laravel also has a Query Builder that lets you write more direct SQL-like queries in PHP without using a model. And if you need raw SQL for a complex query, Laravel supports that too. Eloquent is simply the most convenient option for most standard database operations.
Both ultimately produce HTML. Blade's advantage is its cleaner syntax — @if, @foreach, @extends, and {{ }} are more readable than their raw PHP equivalents. Blade also adds layout inheritance and components, which plain PHP does not provide out of the box. There is no performance difference since Blade compiles to plain PHP and is cached.
Yes. Laravel has a massive ecosystem of community packages available through Composer and Packagist. If Laravel does not include something natively, there is almost always a well-maintained package that adds it. The framework is also designed to be extensible so you can build your own service providers and packages.

Share this tutorial