I have a boolean column in my users table for active
. But I can't figure out how to have the column checked during login and only allow login if active has a value of 1. I wish I had examples of code I've tried, but I am literally stuck. I am using Laravel 8 and Breeze. I am assuming that the check would happen inside the AuthenticatedSessionController file in the store
function. Below is the file.
AuthenticatedSessionController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* @param \App\Http\Requests\Auth\LoginRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
/**
* Destroy an authenticated session.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
CodePudding user response:
Please look at authenticate() function located at app/Http/Requests/LoginRequest.php
/**
* Attempt to authenticate the request's credentials.
*
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
//array_merge( $request->only($this->username(), 'password'), ['is_active' => 1 ])
//if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
if (! Auth::attempt(array_merge( $this->only('email', 'password'), ['is_active' => 1 ]), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
CodePudding user response:
You have to use AuthenticatesUsers
where you doing POST login request
AuthenticatesUsers
is Laravel's default authentication trait which provide the Login Related methods.
You have to place below method in your LoginController to override default method and add your column to check if user is active or not.
protected function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'), ['active' => 1]);
}