Ultimate Laravel Authentication Tutorial with Practical Examples

Laravel provides a simple, and seamless authentication mechanism to validate the logged in users. In this Laravel Authentication Tutorial, you will learn the basics of how users are authenticated in Laravel? Read Laravel Quickstart Tutorial to understand the fundamentals concepts.

Laravel Authentication – Introduction

Setting up user registration and login is the foundation of any web application. Laravel authentication is all about this. In this Laravel Authentication tutorial, we will touch everything related to user login, register, sessions, passwords resets, and list of available Laravel authentication methods. Before setting up user login/register forms, understand how Laravel handles HTTP requests?

Laravel authentication is the inbuilt mechanism to verifying the user credentials which is very easy to use and understand. To authenticate a user or protect a route in Laravel, Laravel Developers just need to call few Laravel authentication methods.

If you are a beginner to Laravel MVC, then we recommend you to read the following topics:

Let’s see how this all work together in this Laravel Authentication Tutorial guide.

How User Authentication Works in Laravel?

Every new installation in Laravel comes with ‘create_users_table‘ migration and a User model.Laravel framework offers a “php artisan make::auth” Artisan command that creates a collection of authentication-related views and routes and controllers.

Pre-built Laravel Authentication Controllers

The default authentication controllers are – a RegisterController, a LoginController, a ForgotPasswordController, and a ResetPasswordController. These authentication APIs are simple and clean, and the conventions all work together to provide a simple—and seamless—authentication and authorization system.

Laravel’s authentication mechanism works on the concept of Guards and Providers. These guards are facades which defines how the users should be authenticated upon each request.

Laravel Authentication Tutorial will also list down the important authentication methods.

Every new Laravel Installation comes with pre-installed authentication controllers. These are controller files are located at App\Http\Controllers\Auth namespace.

LoginController – handles authentication of users upon each Laravel Request.

RegisterController – handles registration of new users into the system and stores the new user details into users table using User Model.

The output will show “Authentication Scaffolding generated successfully”.

This command will create the basic login & registration authentication components – layout views, routes, and necessary controllers. The login & registration layout views are created under resources/views/auth location and routes are added in the routes.php file located under app/Http/routes.php

The Laravel Artisan command make:auth will also create a basic layout of the application under resources/views/layouts.

By default, Laravel makes use of Bootstrap CSS template to create all the view files.

Here, the $redirectTo is property of LoginController, RegisterController, and ResetPasswordController controllers.We can also define redirectTo() method in these controllers files.

Customize Login Controller to add username in Laravel

During the authentication process, By default Laravel make use of email field to authenticate the user credentials and compare with the corresponding record in the user’s table. To customize process you can add username() method to enable username-based authentication in Laravel. Add the username() method to the LoginController().

What is Guard in Laravel? How to Customize Laravel Guard?

Each and every aspect of Laravel’s authentication system is routed through something called a guard.

Each guard is a combination of two pieces: a driver that defines how it persists and retrieves the authentication state (for example, session), and a provider that allows you to get a user by certain criteria (for example, users).

Changing the Default Guard:All the guard are defined in the ../config/auth.php file. You can change the default guard, add new guards, change the default guard. The default guard is the one which is used any time you use any auth features.The auth()->user() call will get the currently authenticated user using the default guard.

Get the Currently authenticated User’s ID:

// Get the currently authenticated user’s ID…$id = Auth::id();

How to protect routes in Laravel?

Before allowing the users to play with various features of an application, so there could be a set of routes that should be accessed by authenticated users only. Laravel authentication mechanism provides default auth() middleware to protect the specific routes.

Developers need to attach the auth middleware to all those routes which need to be protected.

Protect a single route:Route::get(‘profile’, function () { // Only authenticated users may enter…})->middleware(‘auth’);

How to check un-authenticated user in Laravel?

Suppose in the views, you have to check if the current user is a logged-in or un-authenticated user:

@if(Auth::guest()) <!– some logic —>@endif

List of Laravel Authentication Methods

Laravel Auth facade provides a set of methods for performing common tasks:

Auth::check() – check if the current user is authenticated or not. returns true if the user is authenticated otherwise false.

Auth::user() – Retrieving the authenticated user information.

Auth::id() – returns the user ID of currently logged-in user.

Auth::logout() – do lohout from the current session.

Auth::login() – authenticate new user.

Auth::loginUsingId(1) – authenticate user by ID

Auth::once() – authenticate the user for current single request only, no sessions.cookies will be utilized.

Auth::guest() – returns true if the current user is not logged-in

Manually Authenticating Users in Laravel

By default, for user authentication the user’s input provides their credentials, and then use auth()->attempt() to see whether the provided credentials match any real users. If so, you log them in.

But sometimes there are cases where you want to to be able to choose to log a user in on your own. For example, you may want to allow admin users to switch users. There are two methods that make this possible. First, you can just pass a user ID:

auth()->loginUsingId(5);

Second, you can pass a User object (or any other object that implements the Illuminate\Contracts\Auth\Authenticatable contract):auth()->login($user);

Conclusion

We have tried our best to collect all the Laravel Authentication related methods and information at a single place so that developers can use this post later as a reference. If you liked, then please share on social media to appreciate our work. We will keep posing the latest Laravel Authentication Tutorial articles.