How to implement a user login & Register form with validation in Laravel | CV create Web | Code Abe Academy

This tutorial will teach you how to make a user login form with validation using Laravel. Let’s do it step by step.




Go to your project file location, and type cmd in the address bar to open the location in the Command Prompt. Then create a new project using following command.

Create a new project
composer create-project laravel/laravel cv-create-web

After creating a new project add database to the .env file. Here I have use MySQL for the database.

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cv_create_app_db
DB_USERNAME=root
DB_PASSWORD=

Login

Now, Let's create the Login. 

  1. Create login.blade.php file.
  2. Add bootstrap CDN link.
  3. Add form-container.
  4. login.blade.php 
     <section class="min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
            <div class="container-fluid">
                <div class="row justify-content-md-center">
                    <div class="col-md-6 ">
                        <div class="card px-5 py-3 mt-3 shadow">
                            <h1 class="text-info text-center mt-2 mb-4">Login to Your Account </h1>
                            <h6 class="text-center mb-3">Enter your username & password to login</h6>
    
                        </div>
                    </div>
                </div>
            </div>
        </section>
    
  5. Add Custom CSS.
  6. Create a new folder named css inside the public directory of your project. Inside the css folder, create a new file named custom.css. Add the following CSS to the custom.css file.

    custom.css
    body {
        background-size: cover;
        background-repeat: no-repeat;
        font-family: "Open Sans", sans-serif;
        background: #f6f9ff;
        color: #444444;
    }

    Connect the custom.css file to your login.blade.php file by adding the this line "<link rel="stylesheet" href="{{ asset('css/custom.css') }}" />" within the <head> tag.

  7. Add form with validation.
  8. login.blade.php 
    <form class="needs-validation" action="" method="POST" novalidate>
            @csrf
            <div class="mb-2">
                <label for="email" class="form-label">Email</label>
                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required>
                <div class="invalid-feedback">
                    Please Enter Your Email.
                </div>
            </div>
            <div class="mb-2">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" name="password" id="password" placeholder="Your Password"
                    required>
                <div class="invalid-feedback">
                    Please Enter Your Password.
                </div>
            </div>
            <div class="mb-2">
                <div class="d-grid">
                    <button class="btn btn-success float-right mt-2">Login</button>
                </div>
            </div>
    
            <div class="mb-2 mt-4">
                <div class="d-grid">
                    <p>Create a New Account <span><a href="{{ route('register') }}" class="text-primary">Register</a></span>
                    </p>
    
                </div>
            </div>
        </form>
    
  9. Add Form Validation Script.
  10. login.blade.php
    <script>
        (function() {
            'use strict'
    
            var forms = document.querySelectorAll('.needs-validation')
    
            Array.prototype.slice.call(forms)
                .forEach(function(form) {
                    form.addEventListener('submit', function(event) {
                        if (!form.checkValidity()) {
                            event.preventDefault()
                            event.stopPropagation()
                        }
    
                        form.classList.add('was-validated')
                    }, false)
                })
        })()
    </script>
  11. Create a controller.
  12. AuthController
    php artisan make:controller AuthController
  13. Create a route.
  14. Web.php
    use App\Http\Controllers\AuthController;
    
    Route::get('/',[AuthController::class,'login'])->name('login');
    
  15. Create login view function.
  16. AuthController
    public function login()
        {
            return view('login');
        }
    
    
  17. Migrate table.
  18. Migrate users table
    php artisan migrate
  19. Add loginPost route.
  20. Web.php
    use App\Http\Controllers\AuthController;
    
    Route::post('/login',[AuthController::class,'loginPost'])->name('loginPost');
    
  21. Create loginPost function.
  22. AuthController
    use Illuminate\Support\Facades\Auth;
    
    public function loginPost(Request $request)
        {
            $credetails = [
                'email' => $request->email,
                'password'=> $request->password,
            ];
    
            if(Auth::attempt($credetails)){
                return 'success';
                // return redirect('/index');
    
            }
    
            return back()->with('error','Email or Password Invalid');
        }
    

Register

Now, Let's create the Register. 

  1. Create register.blade.php file.
  2. Add bootstrap.
  3. Add form-container.
  4. Add form with validation.
  5. register.blade.php 
    <form class="needs-validation" action="{{ route('registerPost') }}" method="POST" novalidate>
            @csrf
            <div class="mb-2">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" name="name" id="name" placeholder="Your Name" required>
                <div class="invalid-feedback">
                    Please Enter Your Name.
                </div>
            </div>
            <div class="mb-2">
                <label for="email" class="form-label">Email</label>
                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required>
                <div class="invalid-feedback">
                    Please Enter Your Email.
                </div>
            </div>
            <div class="mb-2">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" name="password" id="password" placeholder="Your Password"
                    required>
                <div class="invalid-feedback">
                    Please Enter Your Password.
                </div>
            </div>
            <div class="mb-2">
                <p>If you already have an account? <span><a class="text-primary"
                            href="{{ route('login') }}">Login</a></span></p>
            </div>
            <div class="mt-2 mb-2">
                <div class="d-grid">
                    <button class="btn btn-success float-right">Register</button>
                </div>
            </div>
        </form>
    
  6. Add Form Validation Script.
  7. Create a route.
  8. Web.php
    use App\Http\Controllers\AuthController;
    
    Route::get('/register',[AuthController::class,'register'])->name('register');
    
  9. Create register view function.
  10. AuthController
    public function register()
        {
            return view('register');
        }
    
  11. Create registerPost function.
  12. AuthController
    use App\Models\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Facades\Validator;
    
    public function registerPost(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users,email',
                'password' => 'required|string',
            ]);
    
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            }
    
            $user = new User();
    
            $user->name = $request->name;
            $user->email = $request->email;
            $user->password = Hash::make($request->password);
    
            $user->save();
    
            return redirect()->route('login')->with('success', 'Registration successful.');
        }
    
  13. Success message.
  14. login.blade.php
    @if (Session::has('success'))
        <div class="alert alert-success" role="alert">
            {{ Session::get('success') }}
        </div>
        @endif
    
  15. Error message.
  16. login.blade.php
    @if (Session::has('error'))
                  <div class="alert alert-danger" role="alert">
                         {{ Session::get('error') }}
                  </div>
               @endif
    

Post a Comment

Previous Post Next Post