我想做的是抛出一个自定义错误消息,如果用户不活跃
方法:
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());
}
然后在刀片文件中:
@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
当我尝试登录时,我得到Attempt to read property "is_active" on null
我还在protected $fillable
中加入了is_active
为什么会发生这种情况?
当您使用if (! Auth::attempt($this->only('email', 'password')
时表示如果auth未能执行if
条件。因此,如果auth失败,则无法访问Auth::user()
。因为它总是null
。
或者你可以这样做
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());
}