Skip to content
Advertisement

Laravel Middleware Error – Call to a member function isBasic() on null

I want to check user type when they log in and apply function

In my middleware, I have this code

public function handle($request, Closure $next)
{
    $user = Auth::user();
    if ($user->isBasic()) {
        $previous_session = $user->session_id;

        if ($previous_session) {
            Session::getHandler()->destroy($previous_session);
        }

        Auth::user()->session_id = Session::getId();
        Auth::user()->save();
        return redirect(route('home'));
    }

    return $next($request);
}

In my User model, I have this

public function isBasic()
{
    return $this->role=='basic';
}

I have already registered the middleware in Kernel

'basic' => AppHttpMiddlewareCheckSession::class,

And I passed it to my LoginController like this

public function __construct()
{
    $this->middleware('basic');
}

But when it tried to visit the login controller, it says

Call to a member function isBasic() on null

I am a beginner in Laravel and I don’t know what to do

Advertisement

Answer

This seems like a good candidate for the authenticated method of the LoginController which gets called after a user has logged in.

use IlluminateHttpRequest;


/**
 * The user has been authenticated.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    if ($user->isBasic()) {
        $previous_session = $user->session_id;

        if ($previous_session) {
            $request->session()->getHandler()->destroy($previous_session);
        }

        $user->session_id = $requset->session()->getId();
        $user->save();

        // do these specific users need to be redirected to somewhere special?
        return redirect()->route('home');
    }
}

You could even listen for the Auth events if you wanted to, as long as its not a queued listener.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement