Multiple parameters to Middleware in Laravel 5.8

min read

Day 21 Part 2  #100DaysOfCode

Thêm nhiều tham số đến Middleware 

//routes/web.php

Route::group(['middleware' => ['role_check:Normal_User,Admin']], function() {
        Route::get('/user/{user_id}', 'UserController@showUserDashboard');
    });

Mở file app/Http/Kernel.php thêm middleware

 protected $routeMiddleware = [
       .
       .
       .
       'role_check' => \App\Http\Middleware\CheckRoleMiddleware::class,
];

//File middleware 

/**
 * Handle an incoming request.
 *
 * @param $request
 * @param Closure $next
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
 */
public function handle($request, Closure $next) {

    $roles = array_slice(func_get_args(), 2); // [default, admin, manager]

    foreach ($roles as $role) {

        try {

            Role::whereName($role)->firstOrFail(); // make sure we got a "real" role

            if (Auth::user()->hasRole($role)) {
                return $next($request);
            }

        } catch (ModelNotFoundException $exception) {

            dd('Could not find role ' . $role);

        }
    }

    Flash::warning('Access Denied', 'You are not authorized to view that content.'); // custom flash class

    return redirect('/');
}

File model User.php

public function hasRole($role)
{
    return User::where('role', $role)->get();
}
public function userID()
{
    return $this->user_id; 
}

Hoặc ta có thể check Role trong Middleware bằng cách sau:

public function handle($request, Closure $next, $role)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    $userID = Auth::user()->userID();

    if (auth()->check() && auth()->user()->hasRole($role)) {
        return $next($request);
    }

}

Ta có thể dùng dấu(...) để xác nhận mảng tham số trong middleware

public function handle($request, Closure $next, ...$permissions){}
public function handle($request, Closure $next, ...$roles)
{
    foreach($roles as $role){
        if ($request->user()->hasRole($role)){
            return $next($request);
        }
    }
    abort(404);
}

Còn không ta chèn trực tiếp tham số trong function handle() luôn

 public function handle($request, Closure $next, $permission1, $permission2, $permission3)
    {
        return $next($request);
    }

 

 

 

 

 

 

 

 

 

x

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)