Showing posts with label laravel login. Show all posts
Showing posts with label laravel login. Show all posts

Wednesday, 3 August 2022

Custom Auth Login Registration Logout in Laravel 9

Laravel 9 Custom Login Registration Video Tutorial Part 1



Laravel 9 Custom Login Registration Video Tutorial Part 2



Laravel 9 Custom Login Registration Video Tutorial Part 3



This is Laravel 9 Custom Login Logout and Registration Tutorial, so by this tutorial, we will show you how to create custom Authentication Login Logout and Registration in Laravel 9 Application. So here we will use Laravel 9 Custom Login and Registration.

If you have use Laravel framework for your web development then Laravel 9 framework has provides in built Authentication by using jetstream and UI package. But in some condition we have to create our own Login, Regstration, dashboard and logout. So This tutorial will help you to create custom Login Registration in Laravel 9 framework and here in this tutorial we will create step by step custom login and registration page in Laravel 9 application.

  1. Install Laravel 9 Application
  2. Make Database Connection
  3. Create Controller
  4. Create View Blades Files
  5. Set Controller Method Route
  6. Run Laravel 9 Application

Custom Auth Login Registration Logout in Laravel 9




Step 1 : Install Laravel 9 Application


First for Crate Custom Login and Registration in Laravel 9 framework, then first we have to download fresh Laravel 9 application. So for this, we have goes to command prompt and run following command. This command will create custom_login directory and under that directory, it will download Laravel 9 application.


composer create-project laravel/laravel custom_demo


Step 2 : Make Database Connection


After download Laravel 9 Application for Create Custom Login and Registration, now we have to make MySQL database connection, So we have to open .env file and under this file, we have to define following MySQL database configuration which you can seen below and it will make MySQL database connection in Laravel 9 Application.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


After Make MySQL database connection, now we need to create users table in connected MySQL database. So we goes to command prompt and run following command. This command will create users tables in MySQL database.


php artisan migrate


Step 3 : Create Controller


Now in this steps for handle http request of Laravel 9 Custom Login and Registration Application, we have to create controller. So for this, we have goes to command prompt and run following command, which will create SampleController.php file under app/Http/Controllers directory and under this file, we have to add following code.

app/Http/Controllers/SampleController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Hash;
use Session;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

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

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

    function validate_registration(Request $request)
    {
        $request->validate([
            'name'         =>   'required',
            'email'        =>   'required|email|unique:users',
            'password'     =>   'required|min:6'
        ]);

        $data = $request->all();

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

        return redirect('login')->with('success', 'Registration Completed, now you can login');
    }

    function validate_login(Request $request)
    {
        $request->validate([
            'email' =>  'required',
            'password'  =>  'required'
        ]);

        $credentials = $request->only('email', 'password');

        if(Auth::attempt($credentials))
        {
            return redirect('dashboard');
        }

        return redirect('login')->with('success', 'Login details are not valid');
    }

    function dashboard()
    {
        if(Auth::check())
        {
            return view('dashboard');
        }

        return redirect('login')->with('success', 'you are not allowed to access');
    }

    function logout()
    {
        Session::flush();

        Auth::logout();

        return Redirect('login');
    }
}






Step 4 : Create View Blades Files


In this steps, we need to create blade views file for display custom Login Registration page output in the browser. So here we have goes into resources/views directory and under this we have to create blades files for display login, registration and dashboard page files and we will also create master template files also. Below we will create files one by one.

resources/views/main.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 Custom Login Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <nav class="navbar navbar-light navbar-expand-lg mb-5" style="background-color: #e3f2fd;">
        <div class="container">
            <a class="navbar-brand mr-auto" href="#">Laravel 9 Custom Login Registration</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                    
                <ul class="navbar-nav">
                    @guest

                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('registration') }}">Register</a>
                    </li>

                    @else

                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('logout') }}">Logout</a>
                    </li>

                    @endguest
                </ul>
                
            </div>
        </div>
    </nav>
    <div class="container mt-5">

        @yield('content')
        
    </div>
    
</body>
</html>


resources/views/login.blade.php

@extends('main')

@section('content')

@if($message = Session::get('success'))

<div class="alert alert-info">
{{ $message }}
</div>

@endif

<div class="row justify-content-center">
	<div class="col-md-4">
		<div class="card">
			<div class="card-header">Login</div>
			<div class="card-body">
				<form action="{{ route('sample.validate_login') }}" method="post">
					@csrf
					<div class="form-group mb-3">
						<input type="text" name="email" class="form-control" placeholder="Email" />
						@if($errors->has('email'))
							<span class="text-danger">{{ $errors->first('email') }}</span>
						@endif
					</div>
					<div class="form-group mb-3">
						<input type="password" name="password" class="form-control" placeholder="Password" />
						@if($errors->has('password'))
							<span class="text-danger">{{ $errors->first('password') }}</span>
						@endif
					</div>
					<div class="d-grid mx-auto">
						<button type="subit" class="btn btn-dark btn-block">Login</button>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

@endsection('content')


resources/views/registration.blade.php

@extends('main')

@section('content')

<div class="row justify-content-center">
	<div class="col-md-4">
		<div class="card">
		<div class="card-header">Registration</div>
		<div class="card-body">
			<form action="{{ route('sample.validate_registration') }}" method="POST">
				@csrf
				<div class="form-group mb-3">
					<input type="text" name="name" class="form-control" placeholder="Name" />
					@if($errors->has('name'))
						<span class="text-danger">{{ $errors->first('name') }}</span>
					@endif
				</div>
				<div class="form-group mb-3">
					<input type="text" name="email" class="form-control" placeholder="Email Address" />
					@if($errors->has('email'))
						<span class="text-danger">{{ $errors->first('email') }}</span>
					@endif
				</div>
				<div class="form-group mb-3">
					<input type="password" name="password" class="form-control" placeholder="Password" />
					@if($errors->has('password'))
						<span class="text-danger">{{ $errors->first('password') }}</span>
					@endif
				</div>
				<div class="d-grid mx-auto">
					<button type="submit" class="btn btn-dark btn-block">Register</button>
				</div>
			</form>
		</div>
	</div>
</div>

@endsection('content')


resources/views/dashboard.blade.php

@extends('main')

@section('content')

<div class="card">
	<div class="card-header">Dashboard</div>
	<div class="card-body">
		
		You are Login in Laravel 9 Custom Login Registration Application.
	</div>
</div>

@endsection('content')


Step 5 : Set Controller Method Route


Under this step, we need to create custom route for SampleController.php files method. So we need to open routes/web.php file and under this file we have to all following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\SampleController;

/*
|--------------------------------------------------------------------------
| 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::controller(SampleController::class)->group(function(){

    Route::get('login', 'index')->name('login');

    Route::get('registration', 'registration')->name('registration');

    Route::get('logout', 'logout')->name('logout');

    Route::post('validate_registration', 'validate_registration')->name('sample.validate_registration');

    Route::post('validate_login', 'validate_login')->name('sample.validate_login');

    Route::get('dashboard', 'dashboard')->name('dashboard');

});



Step 6 : Run Laravel 9 Application


This is last step of Laravel 9 Custom Login, Registration and Logout Application and after follow all above steps, now for check output in the browser, we have to start Laravel server. So for this we have goes to command prompt and run following command.


php artisan serve


So after run this command it will start Laravel server and provide us base url of our Laravel 9 Custom Login Registration Application. So we have to copu that url and open in browser for check output in the browser. So for check demo of Laravel 9 Custom Login Registration application, we have to open following url in the browser.


http://127.0.0.1:8000/login


And lastly, if you have follow this tutorial step by step, then you can able to build custom Login Registration page in Laravel 9 Framework from scratch. We hope this tutorial will help you and you can something learn new things from this tutorial. So best of Luck for this Laravel 9 Custom Login Registration tutorial.





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.