Laravel Breeze is a lightweight starter kit that provides a simple and convenient way to implement authentication in Laravel applications. It was introduced in Laravel version 8.x as a replacement for the deprecated Laravel UI package.
Laravel Breeze provides a simple way to implement Laravel’s all authentication features like login, registration, password reset, email verification, and password confirmation in Laravel application.
It provides a view layer with its Tailwind CSS. If you need to build a fast startup for your application then you should use it.
To use Laravel Breeze, you need to create a new Laravel application, configure a database, and run migration.
Breeze utilizes Laravel’s built-in authentication features and includes the necessary views, routes, and controllers to quickly set up a fully functional authentication system. It is designed to be easy to use and customizable, making it a great starting point for new Laravel projects or for quickly adding authentication to existing projects.
To follow this tutorial, you will need the following:
With these requirements in place, you’ll be ready to start building your Laravel Breeze application. In the next section, we’ll go over the installation and setup process.
laravel new laravel-breeze cd laravel-breeze
php artisan migrate
composer require laravel/breeze --dev
php artisan breeze:install npm install npm run dev
You can check all your auth routes in web/auth.php file
There are routes for Login, Register, Forgot Password, Reset Password, Verify Email, Confirm Password.
Now run your app and open http://localhost:8000/login and http://localhost:8000/register to view the output.
As you run your application you will find the following screen scaffold for your application.
You are good to go! Enjoy!
Before we can start using Laravel Breeze, we need to install it and configure our Laravel application to use it. In this section, we will cover the installation process and explain how to run the Laravel Breeze installer.
The first step in installing Laravel Breeze is to open up your command-line interface and navigate to the root directory of your Laravel application. Once you are in the root directory, run the following command to install Laravel Breeze:
composer require laravel/breeze --dev
This will download and install the necessary dependencies for Laravel Breeze.
After Laravel Breeze has been installed, we can run the Laravel Breeze installer to generate the authentication scaffolding. To do this, run the following command in your terminal:
php artisan breeze:install
This will generate the necessary views, routes, and controllers needed for authentication. Additionally, it will update the application’s webpack.mix.js file to include the necessary assets for the authentication views.
Once the installer has finished running, you can verify that the authentication scaffolding has been generated by navigating to the routes/web.php file in your Laravel application. You should see the following lines of code:
use Laravel\Jetstream\Jetstream; Route::middleware(['web', 'guest'])->group(function () { Route::get('/register', [RegisteredUserController::class, 'create']) ->name('register'); Route::post('/register', [RegisteredUserController::class, 'store']); Route::get('/login', [AuthenticatedSessionController::class, 'create']) ->name('login'); Route::post('/login', [AuthenticatedSessionController::class, 'store']); }); Route::middleware(['web', 'auth'])->group(function () { Route::get('/dashboard', function () { return view('dashboard'); })->name('dashboard'); Route::post('/logout', [AuthenticatedSessionController::class, 'destroy']) ->name('logout'); });
These routes define the authentication endpoints and controllers that were generated by the Laravel Breeze installer.
Congratulations, you have successfully installed and set up Laravel Breeze in your Laravel application. In the next section, we will cover how to create a basic authentication system with Laravel Breeze.
Before we can start using Laravel Breeze’s authentication features, we need to configure our database connection. Laravel Breeze uses Laravel’s built-in authentication features, which require a database to store user information.
To configure the database connection, open up the .env file located in the root directory of your Laravel application. Update the following lines to match your database configuration:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_database_username DB_PASSWORD=your_database_password
Make sure to replace your_database_name, your_database_username, and your_database_password with your actual database credentials.
After you have updated the .env file, run the following command in your terminal to create the necessary tables in your database:
php artisan migrate
This will create the required tables for Laravel’s authentication features, such as users, password_resets, and personal_access_tokens.
With the database connection configured and the necessary tables created, we can now move on to creating a basic authentication system with Laravel Breeze.
Now that we have installed and set up Laravel Breeze, we can start creating a basic authentication system. In this section, we will cover how to generate the authentication scaffolding, configure the authentication guards and providers, add user registration and login functionality, add logout functionality, and customize the authentication views.
To generate the authentication scaffolding, we can use Laravel Breeze’s pre-built commands. Run the following command in your terminal to generate the authentication scaffolding:
php artisan breeze:auth
This will generate the necessary views, routes, and controllers needed for authentication, as well as the front-end assets required for the views.
By default, Laravel Breeze uses Laravel’s built-in authentication guards and providers. However, we can configure these to fit our needs. To configure the authentication guards and providers, open up the config/auth.php file and make the necessary changes.
For example, if you want to use a custom guard and provider for your authentication system, you can update the following lines of code:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], ],
With the authentication scaffolding generated and the guards and providers configured, we can now add user registration and login functionality. By default, Laravel Breeze includes these functionalities in the generated views and controllers.
To access the user registration and login pages, navigate to /register and /login respectively in your application’s URL. From there, you can register a new user or log in with an existing user.
In addition to user registration and login functionality, we also need to add logout functionality. This can be achieved by adding a logout route and controller.
To add the logout route and controller, open up the routes/web.php file and add the following lines of code:
use App\Http\Controllers\Auth\AuthenticatedSessionController; Route::middleware(['auth'])->group(function () { Route::post('/logout', [AuthenticatedSessionController::class, 'destroy']) ->name('logout'); });
This will create a new route that logs the user out when accessed.
Finally, we can customize the authentication views to fit our application’s design. The views can be found in the resources/views/auth directory.
To customize the views, you can modify the HTML and CSS as needed. Additionally, you can also customize the authentication controllers to add additional functionality, such as sending a welcome email to new users.
With these steps completed, you have successfully created a basic authentication system with Laravel Breeze.
Laravel Breeze provides a default registration form that includes the basic fields required for user registration. However, in some cases, you may need to customize the registration form to include additional fields or validate the input of custom fields. In this section, we will cover how to add custom form fields, validate custom form fields, and store custom form data in the database.
To add custom form fields to the registration form, we need to modify the registration view located at resources/views/auth/register.blade.php. You can add additional input fields to the form as needed. For example, if you want to add a “phone number” field, you can add the following code:
<div> <label for="phone_number">Phone Number</label> <input id="phone_number" type="text" name="phone_number" value="{{ old('phone_number') }}" required autofocus> </div>
Once we have added custom form fields, we need to validate them before storing the data in the database. Laravel provides a simple way to validate form input using validation rules. To validate custom form fields, we can add validation rules in the app/Http/Controllers/Auth/RegisteredUserController.php file.
For example, to validate the “phone number” field, we can add the following code to the store method:
$this->validate($request, [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users,email', 'password' => 'required|string|confirmed|min:8', 'phone_number' => 'required|string|max:20', ]);
This will ensure that the “phone number” field is required and has a maximum length of 20 characters.
Once we have added custom form fields and validated the input, we need to store the data in the database. To do this, we need to modify the create method in the app/Actions/Fortify/CreateNewUser.php file.
For example, to store the “phone number” field in the database, we can add the following code to the create method:
public function create(array $input) { return User::create([ 'name' => $input['name'], 'email' => $input['email'], 'password' => Hash::make($input['password']), 'phone_number' => $input['phone_number'], ]); }
This will store the “phone number” field in the user’s table along with the other fields.
With these steps completed, you have successfully customized the registration form in Laravel Breeze and are now able to add, validate, and store custom form data in the database.
Social authentication allows users to log in to your application using their social media accounts, such as Google or Facebook. Laravel Breeze makes it easy to implement social authentication using Laravel’s Socialite package. In this section, we will cover how to set up Socialite, create socialite login and registration routes, and implement socialite login and registration functionality.
To set up Socialite, we need to install it via composer. You can do this by running the following command in your terminal:
composer require laravel/socialite
Once installed, we need to configure Socialite by adding the necessary credentials to the .env file. For example, if you want to use Google authentication, you would add the following lines to the .env file:
GOOGLE_CLIENT_ID=your-client-id GOOGLE_CLIENT_SECRET=your-client-secret GOOGLE_REDIRECT_URI=https://your-app-url.com/login/google/callback
Next, we need to create the routes for socialite login and registration. In the routes/web.php file, we can add the following code:
// Socialite Login Route::get('/login/{provider}', [AuthenticatedSessionController::class, 'redirectToProvider'])->name('login.provider'); Route::get('/login/{provider}/callback', [AuthenticatedSessionController::class, 'handleProviderCallback']); // Socialite Registration Route::get('/register/{provider}', [RegisteredUserController::class, 'redirectToProvider'])->name('register.provider'); Route::get('/register/{provider}/callback', [RegisteredUserController::class, 'handleProviderCallback']);
Finally, we can implement socialite login and registration functionality by modifying the AuthenticatedSessionController and RegisteredUserController files.
To implement socialite login, we can modify the redirectToProvider method in the AuthenticatedSessionController file:
public function redirectToProvider($provider) { return Socialite::driver($provider)->redirect(); }
This will redirect the user to the social media login page.
To handle the callback from the social media login page, we can modify the handleProviderCallback method in the AuthenticatedSessionController file:
public function handleProviderCallback($provider) { $user = Socialite::driver($provider)->user(); $user = User::firstOrCreate([ 'email' => $user->getEmail(), ], [ 'name' => $user->getName(), 'password' => Hash::make(Str::random(20)), ]); Auth::login($user); return redirect(RouteServiceProvider::HOME); }
This will create a new user with the email and name retrieved from the social media provider, and log them in to your application.
To implement socialite registration, we can modify the redirectToProvider and handleProviderCallback methods in the RegisteredUserController file in a similar manner.
With these steps completed, you have successfully implemented social authentication in Laravel Breeze using Laravel’s Socialite package.
Sometimes, you may need to implement multiple authentication systems in your application. For example, you may want to have one authentication system for regular users and another for administrators. In this section, we will cover how to build a multi-authentication system in Laravel Breeze.
To create multiple authentication guards, we need to modify the config/auth.php file. By default, Laravel Breeze only has one guard named web. We can add additional guards by adding new entries to the guards array. For example, to create a guard named admin, we can add the following code:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], ],
Next, we need to configure multiple authentication providers. Providers define how to retrieve the user model for a given guard. We can add new providers by adding new entries to the providers array. For example, to create a provider named admins, we can add the following code:
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ], ],
Finally, we can create different login and registration forms for different user types by modifying the AuthenticatedSessionController and RegisteredUserController files.
To use a different form for a specific guard, we can add a guard parameter to the route. For example, to use the admin guard for the login and registration forms, we can modify the following routes in the routes/web.php file:
// Admin Login Route::get('/admin/login', [AuthenticatedSessionController::class, 'create']) ->middleware('guest') ->name('admin.login'); Route::post('/admin/login', [AuthenticatedSessionController::class, 'store']) ->middleware('guest') ->validator(AdminLoginRequest::class) ->name('admin.login'); // Admin Registration Route::get('/admin/register', [RegisteredUserController::class, 'create']) ->middleware('guest') ->name('admin.register'); Route::post('/admin/register', [RegisteredUserController::class, 'store']) ->middleware('guest') ->validator(AdminRegistrationRequest::class) ->name('admin.register');
Then, we can create separate AdminLoginRequest and AdminRegistrationRequest classes to handle the validation for the admin forms.
With these steps completed, you have successfully built a multi-authentication system in Laravel Breeze.
By default, Laravel Breeze provides basic views and routes for authentication. However, you may want to customize these views and add your own routes and controllers. In this section, we will cover how to customize Laravel Breeze views and routes.
To customize the login and registration views, we can publish the Laravel Breeze views using the following command:
php artisan breeze:publish
This will publish the views to the resources/views/vendor directory. From there, we can modify the views as needed.
For example, we can modify the login.blade.php view to add custom HTML and CSS:
@extends('layouts.app') @section('content') <div class="card"> <div class="card-header">{{ __('Login') }}</div> <div class="card-body"> <form method="POST" action="{{ route('login') }}"> @csrf <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Email') }}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <div class="col-md-6 offset-md-4"> <div class="form-check"> <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}> <label class="form-check-label" for="remember"> {{ __('Remember Me') }} </label> </div> </div> </div> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('Login') }} </button> @if (Route::has('password.request')) <a class="btn btn-link" href="{{ route('password.request') }}"> {{ __('Forgot Your Password?') }} </a> @endif </div> </div> </form> </div> </div> @endsection
To add custom routes and controllers, we can create new routes in the routes/web.php file and create new controllers in the app/Http/Controllers directory.
For example, we can add a new route for a dashboard page and create a new controller to handle the logic for the dashboard:
Route::get('/dashboard', [DashboardController::class, 'index'])
Install the Google Authenticator package:
Publish the configuration file:
Migrate the database:
Configure the Google Authenticator package:
Configure the User Model:
Configure the Middleware:
Once you have completed these steps, your Laravel Breeze application will be set up with two-factor authentication. The next step is to configure the two-factor authentication views.
Customize the Two-Factor Authentication Views:
Configure the Two-Factor Authentication Routes:
That’s it! You have successfully configured the two-factor authentication views in your Laravel Breeze application. The next step is to test the two-factor authentication process.
Enable Two-Factor Authentication for a User:
Test Two-Factor Authentication:
Congratulations! You have successfully tested the two-factor authentication process in your Laravel Breeze application.
This will limit the number of requests to 60 per minute for each user
Add the \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class middleware to the $middlewareGroups array
$this->app['router']->middleware('secure.headers', \App\Http\Middleware\SecureHeaders::class);
public function handle($request, Closure $next) { $response = $next($request); $response->headers->set('X-Content-Type-Options', 'nosniff'); $response->headers->set('X-Frame-Options', 'SAMEORIGIN'); $response->headers->set('X-XSS-Protection', '1; mode=block'); $response->headers->set('Referrer-Policy', 'same-origin'); $response->headers->set('Permissions-Policy', 'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()'); return $response; }
This will configure the HTTP secure headers for your Laravel Breeze application
Gate::define('update-post', function ($user, $post) { return $user->id === $post->user_id; });
Use the @can Blade directive in your views to check if the user is authorized to perform a certain action, for example:
@can(‘update-post’, $post)
<a href=”{{ route(‘posts.edit’, $post->id) }}”>Edit Post</a>
@endcan
Congratulations! You have successfully secured your Laravel Breeze application.
public function test_registration_requires_name() { $response = $this->post('/register', [ 'name' => '', 'email' => '[email protected]', 'password' => 'password', 'password_confirmation' => 'password' ]); $response->assertSessionHasErrors('name'); }
Use Laravel’s built-in error logging and debugging features, such as:
Congratulations! You have successfully tested and debugged your Laravel Breeze application.
php artisan key:generate --show
php artisan optimize php artisan config:cache php artisan route:cache php artisan view:cache
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
composer install --no-dev php artisan key:generate --show
php artisan migrate --seed
Congratulations! You have successfully deployed your Laravel Breeze application to a production server.
In conclusion, Laravel Breeze is a powerful authentication solution for Laravel applications that provides a simple and elegant way to implement authentication features quickly. Throughout this tutorial, we have covered various aspects of Laravel Breeze, from installation and setup to customizing views and implementing two-factor authentication.
Some of the key takeaways from this tutorial include:
With the knowledge gained from this tutorial, you can start building robust and secure Laravel applications with Laravel Breeze.
As a next step, you can explore the various advanced features of Laravel Breeze, such as email verification, password confirmation, and user roles and permissions.
Finally, if you want to learn more about Laravel and its ecosystem, you can check out the official Laravel documentation, Laracasts, and other resources available online.
Thank you for following along with this Laravel Breeze tutorial, and happy coding!
Subscribe to our newsletter and learn about the latest digital trends.