0
0
Laravelframework~30 mins

Why middleware filters requests in Laravel - See It in Action

Choose your learning style9 modes available
Why Middleware Filters Requests in Laravel
📖 Scenario: You are building a simple Laravel web application that needs to control access to certain pages. You want to use middleware to filter requests and allow only authenticated users to access a protected page.
🎯 Goal: Learn how to create and apply middleware in Laravel to filter HTTP requests based on authentication status.
📋 What You'll Learn
Create a middleware class named CheckAuthenticated
Define a route /dashboard that uses the middleware
Use a boolean variable $isAuthenticated to simulate user login status
In the middleware, check $isAuthenticated and allow or block access
Return a simple response indicating access granted or denied
💡 Why This Matters
🌍 Real World
Middleware is used in real Laravel apps to protect pages, check user permissions, and handle tasks like logging or modifying requests.
💼 Career
Understanding middleware is essential for backend developers working with Laravel to build secure and well-structured web applications.
Progress0 / 4 steps
1
DATA SETUP: Create a boolean variable $isAuthenticated
Create a boolean variable called $isAuthenticated and set it to false to simulate a user who is not logged in.
Laravel
Need a hint?

Use $isAuthenticated = false; to represent a user who is not logged in.

2
CONFIGURATION: Define a middleware class CheckAuthenticated
Create a middleware class named CheckAuthenticated with a method handle that accepts $request and $next parameters.
Laravel
Need a hint?

Use a class with a handle method that checks $isAuthenticated and returns a message or calls $next($request).

3
CORE LOGIC: Define a route /dashboard using the middleware
Create a function dashboard that returns 'Welcome to your dashboard!'. Then simulate a request to /dashboard by calling the middleware's handle method with a dummy $request and a closure that calls dashboard.
Laravel
Need a hint?

Define a dashboard function and call the middleware's handle method with a closure that calls dashboard.

4
COMPLETION: Change $isAuthenticated to true to allow access
Change the value of $isAuthenticated to true so the middleware allows access to the dashboard.
Laravel
Need a hint?

Set $isAuthenticated = true; to simulate a logged-in user.