Przemek Wojtas
Przemek Wojtas

Reputation: 1371

Laravel check if user has specific role before proceeding with other functions

I have a controller like this:

public function __construct() 
{
    $check = Auth::id();

    if ($check->role == '5') {
        // allow to run any other controller
    } else {
        // return view('home')
    }

    return $check;
}

public function index() 
{
    return view('admin.home');
}

What I want to do is whenever, AdminController is triggered, run __construct function and check if role == 5, if it is, proceed with the request, else return view. How can that be done?

Edit

public function handle($request, Closure $next)
{
    if ($request->role == 2) {

    } else {
        return view('index');
    }

    return $next($request);
}

Kernel:

protected $middlewareGroups = [
    'admin' => [
        \App\Http\Middleware\CheckAdmin::class,
    ],
];

Route:

Route::group(['middleware' => ['admin']], function () {

Error::

(1/1) FatalThrowableError Call to a member function setCookie() on null in VerifyCsrfToken.php (line 156)

Upvotes: 2

Views: 2630

Answers (1)

Zayn Ali
Zayn Ali

Reputation: 4915

view() returns a Illuminate\View\View object, instead of a Illuminate\Http\Response. So instead of sending the view. Redirect the user to index route

Try this

public function handle($request, Closure $next)
{
    if ($request->role != 2) {
        return return redirect()->route('index');
    }

    return $next($request);
}

Upvotes: 4

Related Questions