Custom Login and Registration in Laravel

Share this

In this post i am going to tell you how can we make custom login and registration in Laravel so first i need to create a registration page.For that, i need to create a blade file called registration.blade.php  and this file will be created under resources > views

registration.blade.php

@extends('layout.main')
@section('maincontainer')
    	<!-- three black card section -->
    	<div class="row pt-3 pb-1 plr_24">
    		<div class="col-md-4 mb-3">
            
    		</div>
    		<div class="col-md-4 mb-3">
            
            <div class="register">
            <h4 class="mt-2">Registration</h4>
			@if(Session::has('success'))
			<div class="alert alert-info alert-dismissible fade show" role="alert">
        		{{Session::get('success')}}
		
  			</div>
        
        @endif
		@if(Session::has('fail'))
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		{{Session::get('fail')}}
		
  			</div>
        
        @endif

          		<form action="{{route('registration-submit')}}" method="post">
				  @csrf
          			<div class="form-section">
          				<span class="fa fa-user input-icon"></span>
          				<input type="text" name="name" placeholder="Full Name" value="{{old('name')}}">
						 <span class="text-danger"> @error('name') {{$message}} @enderror </span>
          			</div>
          			<div class="form-section">
          				<span class="fa fa-envelope input-icon"></span>
          				<input type="text" name="email" placeholder="Email" class="email" value="{{old('email')}}">
						  <span class="text-danger"> @error('email') {{$message}} @enderror </span>
          			</div>
          			<div class="form-section">
          				<span class="fa fa-unlock-alt input-icon"></span>
          				<input type="password" name="password" placeholder="Enter Password" value="{{old('password')}}">
						  <span class="text-danger"> @error('password') {{$message}} @enderror </span>
          			</div>
                    <div class="form-section">
          				<span class="fa fa-unlock-alt input-icon"></span>
          				<input type="password" name="password_confirmation" placeholder="Re Type Password"value="{{old('password_confirmation')}}">
						  <span class="text-danger"> @error('password_confirmation') {{$message}} @enderror </span>
          			</div>
                      <div class="form-section">
          				<b>By Submitting this form you agree our <a href="">Terms and conditions</a></b>
          			</div>
          			<div class="form-section btn-container text-center">
          				<input type="submit" value="Register"><br/><br/>
						  <a href="{{route('login')}}">Login now</a>
          			</div>
          		</form>
          	</div>



    		</div>
    		<div class="col-md-4 mb-3">
    			
    		</div>
    	</div>
    	
@endsection


New, create a another file called login.blade.php file under resources > views folder

login.blade.php

@extends('layout.main')
@section('maincontainer')
    	<!-- three black card section -->
    	<div class="row pt-3 pb-1 plr_24">
    		<div class="col-md-4 mb-3">
    			
    		</div>
    		<div class="col-md-4 mb-3">
            
            <div id="tab-1" class="login tab-content current">
                <h4 class="mt-2">Login</h4>
                @if(Session::has('success'))
			<div class="alert alert-info alert-dismissible fade show" role="alert">
        		{{Session::get('success')}}
		
  			</div>
        
                 @endif
                    @if(Session::has('fail'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    {{Session::get('fail')}}
                    
                        </div>
        
                    @endif
                    <form action="{{route('login-submit')}}" method="post">
				    @csrf
                    <div class="form-section">
                        <span class="fa fa-user input-icon"></span>
                        <input type="text" name="userid" placeholder="Registered e-mail id">
                        <span class="text-danger"> @error('userid') {{$message}} @enderror </span>
                    </div>
                    <div class="form-section">
                        <span class="fa fa-unlock-alt input-icon"></span>
                        <input type="password" name="password" placeholder="Password">
                        <span class="text-danger"> @error('password') {{$message}} @enderror </span>
                    </div>
                    <div class="form-section btn-container">
                        <input type="submit" value="Login">
                    </div>
                    <div class="form-section btn-container">
                        <a href="{{route('forgot-password')}}">Forgot Password ?</a> | <a href="{{route('registration')}}">Registration</a>
                    </div>
                </form>

</div>
    		</div>
    		<div class="col-md-4 mb-3">
    			
    		</div>
    	</div>
    	
@endsection


Now, I have to create a controller file to make some function for Registration and login so to create the controller file i need to run the following command on visual code terminal or command prompt which is following
php artisan make:controller front

After running this command you will see a file called front.php under app > Http > Controllers > front.php,You can check the following screen shot as well.

Now you need to create some functions to handle login and registration requests so following are the list of those functions

  • login()  // to handle the login page
  • register() // to handle the registration page
  • login_submit(Request $request) // to handle the login page submition
  • email_verification($token) // to handle the email verification process
  • logout() // to handle the logout process
<?php

namespace App\Http\Controllers;

use App\Models\categories;
use App\Models\User;
use App\Models\listing;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Hash;
use Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;


class front extends Controller
{
    
    
    public function login()
    {
        $category = DB::table('categories')->get();
        $menu=categories::paginate(4);
        return view('login',compact('menu','category'));
    }
    public function register()
    {
        $category = DB::table('categories')->get();
        $menu=categories::paginate(4);
        return view('registration',compact('menu','category'));
        
    }
    
    
    
    public function login_submit(Request $request)
    {
        $request->validate([
            'userid'=>'required',
            'password'=>'required',
            
            
        ]);
        $userid=user::where('email','=',$request->userid)->first();

        if($userid)
        {
            if(Hash::check($request->password,$userid->password)){
                $request->session()->put('loginid',$userid->email);
                return redirect('add-listing');
            }
            else
            {
                return back()->with('fail',"Wrong Password!");
            }
        }
        else
        {
            return back()->with('fail',"Wrong User Id!");
        }

    }
    public function logout()
    {
        if(Session::has('loginid')){
            Session::pull('loginid');
            
            return redirect('login');
        }
    }
    
    public function email_verification($token)
    {
        $updateemail = DB::table('users')->where(['email_verified_at' => NULL, 'remember_token'=> $token])->first();
        if($updateemail)
        {
            DB::table('users')->where('remember_token', $token)->update([
            'email_verified_at'=>date('Y-m-d H:i:s'),
            
        ]);
        return redirect('message')->with('success','Successfully Verified !');
        }
        else
        {
            return redirect('message')->with('fail','Email id is already verified !');
        }

    }
    public function registration_submit(Request $request)
    {
        $request->validate([
            'name'=>'required',
            'email'=>'required | email | unique:users',
            'password'=>'required|min:3|confirmed',
            'password_confirmation'=>'required',
            
        ]);
        $users = new user();
        $users->name=$request->name;
        $users->email=$request->email;
        $users->password=Hash::make($request->password);
        $users->remember_token=Str::random(32);
        
        $result=$users->save();
        if($result)
        {
            $data=['name'=>$request->name,'token'=>$users->remember_token];
            $user['to']=$request->email;
            Mail::send('email-verification',$data,function($messages) use($user){
                $messages->to($user['to']);
                $messages->subject('Email-Verification !');
            });
            return back()->with('success',"Please check your email id and verify it !");
        }
        else
        {
            return back()->with('fail',"Something went wrong !");
        }
    }
}

Now, It is time to make routes under web.php file.This file is under routes folder so go to routes > web.php and update the details which are following.

web.php

<div>
<div><?php</div>
<div>use Illuminate\Support\Facades\Route;</div>
<div>use App\Http\Controllers\front;</div>
<div>/*</div>
<div>|--------------------------------------------------------------------------</div>
<div>| Web Routes</div>
<div>|--------------------------------------------------------------------------</div>
<div>|</div>
<div>| Here is where you can register web routes for your application. These</div>
<div>| routes are loaded by the RouteServiceProvider within a group which</div>
<div>| contains the "web" middleware group. Now create something great!</div>
<div>|</div>
<div>*/</div>
<div>Route::get('/',[front::class,'home']);</div>
<div>Route::get('/login',[front::class,'login'])->name('login');</div>
<div>Route::get('/registration',[front::class,'register'])->name('registration');</div>
<div>Route::post('/registration-submit',[front::class,'registration_submit'])->name('registration-submit');</div>
<div>Route::post('/login-submit',[front::class,'login_submit'])->name('login-submit');</div>
<div>Route::get('/logout',[front::class,'logout'])->name('logout');</div>
<div>Route::get('/email-verification/{token}',[front::class,'email_verification'])->name('email-verification');</div>
<div>Route::get('/message',[front::class,'message'])->name('message');</div>

So in above file i have made the routes for login and registration and i also gave the name of routes using name() function.

Now, I need to create few middleware to validate the login process. Means, when someone login to the dashboard the route/ page of dashboard only accessible to only login user. To do this validation we need to create middleware so run the following command php artisan make:middleware validlogin and this file is under Middleware and i have create two middleware which have following source code.

validlogin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class validlogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if(Session()->has('loginid')){
            
            return $next($request);
            
        }
        else
        {
            return redirect('login');
        }
        
        
    }
}

In the above code Session()->has('loginid') is checking the session weather it is ‘loginid’ or not, if it is not then it will be redirected to login route

noback.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class noback
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
    }
}

In this code you can see the process of cache removal. This code is resolving the issue of back button in the browser. it expire the internal pages which comes after login.

Now goto Kernal.php and register middlewares there using following code
'validlogin' => \App\Http\Middleware\validlogin::class,
'noback' => \App\Http\Middleware\noback::class,

Kernal.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array<int, class-string|string>
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array<string, class-string|string>
     */
    protected $routeMiddleware = [
        
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'validlogin' => \App\Http\Middleware\validlogin::class,
        'noback' => \App\Http\Middleware\noback::class,
    ];
}

Share this

Leave a Comment