I'm doing a Laravel authentication. I don't know if it is important to clarify that I'm using the Auth::routes
.
I added an active
field to my users model. But even when is not active, I'm able to log in.
This is my user model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Passport\HasApiTokens;
use Laratrust\Traits\LaratrustUserTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Auth;
class User extends Authenticatable
{
use Notifiable;
use LaratrustUserTrait;
use HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'active'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'active' => 'boolean',
'email_verified_at' => 'datetime',
];
}
Then, as the documentation specifies under the "Specifying Additional Conditions" section, I added inside my LoginController.php
the custom validation with the extra parameter to the attempt function.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Handle an authentication attempt.
*
* @param \Illuminate\Http\Request $request
*
* @return Response
*/
public function authenticate(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
return redirect()->intended($redirectTo);
}
}
}
What Am I doing wrong?
It is important to clarify where to put the code of the Laravel documentation. In order to make it work, you need to import
use Illuminate\Http\Request;
at the top of yourLoginController.php
file.Then, you have to override the credentials function.
After doing this, the expected results were obtained.
Instead of override authenticate() method, override credentials method in your LoginController.