Laravel / Laravel Authentication and Security

Securing Routes with Middleware

This tutorial will demonstrate how to secure your Laravel application's routes using middleware. Middleware provides a way to filter HTTP requests, ensuring only authorized users …

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explains authentication, authorization, and security best practices in Laravel.

Securing Routes with Middleware in Laravel

1. Introduction

Goal of the Tutorial

This tutorial aims to teach you how to secure your Laravel application's routes using middleware. Middleware allows you to filter HTTP requests entering your application, ensuring only authorized users can access certain routes.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand what middleware is and how it works in Laravel
- Create and register a new middleware
- Secure your routes using middleware

Prerequisites

Before starting this tutorial, you should have a basic understanding of Laravel and PHP. Familiarity with Laravel routing will be beneficial.

2. Step-by-Step Guide

Understanding Middleware

Middleware provides a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Creating Middleware

To create a new middleware, use the make:middleware Artisan command:

php artisan make:middleware CheckAge

This command will place a new CheckAge class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 200.

public function handle($request, Closure $next)
{
    if ($request->age <= 200) {
        return redirect('home');
    }

    return $next($request);
}

Registering Middleware

After creating the middleware, you need to register it in your app/Http/Kernel.php file.

protected $routeMiddleware = [
    'age' => \App\Http\Middleware\CheckAge::class,
];

Assigning Middleware to Routes

Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:

Route::get('post', function () {
    // Only authenticated users may enter...
})->middleware('age');

3. Code Examples

Example 1: Creating a Middleware

php artisan make:middleware IsAdmin

This creates a new file IsAdmin.php in the app/Http/Middleware directory.

public function handle($request, Closure $next)
{
    if (auth()->user()->is_admin == 0) {
        return redirect('home');
    }

    return $next($request);
}

In this example, we create a middleware that checks if the user is an admin. If they're not, they're redirected back to the 'home' page.

Example 2: Assigning Middleware to Routes

First, register the middleware in app/Http/Kernel.php.

protected $routeMiddleware = [
    'is.admin' => \App\Http\Middleware\IsAdmin::class,
];

Then, assign the middleware to a route.

Route::get('admin', function () {
    // Only admins may enter...
})->middleware('is.admin');

In this example, only admins can access the 'admin' route.

4. Summary

  • Middleware offers a way to filter HTTP requests in your application.
  • You can create a middleware using the make:middleware Artisan command.
  • Middleware can be assigned to routes to restrict access based on certain conditions.

5. Practice Exercises

  1. Create a middleware that checks if the user's email is verified. If not, redirect them to a 'verify email' page.
  2. Register the middleware you just created and assign it to a 'profile' route.

Remember, practice is key to mastering any concept. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

File Size Checker

Check the size of uploaded files.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help