How to create login authentication in Laravel 8

How to create Laravel user login authentication in Laravel 8

Posted by Luke Beeno on April 16, 2021

How to create login authentication in Laravel 8

How to create Laravel user login authentication in Laravel 8

Posted by Luke Beeno on April 16, 2021

In this tutorial you will see how to use Laravel authentication to verify user login. Assuming that you have already connected and inserted a user to the database. If not, and you wish to understand how to insert user into your database in Laravel, go to this tutorial https://wecode101.com/laravel-8-seeding-database.

Step 1. Create login controller by executing command:

php artisan make:controller Auth/LoginController

Go to "app/Http/Controllers/Auth" and edit the file:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use App\Http\Requests\LoginRequest;

use Illuminate\Http\RedirectResponse;

use Illuminate\View\View;

class LoginController extends Controller {

/** * * @return View */

public function showLoginForm(): View {

return view('auth/login');

}

/** * * @param LoginRequest $request * @return RedirectResponse */

public function processLogin(LoginRequest $request): RedirectResponse {

   $credentials = $request->except(['_token']);

if (auth()->attempt($credentials)) {

    return redirect()->route('home');

}else{

   session()->flash('error', 'Invalid credentials');

   return redirect()->route('login');

  }

 }

}

Step 2. Create request file by running command:

php artisan make:request LoginRequest

Go to "app/Request" and edit the file LoginRequest.php:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequest {

    /**    

    * Determine if the user is authorized to make this request.  

    *    

    * @return bool  

   */    

   public function authorize()  

   {      

      return true;  

   }

   /**

    * Get the validation rules that apply to the request.  

    *    

    * @return array

    */    

    public function rules()

    {

       return [      

          'email' => 'required',

          'password' => 'required'

        ];

    }

}

Step 3. Create home controller by executing command

php artisan make:controller HomeController

Go to "app/Http/Controllers" and edit the file HomeController.php:

namespace App\Http\Controllers;

use Illuminate\View\View;

class HomeController extends Controller {

    /**    

     *    

     * @return View  

     */

    public function index(): View     {

        return view("home");

    }

}

Step 4. Create login view 

Go to "resources/view" create another folder "auth" and create the file "login.blade.php" within "auth" folder.

The path looks like this "resources/view/auth/login.blade.php". Here is an example of login.blade.php below:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">

    <title>Wikicode login auth tutorial</title>

    <meta name="description" content="Wikicode login auth in Laravel 8">
    <meta name="author" content="Wikicodes">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container align-items-start">
    @if (session('error'))
        <div class="alert alert-danger mt-3">
            {{ session('error') }}
        </div>
    @endif
    <div class="card card-body container-fluid d-flex justify-content-center mt-5" style="max-width: 30em">
        <h2>Login</h2>
        <form id="signin" class="form-horizontal validate-form" method="POST" action="{{ route('process.login') }}">
            {{ csrf_field() }}

            <div class="form-group">
                <label for="email" class="control-label">Email</label>
                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" autocomplete="off">
                @error('email')
                <div class="error-txt">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="password" class="control-label">Password</label>
                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" autocomplete="off">
                @error('password')
                <div class="error-txt">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <div class="checkbox">
                    <label class="mb-0">
                        <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
                    </label>
                </div>
            </div>

            <div class="form-group mb-0">
                <button type="submit" class="btn btn-primary">
                    Login
                </button>
            </div>
        </form>
    </div>
</div>
</body>
</html>

Step 5. Create home view

Go to "resources/view" and create file "home.blade.php", example below:

<h1>Dashboard<h1>

Step 6. add auth route

Go to "auth/web.php" and edit

use App\Http\Controllers\Auth\LoginController;

use App\Http\Controllers\HomeController;

use Illuminate\Support\Facades\Route;

/*

|--------------------------------------------------------------------------

| 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::middleware(['guest'])->group(function(){

    Route::get('/', [LoginController::class,

'showLoginForm'])->name('login');

    Route::post('/login', [LoginController::class,

'processLogin'])->name('process.login');

});

Route::middleware(['auth'])->group(function(){

    Route::get('/home', [HomeController::class, 'index'])-

>name('home');

});

Step 7. Start server

php artisan serve

You should see the login form, try to login with a user in the database using correct username and password.

Once successful you should be redirected to the home page. Also try logging in using incorrect credentials, you should see an error message.

 If you wish to download this tutorial go to https://github.com/wecode101/login_authentification_laravel_8

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question