Share this:

In this blog, we will explore Laravel 10 custom login and registration feature. We will create a web application that will include a personalized user login and registration system with email verification and password reset functionality.

By the end of this tutorial, you will have a better understanding of Laravel’s authentication system and how to implement it in your projects.

Table of Contents

  1. Introduction to Laravel 10
  2. Prerequisites
  3. Setting up a Laravel 10 project
  4. Creating a database and configuring the environment
  5. Generating authentication scaffolding
  6. Customizing registration and login forms
  7. Adding email verification
  8. Implementing password reset functionality
  9. Testing the custom login and registration system
  10. Conclusion

Introduction to Laravel 10

Laravel is a popular PHP framework designed to make web application development fast, simple, and enjoyable. Laravel 10, the latest version, introduces new features and improvements that enhance the overall development experience. One of the most powerful aspects of Laravel is its built-in support for user authentication. Laravel provides a simple and secure way to manage user registration, login, and password reset functionality.

In this tutorial, we will walk you through the process of creating a custom login and registration system using Laravel 10. We will customize the default authentication scaffolding provided by Laravel and add email verification and password reset functionality to our web application.

Prerequisites

Before we begin, ensure you have the following installed on your system:

  • PHP >= 8.1
  • Composer
  • Laravel Installer
  • A local development environment (such as Laravel Valet, Homestead, or XAMPP)

Additionally, you should have basic knowledge of Laravel, PHP, HTML, and CSS. Familiarity with Laravel’s Blade templating engine and Eloquent ORM is also helpful.

Setting up a Laravel 10 project

First, open your terminal (or command prompt) and run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel custom-auth

Once the installation is complete, navigate to the project directory:

cd custom-auth
Setting up a Laravel 10 project
Setting up a Laravel 10 project

To ensure that your Laravel installation is successful, run the built-in development server:

php artisan serve

Visit http://localhost:8000 in your web browser, and you should see the Laravel welcome page.

Creating a database and configuring the environment

Before we proceed, create a new MySQL database for our application. You can use a database management tool like phpMyAdmin or MySQL Workbench to do this.

Next, open the .env file in the root of your project and update the database configuration settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

Replace your_database_name, your_database_user, and your_database_password with the appropriate values for your database.

Creating a database and configuring the environment
Creating a database and configuring the environment

Save your changes and close the file.

Generating authentication scaffolding

Install the Laravel UI package:

composer require laravel/ui

Generate the authentication scaffolding with Bootstrap:

php artisan ui bootstrap --auth

This command will generate the authentication scaffolding, including views, routes, and controllers, using the Bootstrap CSS framework. You can also use the --vue or --react options to scaffold with Vue.js or React.js, respectively.

Next, install the required npm dependencies and compile the assets:

npm install
npm run dev

This will install Bootstrap, jQuery, and other required packages, and compile the necessary CSS and JavaScript files.

Customizing registration and login forms

Now, let’s customize the registration and login forms. Open the resources/views/auth/register.blade.php file and modify the form as needed.

For example, you can add new fields, change labels, or update the layout. Don’t forget to add corresponding validation rules in the app/Http/Controllers/Auth/RegisterController.php file.

Similarly, customize the login form by editing the resources/views/auth/login.blade.php file. You can adjust the appearance of the form, add new fields, or modify existing ones.

After customizing the forms, migrate the database to create the necessary tables:

php artisan migrate

Adding email verification

To add email verification, first update the User model located in the app/Models/User.php file. Implement the MustVerifyEmail interface and import the corresponding namespace:

use Illuminate\Contracts\Auth\MustVerifyEmail;

class User extends Authenticatable implements MustVerifyEmail
{
    // ...
}
Adding email verification
Adding email verification

Next, open the app/Http/Controllers/Auth/RegisterController.php file and modify the registered method to send a verification email upon successful registration:

use Illuminate\Auth\Events\Registered;

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    event(new Registered($user));

    return $user;
}

Finally, update the routes/web.php file to include the email verification routes:

use Illuminate\Foundation\Auth\EmailVerificationRequest;

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');

Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'Verification link sent!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.send');

Implementing password reset functionality

To implement password reset functionality, first ensure that the MAIL_* settings in your .env file are properly configured to send emails. You can use an email service like Mailgun or SMTP for this purpose.

Next, open the routes/web.php file and include the password reset routes:

use Illuminate\Support\Facades\Password;

Route::get('/forgot-password', function () {
    return view('auth.forgot-password');
})->middleware('guest')->name('password.request');

Route::post('/forgot-password', function (Request $request) {
    $request->validate(['email' => 'required|email']);
    $status = Password::sendResetLink(
        $request->only('email')
    );
    return $status === Password::RESET_LINK_SENT
                ? back()->with(['status' => __($status)])
                : back()->withErrors(['email' => __($status)]);
})->middleware('guest')->name('password.email');

// Add other password reset routes here

Customize the password reset views in the resources/views/auth/forgot-password.blade.php and resources/views/auth/reset-password.blade.php files. Make any necessary changes to the appearance or layout of these forms.

Finally, add the necessary routes for handling password resets in the routes/web.php file:

use Illuminate\Auth\Events\PasswordReset;

Route::get('/reset-password/{token}', function ($token) {
    return view('auth.reset-password', ['token' => $token]);
})->middleware('guest')->name('password.reset');

Route::post('/reset-password', function (Request $request) {
    $request->validate([
        'token' => 'required',
        'email' => 'required|email',
        'password' => 'required|min:8|confirmed',
    ]);
    $status = Password::reset(
        $request->only('email', 'password', 'password_confirmation', 'token'),
        function ($user, $password) {
            $user->forceFill([
                'password' => Hash::make($password)
            ])->save();
            event(new PasswordReset($user));
        }
    );
    return $status === Password::PASSWORD_RESET
                ? redirect()->route('login')->with('status', __($status))
                : back()->withErrors(['email' => __($status)]);
})->middleware('guest')->name('password.update');

Testing the custom login and registration system

Now that you have implemented the custom login and registration system, it’s time to test it. Start your development server using php artisan serve and visit the following URLs in your browser:

Test the registration process, including email verification. Verify that the login system works as expected, including the password reset functionality.

Conclusion

In this tutorial, we have demonstrated how to create a custom login and registration system using Laravel 10. By following these steps, you can build a secure and robust authentication system for your web applications. With Laravel’s built-in support for user authentication, you can focus on developing your application’s core features without worrying about the complexities of managing user accounts.

Share this:

Categorized in: