loading...

Laravel middleware: My notes

abdelkbirkhoui1 profile image A.Khouilid ・2 min read

> Create 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.

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

php artisan make:middleware NameOfMiddlwere

After we create a new middleware, we can put our condition inside its method:

For example, a user wants to access his profile, so we need to check if he is login or not, for that we use middleware.

we create a method check if $_SESSION['is_login'] = true;

namespace App\Http\Middleware;

use Closure;

class CheckLogin
{

    public function handle($request, Closure $next)
    {
        if (isset($_SESSION['is_login']) {
             if ($_SESSION['is_login'] == false) {
               return redirect('/');
             }
        }

        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

As we see, we get the request and check if the user login or not, if he not we redirect him into the home page, otherwise, we allow him to access his profile. (we use a callback function 'closure' )

> Assigning Middleware To Routes

if we want to assign middleware to a specific route, First we should assign the middleware a key in our app/Http/Kernel.php file.

then we can use our middleware like this:

Route::get('admin/profile', function () {
    //
})->middleware('theKey');
Enter fullscreen mode Exit fullscreen mode

> Middleware Parameters

Let's imagine that before we allow any user to access a specific route, we need to check if he's an Admin first.

public function handle($request, Closure $next, $type)
    {
        if (isset($_SESSION['user_type'])) {

            if ($_SESSION['user_type'] == $type) {
               //Redirect...
            }
        }

        return $next($request);
}
Enter fullscreen mode Exit fullscreen mode

And we can put the parameter like this...

Route::get('admin/profile', function () {
    //
})->middleware('theKey:Admin');
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide
Collapse
l3lackheart profile image
l3lackheart

I highly recommend to use the built-in app/Http/Middleware/Authenticate.php and app/Http/Middleware/RedirectIfAuthenticated.php instead
More detail here: laravel.com/docs/8.x/authenticatio...

Collapse
abdelkbirkhoui1 profile image
A.Khouilid Author

thank you, absolutely I will give it a try.