Laravel 10 Custom Login and Registration: A Comprehensive Guide

Ravi Rajyaguru

Updated on:

PHP
Laravel 10 Custom Login and Registration A Comprehensive Guide

In this comprehensive guide, we will walk you through the process of creating a custom login and registration system in Laravel 10, covering everything from setting up the environment to creating and validating the registration form. Follow along to learn how to build a robust, secure authentication system for your Laravel applications.

Setting Up the Environment

Before diving into the implementation, ensure that your environment meets the following requirements:

  1. PHP >= 7.4
  2. Composer installed
  3. Laravel Installer

Create a new Laravel project using the following command:

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

For more information on Laravel’s requirements, visit the official Laravel documentation.

Creating the Authentication Scaffold

To generate the authentication scaffold, we will use Laravel Breeze. Install it using the following command:

composer require laravel/breeze --dev

After installing Laravel Breeze, run the following command to generate the authentication scaffold:

php artisan breeze:install

To compile the assets, run:

npm install
npm run dev

Customizing the Registration Form

Navigate to the resources/views/auth/register.blade.php file and add the additional input fields you want to include in the registration form. For this example, let’s add first_name and last_name fields:

<div class="mb-3">
    <label for="first_name" class="form-label">First Name</label>
    <input type="text" name="first_name" id="first_name" class="form-control" value="{{ old('first_name') }}" required autofocus>
</div>

<div class="mb-3">
    <label for="last_name" class="form-label">Last Name</label>
    <input type="text" name="last_name" id="last_name" class="form-control" value="{{ old('last_name') }}" required>
</div>

For more details on Laravel Blade templates, consult the official Blade documentation.

Adding Validation Rules

Navigate to the app/Http/Controllers/Auth/RegisteredUserController.php file and update the store method by adding the following validation rules:

$request->validate([
    'first_name' => ['required', 'string', 'max:255'],
    'last_name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
    'password' => ['required', 'string', 'min:8', 'confirmed'],
]);

Learn more about Laravel’s validation system in the official validation documentation.

Handling User Registration

Update the User model in the app/Models/User.php file by adding the first_name and last_name properties:

protected $fillable = [
    'first_name',
    'last_name',
    'email',
    'password',
];

In the RegisteredUserController‘s store method, update the user creation code to include the first_name and last_name fields:

$user = User::create([
    'first_name' => $request->first_name,
    'last_name' => $request->last_name,
    'email' => $request->email,
    'password' => Hash::make($request->password),
]);

// Log the user in and redirect to the dashboard
Auth::login($user);

return redirect(RouteServiceProvider::HOME);

To implement the custom login system, navigate to the resources/views/auth/login.blade.php file and ensure that the email and password fields are present in the form:

<div class="mb-3">
    <label for="email" class="form-label">Email address</label>
    <input type="email" name="email" id="email" class="form-control" value="{{ old('email') }}" required autofocus>
</div>

<div class="mb-3">
    <label for="password" class="form-label">Password</label>
    <input type="password" name="password" id="password" class="form-control" required>
</div>

Navigate to the app/Http/Controllers/Auth/AuthenticatedSessionController.php file and update the store method with the following validation rules:

$request->validate([
    'email' => ['required', 'string', 'email', 'max:255'],
    'password' => ['required', 'string', 'min:8'],
]);

Now, add the authentication logic to the store method:

$credentials = $request->only('email', 'password');

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

    return redirect()->intended(RouteServiceProvider::HOME);
}

return back()->withErrors([
    'email' => 'The provided credentials do not match our records.',
]);

Testing the Authentication System

After implementing the custom login and registration system, you can test the functionality by running the Laravel development server:

php artisan serve

Navigate to the registration page at http://127.0.0.1:8000/register, fill in the form, and click “Register.” After successful registration, you will be redirected to the dashboard.

Next, navigate to the login page at http://127.0.0.1:8000/login, enter your credentials, and click “Log in.” If the credentials are correct, you will be redirected to the dashboard.

For more information on testing Laravel applications, refer to the official testing documentation.

Conclusion

In this comprehensive guide, we demonstrated how to create a custom login and registration system in Laravel 10 using Laravel Breeze. We covered the essential steps, including setting up the environment, creating the authentication scaffold, customizing the registration form, adding validation rules, handling user registration, implementing the custom login system, and testing the authentication system. With this knowledge, you can now build robust and secure authentication systems for your Laravel applications.

For further reading and advanced topics in Laravel, explore the official Laravel documentation.

Laravel 10 Custom Login and Registration: Frequently Asked Questions

Below are some frequently asked questions and answers related to implementing custom login and registration in Laravel 10.

How can I customize the look and feel of the authentication pages?

You can customize the look and feel of the authentication pages by modifying the corresponding Blade template files located in the resources/views/auth directory. You can apply your desired CSS styles, change the layout, or add new elements to these files.

How can I add social media login functionality to my Laravel application?

To add social media login functionality, you can use Laravel Socialite, an official Laravel package that makes it easy to authenticate users using various OAuth providers, such as Facebook, Twitter, Google, and GitHub. Install the package, configure the required services, and update your application’s authentication system accordingly.

How can I implement Two-Factor Authentication (2FA) in my Laravel application?

To implement Two-Factor Authentication (2FA), you can use a package like laravel/fortify or pragmarx/google2fa-laravel. These packages provide a simple way to add 2FA support to your application. Follow the package’s documentation to set up 2FA, generate and validate tokens, and update your authentication system.

How can I use AJAX for the registration and login processes in Laravel?

To use AJAX for registration and login processes, update the registration and login forms with JavaScript event listeners that intercept the form submission, gather the input data, and send it to your server using AJAX. Then, modify your Laravel authentication controllers to handle AJAX requests and return appropriate JSON responses.

How can I implement email verification for new users in Laravel?

Laravel comes with built-in support for email verification. To implement this feature, update your User model to implement the MustVerifyEmail contract and use the EmailVerification middleware in your routes. Once this is set up, Laravel will automatically send verification emails to newly registered users and require them to verify their email addresses before gaining access to protected routes.

How do I add custom error messages for validation rules?

To add custom error messages for validation rules, create a new language file in the resources/lang/en directory, e.g., custom-validation.php, and define your custom messages in an array. Then, reference this file in the config/app.php file under the validation.language key. Finally, update your validation rules in the authentication controllers to include the custom messages.

How can I customize the redirect URL after successful registration and login?

To customize the redirect URL after successful registration or login, update the RouteServiceProvider class located in the app/Providers directory. Define a new constant for the custom route, and update the HOME constant value accordingly:

public const HOME = '/your-custom-route';

Your application will now redirect users to the specified custom route upon successful registration or login.

How can I implement password reset functionality in Laravel?

Laravel provides built-in support for password reset functionality. To implement this feature, run the following command:

php artisan make:auth

This command generates the necessary routes, controllers, and views for password reset functionality. Update your routes file (routes/web.php) to include the generated password reset routes, and customize the password reset views in the resources/views/auth directory as needed.

How can I restrict access to specific routes for authenticated users?

To restrict access to specific routes for authenticated users, use the auth middleware provided by Laravel. Add the auth middleware to the desired route or route group in the routes/web.php file:

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index')->name('dashboard');
    // ... other protected routes
});

This will ensure that only authenticated users can access the specified routes.

How can I handle role-based authentication in Laravel?

To handle role-based authentication, you can use a package like spatie/laravel-permission. This package provides an easy way to manage user roles and permissions. Install the package, configure it, and create the necessary roles and permissions. Then, use the provided middleware or directives to restrict access to specific routes or parts of your application based on the user’s role or permissions.

Leave a Comment