Laravel 11 Login and Register

Laravel 11 Login and Register

Laravel 11 Login and Register

In this post, we will give you information about Laravel 11 Login and Register. Here we will give you details about Laravel 11 Login and Register And how to use it also give you a demo for it if it is necessary.

In this tutorial, I will show how to create Laravel 11 Login and Register with step by step guide. Laravel provides a command-line tool called Artisan that makes it easy to generate authentication controllers, views, and routes.

Install Laravel for Laravel 11 Login and Register
If you haven’t already installed Laravel, you can do so using Composer:

composer create-project --prefer-dist laravel/laravel project_name

Configure Database
Update your database configuration in the .env file with your database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

Run Migrations
Run the migrations to create the necessary tables for authentication:

php artisan migrate

Create Authentication Controllers
Laravel provides artisan commands to generate authentication controllers and views. Run the following commands:

php artisan make:auth

This command will generate controllers, views, and routes necessary for registration and login.

Create Custom Registration Login Routes

In this step, we will need to create our custom user registration and login routes and copy and paste the below code in routes/web.php file.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\LoginRegisterController;

Route::get('/', function () {
    return view('welcome');
});
// Laravel 11 Login and Register Route
Route::controller(LoginRegisterController::class)->group(function() {
    Route::get('/register', 'register')->name('register');
    Route::post('/store', 'store')->name('store');
    Route::get('/login', 'login')->name('login');
    Route::post('/authenticate', 'authenticate')->name('authenticate');
    Route::get('/dashboard', 'dashboard')->name('dashboard');
    Route::post('/logout', 'logout')->name('logout');
});

In the above code, we have defined the routes for user registration form and registration form submission which will store user data into our user table.

Then we define the routes for our login form and processing login form, it will authenticate the user, and if it gets successful, it will be redirected to the dashboard.

Finally, we defined our dashboard and logout routes which will be accessed only after logging in to the application.

We have also given names to each route for convenience use.

Create a LoginRegister Controller

In this step, we will create a controller with the name LoginRegisterController with the six (6) methods in it which are listed below.

  1. register() -> To display the registration form
  2. store() -> To store the registration form data
  3. login() -> To display the login form
  4. authenticate() -> To authenticate the login user credentials
  5. dashboard() -> To display the dashboard screen to an authenticated user
  6. logout() -> To perform the logout operation by the user

As their names, you can presume what these methods will do, register() method will display the registration form, and store() method will process the registration form data and save it into the database.

Similarly, login() method will display the login form, and authenticate() method will process the login form after the login form submission.

Run the below command to create a LoginRegisterController controller.

php artisan make:controller Auth\LoginRegisterController

The above command will create a controller in the app\Http\Controllers\Auth\ directory, simply copy and paste the below code in the app\Http\Controllers\Auth\LoginRegisterController.php

<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class LoginRegisterController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest')->except([
            'logout', 'dashboard'
        ]);
    }

    public function register()
    {
        return view('auth.register');
    }
    // Laravel 11 Login and Register 
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:250',
            'email' => 'required|email|max:250|unique:users',
            'password' => 'required|min:8|confirmed'
        ]);

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

        $credentials = $request->only('email', 'password');
        Auth::attempt($credentials);
        $request->session()->regenerate();
        return redirect()->route('dashboard')
        ->withSuccess('You have successfully registered & logged in!');
    }

    public function login()
    {
        return view('auth.login');
    }
   
    public function authenticate(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if(Auth::attempt($credentials))
        {
            $request->session()->regenerate();
            return redirect()->route('dashboard')
                ->withSuccess('You have successfully logged in!');
        }

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

    } 
    
    public function dashboard()
    {
        if(Auth::check())
        {
            return view('auth.dashboard');
        }
        
        return redirect()->route('login')
            ->withErrors([
            'email' => 'Please login to access the dashboard.',
        ])->onlyInput('email');
    } 
    
    /**
     * Log out the user from application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login')
            ->withSuccess('You have logged out successfully!');;
    }    

}

We have additionally added a constructor in the above controller to add the middleware to our routes, only logout and dashboard routes can be accessible after logging in to the application, all the other routes can be accessed without login to the system.

This is mandatory as we do not want anyone to access the login or registration form after successfully logging into the application.

Similarly, we also do not want anyone to access the logout and dashboard without logging in to the system.

This is why we have added the constructor and defined our middleware.

Define Your New Home

As we have defined our middleware for auth and guest routes so If anyone tries to access the login URL after successful login, well Laravel will redirect the user to the default home route which does not exist in our application.

In our case, it is the dashboard route which is our default route for those who try to access the login or register after successful login.

So we will need to make a small change in the file CustomLoginRegister\app\Providers\RouteServiceProvider.php

Just replace the home with a dashboard. Find the below line of code in the RouteServiceProvider.php

public const HOME = '/home';

And replace it with the following line.

public const HOME = '/dashboard';

Create Login Register Blade View Files

We will need to create an auth directory in resources/views/ and then create the following files in it to make the views of our login, registration, and dashboard for Laravel 11 Login and Register.

  1. layouts.blade.php
  2. register.blade.php
  3. login.blade.php
  4. dashboard.blade.php

layouts.blade.php is the main layout of our login & registration application, so just copy and paste the below code in file resources/views/auth/layouts.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel 11 Login and Register</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" >
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"  ></script>     
</head>
<body>
    <nav class="navbar navbar-expand-lg bg-light">
        <div class="container">
          <a class="navbar-brand" href="{{ URL('/') }}">Custom Login Register</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarNavDropdown">
            <ul class="navbar-nav ms-auto">
                @guest
                    <li class="nav-item">
                        <a class="nav-link {{ (request()->is('login')) ? 'active' : '' }}" href="{{ route('login') }}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {{ (request()->is('register')) ? 'active' : '' }}" href="{{ route('register') }}">Register</a>
                    </li>
                @else    
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            {{ Auth::user()->name }}
                        </a>
                        <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="{{ route('logout') }}"
                            onclick="event.preventDefault();
                            document.getElementById('logout-form').submit();"
                            >Logout</a>
                            <form id="logout-form" action="{{ route('logout') }}" method="POST">
                                @csrf
                            </form>
                        </li>
                        </ul>
                    </li>
                @endguest
            </ul>
          </div>
        </div>
    </nav>
    <div class="container">
        @yield('content')
    </div>       
</body>
</html>

register.blade.php is the registration page of our application, copy and paste the below code in file  resources/views/auth/register.blade.php

@extends('auth.layouts')
@section('content')
<div class="row justify-content-center mt-5">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">Register</div>
            <div class="card-body">
                <form action="{{ route('store') }}" method="post">
                    @csrf
                    <div class="mb-3 row">
                        <label for="name" class="col-md-4 col-form-label text-md-end text-start">Name</label>
                        <div class="col-md-6">
                          <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name') }}">
                            @if ($errors->has('name'))
                                <span class="text-danger">{{ $errors->first('name') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label for="email" class="col-md-4 col-form-label text-md-end text-start">Email Address</label>
                        <div class="col-md-6">
                          <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" value="{{ old('email') }}">
                            @if ($errors->has('email'))
                                <span class="text-danger">{{ $errors->first('email') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label for="password" class="col-md-4 col-form-label text-md-end text-start">Password</label>
                        <div class="col-md-6">
                          <input type="password" class="form-control @error('password') is-invalid @enderror" id="password" name="password">
                            @if ($errors->has('password'))
                                <span class="text-danger">{{ $errors->first('password') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label for="password_confirmation" class="col-md-4 col-form-label text-md-end text-start">Confirm Password</label>
                        <div class="col-md-6">
                          <input type="password" class="form-control" id="password_confirmation" name="password_confirmation">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <input type="submit" class="col-md-3 offset-md-5 btn btn-primary" value="Register">
                    </div>                    
                </form>
            </div>
        </div>
    </div>    
</div>    
@endsection

login.blade.php is the login page of our application, copy and paste the below code in file resources/views/auth/login.blade.php

@extends('auth.layouts')
@section('content')
<div class="row justify-content-center mt-5">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">Login</div>
            <div class="card-body">
                <form action="{{ route('authenticate') }}" method="post">
                    @csrf
                    <div class="mb-3 row">
                        <label for="email" class="col-md-4 col-form-label text-md-end text-start">Email Address</label>
                        <div class="col-md-6">
                          <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" value="{{ old('email') }}">
                            @if ($errors->has('email'))
                                <span class="text-danger">{{ $errors->first('email') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label for="password" class="col-md-4 col-form-label text-md-end text-start">Password</label>
                        <div class="col-md-6">
                          <input type="password" class="form-control @error('password') is-invalid @enderror" id="password" name="password">
                            @if ($errors->has('password'))
                                <span class="text-danger">{{ $errors->first('password') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <input type="submit" class="col-md-3 offset-md-5 btn btn-primary" value="Login">
                    </div>                    
                </form>
            </div>
        </div>
    </div>    
</div>    
@endsection

dashboard.blade.php is the dashboard page of our application, copy and paste the below code in file resources/views/auth/dashboard.blade.php

@extends('auth.layouts')
@section('content')
<div class="row justify-content-center mt-5">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">Dashboard - Laravel 11 Login and Register</div>
            <div class="card-body">
                @if ($message = Session::get('success'))
                    <div class="alert alert-success">
                        {{ $message }}
                    </div>
                @else
                    <div class="alert alert-success">
                        You are logged in with Laravel 11 Login and Register!
                    </div>       
                @endif                
            </div>
        </div>
    </div>    
</div>    
@endsection

Make one more minor change in your welcome.blade.php, as the home route is hardcoded in it, just search it and replace it with a dashboard.

Search the below code for Laravel 11 Login and Register

url('/home')

and replace it with the following for Laravel 11 Login and Register

url('/dashboard')

8. Run Laravel Development Server

Now we have completed all the steps that are required to develop Laravel 11 custom user registration and login, so run the Laravel development server to test our application using the below command.

php artisan serve

Then open your web browser and browser or visit the following URL to test your Laravel 11 custom user registration and login.

http://127.0.0.1:8000/register

If you found this tutorial helpful, share it with your friends and developers group.

Conclusion for Laravel 11 Login and Register

Hope this code and post will help you implement Laravel 11 Login and Register. if you need any help or any feedback give it in the comment section or if you have a good idea about this post you can give it in the comment section. Your comment will help us to help you more and improve us.

For More Info See: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

5  +  3  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US