📅  最后修改于: 2023-12-03 15:02:34.442000             🧑  作者: Mango
Laravel 8 comes with an easy-to-use authentication system that allows developers to quickly implement user authentication and authorization in their web applications. The authentication system includes pre-built controllers, views, and routes, making it easy to get up and running quickly.
To get started with Laravel 8 auth, follow these steps:
Create a new Laravel 8 project using the following command:
composer create-project --prefer-dist laravel/laravel project-name
Configure your database settings in the .env
file.
Run the following command to create the auth scaffolding:
php artisan make:auth
This command will generate the necessary views, controllers, and routes for user authentication.
Run the migration to create the users table in the database:
php artisan migrate
Start the Laravel development server:
php artisan serve
Navigate to http://localhost:8000/login
to access the login page.
Laravel 8 supports multiple authentication guards, which allows you to authenticate users based on different criteria. For example, you could have a web
guard for authenticating users via the web app, an api
guard for authenticating users via API requests, etc.
To define a guard, add it to the guards
array in the config/auth.php
file. For example, to add an admin
guard that authenticates users based on whether they are an admin or not, you could add the following to your guards
array:
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
You would then define a admins
provider that specifies how to retrieve and validate the admin credentials:
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
Laravel 8 also includes an authorization system that allows you to define policies and gates that control which users can access which resources. For example, you could define a UpdatePostPolicy
that specifies which users can update a particular post:
class UpdatePostPolicy
{
use HandlesAuthorization;
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
You would then authorize the user in your controller using the authorize
method:
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// Update the post
}
Laravel 8 auth provides an easy-to-use authentication and authorization system for web applications. With pre-built controllers, views, and routes, developers can quickly implement user authentication and authorization in their projects. Additionally, Laravel's support for multiple authentication guards and authorization policies makes it easy to control which users can access which resources.