• Developer New

    Friday, March 24, 2017

    How to create and use Middleware in Laravel 5?

    Laravel is the best framework in PHP todays. Laravel framework provide saveral functionality and you can also find from this site. But now in this post you can learn how to create custom middleware as filter in laravel 5 example and how to use middleware in laravel 5. In this example you can learn how to add middlware from scratch in your laravel application.
    In this example i added middleware for check if user is admin then it can open someroute like ACL. So i added id_admin column in my users table if use have is_admin = 1 then it can access "admins" route. So first create IsAdminMiddleware middleware using bellow command:
    Create Middleware
    php artisan make:middleware IsAdminMiddleware
    Ok, now you can found IsAdminMiddleware.php in app/Http/Middleware directory and open IsAdminMiddleware.php file and put bellow code on that file. In this file i check first if user is not login then it will redirect home route and other if user have not is_admin = 1 then it will redirect home route too.
    app/Http/Middleware/IsAdminMiddleware.php
    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 we need to register and create aliase above middleware in Kernel.php file so first open Kernel.php and add bellow line.
    app/Http/Kernel.php
    namespace App\Http;
    use Illuminate\Foundation\Http\Kernel as HttpKernel;
    class Kernel extends HttpKernel
    {
    ......
    protected $routeMiddleware = [
    ......
    'is-admin' => \App\Http\Middleware\IsAdminMiddleware::class,
    ];
    }
    Now we are ready to use is-admin middleware in routes.php file. so you can see how to use middleware in routes.php file.
    app/Http/routes.php
    Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
    Route::group(['middleware' => 'is-admin'], function () {
    Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins']);
    });
    OR
    Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
    Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins','middleware' => 'is-admin']);

    No comments:

    Post a Comment

    Fashion

    Beauty

    Travel