问题
I recently started using Laravel 8 and I am trying to log in using username and email together but I do not know how to do this. In Laravel 7 I could use...
protected function credentials(Request $request)
{
$field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
? $this->username()
: 'username';
return [
$field => $request->get($this->username()),
'password' => $request->password,
];
}
How can I log in using both username and password in Laravel 8 since there is no LoginController
inside the Auth
folder anymore?
回答1:
Solution working for Laravel-Jetstream
You can authenticate using username or email
following this steps.
1. Confirm login input field name (Let name is identity
)
2. Change config/fortify.php
'username' => 'email' to 'username' => 'identity'
3. Added following authentication code in your app/Providers/FortifyServiceProvider.php
file inside boot method
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->identity)
->orWhere('username', $request->identity)->first();
if (
$user &&
\Hash::check($request->password, $user->password)
) {
return $user;
}
});
[Note] Please use those classes
use Laravel\Fortify\Http\Requests\LoginRequest;
use App\Models\User;
#For register username
1. Add input in your register.blade.php
<div class="mt-4">
<x-jet-label for="username" value="{{ __('User Name') }}" />
<x-jet-input id="username" class="block mt-1 w-full" type="text" name="username" :value="old('username')" required autofocus autocomplete="username" />
</div>
2. Add username
in User model $fillable
array list.
3. Finally change in app/Actions/Fortify/CreateNewUser.php
file
Validator::make($input, [
..........
'username' => ['required', 'string', 'max:255', 'unique:users'],
.........
])->validate();
return User::create([
.......
'username' => $input['username'],
.....
]);
}
Lets enjoy the authentication.
回答2:
Laravel Jetstream (available for Laravel 8) replaces Laravel Authentication UI which was available for previous Laravel versions. This means, for the authentication functionality you want, you have to install and use Jetstream. To install Jetstream with composer, run the following command
composer require laravel/jetstream
php artisan jetstream:install
Then, depending on whether you want to use Livewire or Inertia, run one of the following two commands:
php artisan jetstream:install livewire
or
php artisan jetstream:install inertia
After that, then run
npm install && npm run dev
php artisan migrate
Jetstream is ready for use.
Here is Jetstream documentation and a quick tutorial.
来源:https://stackoverflow.com/questions/63802266/problem-authenticating-with-username-and-password-in-laravel-8