Authentication
Introduction
Want to get started fast? Install the laravel/ui
Composer package and run php artisan ui vue --auth
in a fresh Laravel application. After migrating your database, navigate your browser to http://your-app.test/register
or any other URL that is assigned to your application. These commands will take care of scaffolding your entire authentication system!
Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php
, which contains several well documented options for tweaking the behavior of the authentication services.
At its core, Laravel's authentication facilities are made up of "guards" and "providers". Guards define how users are authenticated for each request. For example, Laravel ships with a session
guard which maintains state using session storage and cookies.
Providers define how users are retrieved from your persistent storage. Laravel ships with support for retrieving users using Eloquent and the database query builder. However, you are free to define additional providers as needed for your application.
Don't worry if this all sounds confusing now! Many applications will never need to modify the default authentication configuration.
Database Considerations
By default, Laravel includes an App\User
Eloquent model in your app
directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database
authentication driver which uses the Laravel query builder.
When building the database schema for the App\User
model, make sure the password column is at least 60 characters in length. Maintaining the default string column length of 255 characters would be a good choice.
Also, you should verify that your users
(or equivalent) table contains a nullable, string remember_token
column of 100 characters. This column will be used to store a token for users that select the "remember me" option when logging into your application.
Authentication Quickstart
Routing
Laravel's laravel/ui
package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:
composer require laravel/ui:^2.4
php artisan ui vue --auth
This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points. A HomeController
will also be generated to handle post-login requests to your application's dashboard.
The laravel/ui
package also generates several pre-built authentication controllers, which are located in the App\Http\Controllers\Auth
namespace. The RegisterController
handles new user registration, the LoginController
handles authentication, the ForgotPasswordController
handles e-mailing links for resetting passwords, and the ResetPasswordController
contains the logic to reset passwords. Each of these controllers uses a trait to include their necessary methods. For many applications, you will not need to modify these controllers at all.
If your application doesn’t need registration, you may disable it by removing the newly created RegisterController
and modifying your route declaration: Auth::routes(['register' => false]);
.
Creating Applications Including Authentication
If you are starting a brand new application and would like to include the authentication scaffolding, you may use the --auth
directive when creating your application. This command will create a new application with all of the authentication scaffolding compiled and installed:
laravel new blog --auth
Views
As mentioned in the previous section, the laravel/ui
package's php artisan ui vue --auth
command will create all of the views you need for authentication and place them in the resources/views/auth
directory.
The ui
command will also create a resources/views/layouts
directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.
Authenticating
Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.
Path Customization
When a user is successfully authenticated, they will be redirected to the /home
URI. You can customize the post-authentication redirect path using the HOME
constant defined in your RouteServiceProvider
:
public const HOME = '/home';
If you need more robust customization of the response returned when a user is authenticated, Laravel provides an empty authenticated(Request $request, $user)
method within the AuthenticatesUsers
trait. This trait is used by the LoginController
class that is installed into your application when using the laravel/ui
package. Therefore, you can define your own authenticated
method within the LoginController
class:
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
return response([
//
]);
}
Username Customization
By default, Laravel uses the email
field for authentication. If you would like to customize this, you may define a username
method on your LoginController
:
public function username()
{
return 'username';
}
Guard Customization
You may also customize the "guard" that is used to authenticate and register users. To get started, define a guard
method on your LoginController
, RegisterController
, and ResetPasswordController
. The method should return a guard instance:
use Illuminate\Support\Facades\Auth;
protected function guard()
{
return Auth::guard('guard-name');
}
Validation / Storage Customization
To modify the form fields that are required when a new user registers with your application, or to customize how new users are stored into your database, you may modify the RegisterController
class. This class is responsible for validating and creating new users of your application.
The validator
method of the RegisterController
contains the validation rules for new users of the application. You are free to modify this method as you wish.
The create
method of the RegisterController
is responsible for creating new App\User
records in your database using the Eloquent ORM. You are free to modify this method according to the needs of your database.
Retrieving The Authenticated User
You may access the authenticated user via the Auth
facade:
use Illuminate\Support\Facades\Auth;
// Get the currently authenticated user...
$user = Auth::user();
// Get the currently authenticated user's ID...
$id = Auth::id();
Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request
instance. Remember, type-hinted classes will automatically be injected into your controller methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
/**
* Update the user's profile.
*
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
// $request->user() returns an instance of the authenticated user...
}
}
Determining If The Current User Is Authenticated
To determine if the user is already logged into your application, you may use the check
method on the Auth
facade, which will return true
if the user is authenticated:
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// The user is logged in...
}
Even though it is possible to determine if a user is authenticated using the check
method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on protecting routes.