laravelauthenticationlaravel-bladeflash-messagelaravel-breeze

Laravel 10 Breeze - Throw custom flash message if user is not active


What I am trying to do is throw a custom error message if the user is not active.

This is the method:

public function authenticate(): void
{
    $this->ensureIsNotRateLimited();

    if (! Auth::attempt($this->only('email', 'password') + ['is_active' => true] , $this->boolean('remember'))) {
        RateLimiter::hit($this->throttleKey());
        
        
        if(Auth::user()->is_active == 0){
            Session::flash('active', 'User is not active.'); 
        }

        throw ValidationException::withMessages([
            'email' => trans('auth.failed'),
        ]);
    }

    RateLimiter::clear($this->throttleKey());
}

Then in the blade file:

 @if(Session::has('active'))
        <div class="bg-red-100 border-t-4 border-red-500 rounded-b text-teal-900 px-4 py-3 shadow-md mb-6" role="alert">
            <div class="flex align-center justify-center">
                <div>
                    <p class="font-bold">{{ Session::get('active') }}</p>
                </div>
            </div>
        </div>
 @endif

And when I try to login I get Attempt to read property "is_active" on null

I also added is_active in protected $fillable

Why does this happen?


Solution

  • When you use if (! Auth::attempt($this->only('email', 'password') means if auth failed to execute the if condition. So if auth failed there is no way you can access Auth::user(). Because it's null always.

    Alternatively you can do something like this

    public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();
    
        $user = User::where('email', $this->input('email'))->first();
    
        if (!$user || !Hash::check($this->input('password'), $user->password)) {
            RateLimiter::hit($this->throttleKey());
    
            if ($user && $user->is_active === 0) {
                Session::flash('active', 'User is not active.');
            }
    
            throw ValidationException::withMessages([
                'email' => trans('auth.failed'),
            ]);
        }
    
        Auth::login($user, $this->boolean('remember'));
        // if you need you can set is_active  tru once logged in
    
        RateLimiter::clear($this->throttleKey());
    }