4

I'm trying to change checkIfUserIsAdmin() method in CheckIfAdmin middleware for disabling access to all users without role admin

What happened: Nothing. backpack_user()->can(...) or backpack_user()->role(...) don't working... Is that right way to restrict user access to admin panel?

bp - 3.5

laravel - 5.7

php - 7.2

user137
  • 629
  • 1
  • 8
  • 20

2 Answers2

9

First, create a middleware:

php artisan make:middleware AdminMiddleware

In this file we will check that the user has ‘admin’ role

<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if (! \Auth::user()->hasRole('admin')) 
            return response(trans('backpack::base.unauthorized'),401);
        return $next($request);
    }
}

Now, add this middleware to /config/backpack/base.php

(don’t delete CheckIfAdmin middleware, just append it)

'middleware_class' => [
    \Backpack\Base\app\Http\Middleware\CheckIfAdmin::class,
    \App\Http\Middleware\AdminMiddleware::class
],

Offcourse we must cache the config then

php artisan config:cache
merdan
  • 1,229
  • 1
  • 11
  • 26
  • I have tried this solution but middleware seems not to been executed. – Kezern Jun 06 '19 at 10:02
  • 1
    @Kezern did you cleared config cache after additon middlewae to backpacks config? if dont try php artisan config:cache – merdan Jun 06 '19 at 12:19
  • I tried your solution , but it gives this error. Call to a member function hasRole() on null on \app\Http\Middleware\AdminMiddleware.php:19 – m yadav Nov 25 '22 at 05:07
5

One way is to make a Middleware in Http\Middleware like CheckIfAdmin.php with below function.

private function checkIfUserIsAdmin($user)
    {
        return ($user->is_admin == 1);
    }

Then add this middleware in array $routeMiddleware of Http\Kernel.php. Like below.

'admin' => \App\Http\Middleware\checkIfUserIsAdmin::class,
Rudolph
  • 139
  • 1
  • 8