Authentication — Laravel 10 Discovery Training

In this chapter we will see the authentication part on Laravel which will allow users to connect and which will also limit access to certain parts of the site to only connected users.

Laravel, when installed, already includes a system of users (there is a model User and the corresponding migrations). This model is relatively simple, it just has the particularity of extending from Authenticablewhich integrates methods related to authentication.

class User extends Authenticatable
{
    //....
}

Then to interact with the authentication we can use the facade Auth which will contain different interesting methods:

use Illuminate\Support\Facades\Auth;

// Essaie de connecter un utilisateur et renvoie true en cas de succès
Auth::attempt([
    'email' => 'john@doe.fr'
    'password' => '0000'
]);

// Connecte un utilisateur manuellement
Auth::login($user); 

// Renvoie l'utilisateur connecté ou null
$user = Auth::user(); 

// Renvoie l'id de l'utilisateur connecté ou null
$id = Auth::id();

Authentication-related configuration can be managed through the configuration file config/auth.php.

Login

To allow the user to connect we will create a form allowing the user to enter his email and password. We will then create an action in our controller which will verify that these identifiers are valid and which will authenticate the user in the event that the password corresponds to the email.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function authenticate(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            return redirect()->intended('dashboard');
        }

        return back()->withErrors([
            'email' => 'Identifiants incorrects.',
        ])->onlyInput('email');
    }
}

Note the use of several specific methods in this controller:

  • The method session() on $request allows us to obtain session-saved information for the user. We will use the method regenerate in order to generate a new session and avoid session theft.
  • In case of error we will use the methods withErrors() And onlyIinput() to return errors and information previously entered by the user, respectively.

It is the user has entered correct information he is then authenticated on the application and can continue to navigate. The method intended redirects the user to the page he originally requested before being redirected to the login form.

Authorisation

Now that we have our authentication system, we must be able to limit access to certain pages of our site to authenticated users only. For this we have the possibility to use the middleware auth which will make it possible to limit access to a group of routes.

Route::middleware(['auth'])->group(function () {
    // ...
});

For a finer permission system we will mention the system of Policy later that will allow us to manage access based on specific conditions.

starter kits

Here we have set up a simple connection system but if we want to set up a complete user account system (registration, password reminder, account confirmation…) there is a lot of code to write. To simplify the task Laravel of the Starter kits which allow to create the complete user account system.

We’ll talk about these starter kits later in the training using one of them, Laravel Breeze, but I’ll let you look at the documentation if you’re curious.