Validation on Login

In this tutorial, we are going to create validation on login page. When you submit login form.

 

Step 1 : Go to your login page so that we will create a form action on the login page that when we are trying to login and in that we have not filled my email and password then we get a error message over there.

Like  :  <form method="post" action="{{url('/main/checklogin')}}">

eg:

<form method="post" action="{{url('/main/checklogin')}}">

  {{csrf_field()}}

  <div class="form-group">
    <label>Email : </label>
    <input type="email" name="email" class="form-control">
  </div>

  <div class="form-group">
    <label>Password : </label>
    <input type="password" name="password" class="form-control">
  </div>

  <button type="submit" name="login" class="btn btn-primary">Login</button>
  <p>Don't have an account <a href="#">Register Here</a></p>
  
</form>

 

In this form, we are creating a csrf_field().

 

What is csrf_field().

Laravel provides protection with the CSRF attacks by generating a CSRF token. This CSRF token is  generated automatically for each user. this token is nothing but a random string that is managed by the Laravel application to verify the user requests.

 

Step 2 : Now create a route in web.php for check login.

Route::post('/main/checklogin','MainController@checklogin');

 

Routing in Laravel allows you to route all your application requests to its appropriate controller.

 

Step 3 : Open your main controller file and create a checklogin function.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use validator;
use Auth;

class MainController extends Controller
{
    
	function index()
	{
		return view('login');
	}

	function checklogin(Request $request)
	{
		//create a validation of login 
		$validateData = $this->validate($request,[
			'email' => 'required|email',
			'password' => 'required|alphaNum|min:5'
		]);

		//if validation in success, so it will show ok otherwise back to with required field.
		if($validateData){
			echo 'ok';
		}else{
			return back()->with('error','Wrong login details');
		}
	}

}

 

Step 4 : In this, we will show the required message on login page.

@if(count($errors) > 0)
  <div class="alert alert-danger">
    <ul>
      @foreach($errors->all() as $error)
        <li>{{$error}}</li>
      @endforeach
    </ul>
  </div>
@endif

 

Click here to download complete code of login

 


Result :

Source Code:

Small Laravel Project

In this project. We are providing you, how to create small project in Laravel....

Source Code