Friday, August 7, 2015

How and why to use Middleware in Laravel 5.1

Middleware in Laravel 5.1:

Middleware is used for check the request and then process it for particular url.

e.g. There are two types of users. One is Vendor and another is Users. Then for both kind of users will get different authorization.

For this:

Create a Middleware File

php artisan make:middleware VendorMiddleware

Now in routes.php we will set its url

route code
Route::group(['middleware' => 'auth'], function () {
    Route::get('/', ['middleware' => 'vendor', function () {
        return view('welcome');
    }]);


In VendorMiddleware:
<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class VendorMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user= Auth::user();
        if($user->user_type=='vendor'){
            echo "vendor login";
        }else{
            echo "you are unauthorized person";
        }
        //return $next($request);
    }
}


Write in app/Http/Kernel.php

 'vendor' => \App\Http\Middleware\VendorMiddleware::class,

Thanks

No comments:

Post a Comment