Introduction to Laravel Breeze
Laravel Breeze is a lightweight and minimalist authentication system that comes pre-installed with Laravel 8. Its purpose is to simplify the process of adding user authentication to Laravel applications. Laravel Breeze is often compared to UI and Jetstream. Laravel Breeze replaces the deprecated Laravel UI, while Laravel Jetstream is an advanced form of Laravel Breeze.
One of the main benefits of Laravel Breeze is its simplicity. It provides a straightforward way to add authentication to your application without requiring a lot of configuration or setup. This can save developers a significant amount of time and effort, especially if they are new to Laravel or web development.
Laravel Breeze also provides a consistent and intuitive user interface for authentication features such as registration, login, password reset, and email verification. The authentication views are built using Tailwind CSS, which provides a modern and responsive design out of the box. Developers can easily customize the views to fit the branding and design of their application.
Another benefit of Laravel Breeze is its compatibility with Laravel Jetstream, which is a more robust authentication system that includes features such as two-factor authentication and API token generation. Developers can start with Laravel Breeze and then upgrade to Laravel Jetstream if they need more advanced authentication features.
This tutorial walks you through Laravel Breeze's installation, flow, configuration, and usage. It would help to have basic Laravel skills before proceeding with this tutorial.
Installation
Install Laravel: Before you can install Laravel Breeze, you need to have a Laravel application set up. If you haven't done this already, you can follow the installation instructions on the Laravel website.
Install Laravel Breeze: Once you have a Laravel application set up, you can install Laravel Breeze using Composer. Open a terminal window and navigate to your Laravel application directory.
Then, run the following command:
composer require laravel/breeze --dev
This will install Laravel Breeze as a dev dependency in your application.
Run the Breeze install command: Once Laravel Breeze is installed, you can run the Breeze install command to set up the authentication scaffolding in your application. Run the following command in your terminal:
php artisan breeze:install
This command will create the authentication views, routes, and controllers in your application. It will also install the necessary dependencies, including Tailwind CSS.
Run the following command to compile the front-end assets:
npm install && npm run dev
Migrate the database: Laravel Breeze requires a database table to store user information. To create this table, run the following command in your terminal:
php artisan migrate
This will create the necessary database table for user authentication.
That's it! Laravel Breeze is now installed.
How Laravel Breeze Works
Laravel Breeze overrides the contents of the routes/web.php
.
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
require __DIR__.'/auth.php';
The middleware
route authenticates a user before accessing the dashboard, whereas the profile
routes control the interaction with a logged-in user's profile. Related auth functionality is found in the routes/auth.php
file, that is reachable via require __DIR__.'/auth.php;
.
Some of the key functionalities of Laravel Breeze include user registration, login, and password reset.
Registration
A user makes a registration request at resources/views/auth/register.blade.php
file.
The request goes to the register
route found in routes/auth.php
file. The registration logic is grabbed from the RegisteredUserController
controller's store
method defined in the App\Http\Controllers\Auth\RegisteredUserController.php
file.
<?php
...
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
...
The store
method validates the details and creates the User
model's instance called $user
. The user's name
,email
, and hashed password
are stored in the database alongside the id
and timestamps
.
The event
function sends a verification email to the registered user. The email verification logic is found in the sendEmailVerificationNotification
class in the app/Providers/EventServiceProvider.php
file.
Email Verification
The email verification is disabled by default. You can enable it in the app/Models/User.php
file. Open the file then connect the User class to MustVerifyEmail
contract.
<?php
...
use Illuminate\Contracts\Auth\MustVerifyEmail;
...
class User extends Authenticatable implements MustVerifyEmail
{
//...
}
Email Testing -> Inboxes -> Settings
Choose a Laravel version under Integrations. Next, copy the given code, return to .env
file of your Laravel application and replace the MAIL variables with the copied code.
from
MAIL_MAILER=smtp MAIL_HOST=mailpit MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS="hello@example.com" MAIL_FROM_NAME="${APP_NAME}"
to
MAIL_MAILER=smtp MAIL_HOST=sandbox.smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=<mailtrap_email_id> MAIL_PASSWORD=<mailtrap_password_id> MAIL_ENCRYPTION=tls
Now a new registration will require email verification. Also, the user's email_verified_at
timestamp should be updated.
The verification logic is defined in theapp/Http/Controllers/Auth/EmailVerificationPromptController.php
file. The verified user can log in to the dashboard using the Auth
facade's login
method.
Login
Laravel Breeze validates the user before attempting to authenticate them. The user makes a login request at the resources/views/auth/login.blade.php
file. The request is sent to routes/auth.php
file and decoded at AuthenticatedSessionController
controller's store
method found at app\Http\Controllers\Auth\AuthenticatedSessionController.php
file.
<?php
use App\Http\Requests\Auth\LoginRequest;
...
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
...
The $request->authenticate()
method authenticates the user. The authenticate
method is implemented in app\Http\Requests\Auth\LoginRequest.php
file.
<?php
...
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
...
The user can log in to their dashboard if the email and password exist in the database.
The login destination is defined in the RouteServiceProvider
class' HOME
attribute in the app/Providers/RouteServiceProvider.php
file.
<?php
...
class RouteServiceProvider extends ServiceProvider
{
...
public const HOME = '/dashboard';
...
}
Another remarkable feature of Laravel Breeze is that it lets you reset your password.
But how does this happen?
Let's find out.
Password Reset
A user clicks on the Forgot your password? link. The request is sent to the forgot-password
route in the routes/auth.php
file. The logic is traced to the store
method of the PasswordResetLinkController
controller in the app/Http/Controllers/Auth/PasswordResetLinkController.php
file.
<?php
...
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
...
Laravel Breeze presents a user with a form. The user enters their email, and Laravel authenticates the email address before returning an error message or sending a reset password message to the user's email address.
Conclusion
In summary, Laravel Breeze is a lightweight and minimalist authentication system that comes pre-installed with Laravel 8. It provides a quick and easy way to add user authentication to Laravel applications.
The key authentication features provided by Laravel Breeze include registration, email verification, login, and password reset. These features are easy to use and customize, and the authentication views are built using Tailwind CSS for a modern and responsive design.
One of the main benefits of Laravel Breeze is its simplicity. It simplifies the process of adding authentication to Laravel applications and saves developers time and effort. It also provides a consistent and intuitive user interface for authentication features.