1

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?

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Raitiko
  • 165
  • 11

1 Answers1

2

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());
}
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • This does work, but when i enter the correct email but wrong password, it gives me the message that it's not active. So it doesn't matter if the password is correct it only checks email. – Raitiko Apr 06 '23 at 06:56
  • 1
    If you want to log in and then throw the not active validation you can swap `is_active` checking line with the ` Auth::login` – Abdulla Nilam Apr 06 '23 at 07:00