Home > other >  Call to a member function isSuperUser() on null
Call to a member function isSuperUser() on null

Time:05-28

I have added this method to my User model:

public function isSuperUser()
{
    return $this->is_superuser;
}

is_superuser is a column of my users table which is set to Boolean type.

And then I created this middleware to check if the authenticated user is admin (super user) or not:

public function handle($request, Closure $next)
    {
        if($request->user()->isSuperUser()) {
            return $next($request);
        }

        return redirect('/');
    }

And I have applied this middleware to all the admin routes in RouteServiceProvider.php:

Route::middleware('auth.admin')
                ->namespace($this->namespace)
                ->prefix('admin')
                ->group(base_path('routes/web/admin.php'));

But now when I load one of the admin routes I get this error:

Call to a member function isSuperUser() on null

However I am already logged in to my account.

So what's going wrong here? How can I solve this issue?

CodePudding user response:

Use this instead.

// ...

if(auth()->user()?->is_superuser)

// ...

CodePudding user response:

You need to assume that user is not logged so you should use:

if($request->user()?->isSuperUser()) {
   return $next($request);
}

or

if(optional($request->user())->isSuperUser()) {
   return $next($request);
}

if you are using older PHP versions

  • Related