Home Laravel How to create and use Middleware in Laravel ?

How to create and use Middleware in Laravel ?

by Shahriar Sagor
Middleware in Laravel

Today now in this post i will show you How to create and use Middleware in Laravel? Laravel is one of the best framework in PHP now days. Laravel framework is provide several functionality and we can also find from on this site. But now from this post we can learn about how to create custom middleware as filter in laravel application example and how to use the middleware in laravel . So In this example we can learn how to add middlware from the scratch in our laravel application.

Now In this example i will add middleware for check the if user is admin then it will open some route as like ACL. So here i will add id_admin column in my users table if the use have is_admin = 1 then it will access “admins” route. So at first need to create IsAdminMiddleware middleware by using bellow command:

Create Middleware

php artisan make:middleware IsAdminMiddleware

Ok, now here we can found IsAdminMiddleware.php in location app/Http/Middleware directory and need to open IsAdminMiddleware.php file and then put bellow code on that file. Now In this file i will check first if user is not login then it will redirect to the home route and other if user have not is_admin = 1 then it will redirect to home route too.

namespace App\Http\Middleware;
use Closure;
use Auth;
class IsAdminMiddleware
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        if(!Auth::check() || Auth::user()->is_admin != '1'){
            return redirect()->route('home');
        return $next($request);

Now here we need to register and the create aliase above middleware in Kernel.php file so at first need to open Kernel.php and add the bellow line.


namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
	protected $routeMiddleware = [
        'is-admin' => \App\Http\Middleware\IsAdminMiddleware::class,

Now i hope we are ready to use is-admin middleware in the routes.php file. so we can see the how to use middleware in routes.php file.


Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::group(['middleware' => 'is-admin'], function () {     
    Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins']); 


Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins','middleware' => 'is-admin']); 

Read Also : How to convert Object into Array in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook.


You may also like