Monday, 5 March 2018

Simple Login System in Laravel



Today, We are going to make Login Authentication System in Laravel Framework. For developing Login System in Laravel We have use Laravel Migrations, Seeding, Routes, Controllers and Views. By using this all features of Laravel we will make Login Authentication System step by step from scratch. If you have developed any application then in all application Login is a required features of any application. And if you have use Laravel PHP framework for developing web application then it is very quite easy to implement Login system. Because Laravel is an open source framework and it has it's own in-built Authentication Library for check user login details. So how to use this Library for making a Login Authentication system in Laravel, so below you can find complete step by step process for developing Login System in Laravel.





First we have to download Laravel application and install it. For this we have to go to command prompt and in that composer must be install and first run composer command in command prompt. After this we have to run following command.


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


This command will make student_crud folder in define location and in that it will download laravel application. Once download complete then in that folder you can find in built User Modal for database operation. First we have to make database connection, so for this we have to go to .env file and config/database.php file and define database credentials.
After making database credentials we have to create users tables in database. So, In downloaded Laravel file we can find users migration file in database/migrations/. So we want to migrate this table to Mysql database. So we have to write following command in command prompt.


php artisan migrate


This command will make users table in Mysql database. Now we want to insert one user records in users table. For this we have use Laravel seeders. It will filled data into Mysql table. For this we have go to command prompt and write following command.


php artisan make:seeder UsersTablesSeeder


This command will make UsersTablesSeeder class in database/seeds/UsersTablesSeeder.php. So we have open that file and under this we have define single user data in run() method.


<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\User;

class UsersTablesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name'    => 'John Smith',
            'email'    => 'john_smith@gmail.com',
            'password'   =>  Hash::make('password'),
            'remember_token' =>  str_random(10),
        ]);
    }
}


After this we have open DatabaseSeeder.php class and under that class run() method we have called UsersTablesSeeder.php.


<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Eloquent::unguard();
        $this->call(UsersTablesSeeder::class);
    }
}



Now We want to export data into Mysql users table, so we have go to command prompt and write following command.


composer dump-autoload



php artisan db:seed


This command will export data into users table. So this way we can filled data into Mysql table from Laravel application. Now we want to make one controller for handle login process. So, We have write following command in command prompt.


php artisan make:controller MainController


It will make MainController.php in app/Http/Controllers folder. In this controller we have first make index() method for load login form.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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


This code will load login form when we have called main controller directly, then it will display login form. After this we have to create Login form view file. So we have create login.blade.php view file for display login form.


<!DOCTYPE html>
<html>
 <head>
  <title>Simple Login System in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Simple Login System in Laravel</h3><br />

   @if(isset(Auth::user()->email))
    <script>window.location="/main/successlogin";</script>
   @endif

   @if ($message = Session::get('error'))
   <div class="alert alert-danger alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <strong>{{ $message }}</strong>
   </div>
   @endif

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

   <form method="post" action="{{ url('/main/checklogin') }}">
    {{ csrf_field() }}
    <div class="form-group">
     <label>Enter Email</label>
     <input type="email" name="email" class="form-control" />
    </div>
    <div class="form-group">
     <label>Enter Password</label>
     <input type="password" name="password" class="form-control" />
    </div>
    <div class="form-group">
     <input type="submit" name="login" class="btn btn-primary" value="Login" />
    </div>
   </form>
  </div>
 </body>
</html>


For handle login form request we have to make one checklogin() method in main controller. This method will handle login form request and validate user login details proper or not. If details not proper then it will redirect to login form and if users details proper then it can access private pages of system which we cannot access without login. Here also we have also make method for validate user with logout link from system.


<?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)
    {
     $this->validate($request, [
      'email'   => 'required|email',
      'password'  => 'required|alphaNum|min:3'
     ]);

     $user_data = array(
      'email'  => $request->get('email'),
      'password' => $request->get('password')
     );

     if(Auth::attempt($user_data))
     {
      return redirect('main/successlogin');
     }
     else
     {
      return back()->with('error', 'Wrong Login Details');
     }

    }

    function successlogin()
    {
     return view('successlogin');
    }

    function logout()
    {
     Auth::logout();
     return redirect('main');
    }
}

?>


Now we have create one view file which user can view after authenticate his login details. So below you can find source code of successlogin.blade.php. This page user can not directly access without login into system.


<!DOCTYPE html>
<html>
 <head>
  <title>Simple Login System in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Simple Login System in Laravel</h3><br />

   @if(isset(Auth::user()->email))
    <div class="alert alert-danger success-block">
     <strong>Welcome {{ Auth::user()->email }}</strong>
     <br />
     <a href="{{ url('/main/logout') }}">Logout</a>
    </div>
   @else
    <script>window.location = "/main";</script>
   @endif
   
   <br />
  </div>
 </body>
</html>


Lastly, we want to set route of all method of Main Controller. So we have go to web.php file and in that we have set route of all request.


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/uploadfile', 'UploadfileController@index');
Route::post('/uploadfile', 'UploadfileController@upload');
Route::get('/main', 'MainController@index');
Route::post('/main/checklogin', 'MainController@checklogin');
Route::get('main/successlogin', 'MainController@successlogin');
Route::get('main/logout', 'MainController@logout');



So, this is complete source of Laravel Login system. On this page we have also put link of source code file also. So, you can also download complete source code file also.

1 comment:

  1. if we press logout and hit the back button it doesn't come to login page and comes back to same page from which we are logging in

    ReplyDelete