Laravel 10 login authentication

How to create login authentication in Laravel 10

Posted by Luke Beeno on March 10, 2023

Laravel 10 login authentication

How to create login authentication in Laravel 10

Posted by Luke Beeno on March 10, 2023

Here is a step-by-step guide on how to create a basic login authentication system in Laravel 10:

Step 1. Create a new Laravel project using Composer. Open up a terminal or command prompt and navigate to the directory where you want to create your project, then run the following command:

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

This will create a new Laravel project with the name project-name.

Step 2. Connnect to your database by editing the .env file. Open the .env file in the root directory of your Laravel project and update the database credentials.

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

Make sure to replace your_database_name, your_database_username, and your_database_password with your actual database credentials, then save the file.

Step 3. Run the migrations to create the necessary tables in the database. The authentication system requires a users table, so you need to run the migrations to create it. Run the following command in the terminal:

php artisan migrate

Step 4. 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');

  }

 }

}

In the example above there is a showLoginForm method that will show the UI of the login form. There is also another method processLogin, this is used to check if a user's login credentials is valid.

Step 5. 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'
        ];

    }

}

In the example above the email and password name are added to the array in the rules method. The names are associated to the input attribute name in the form input field. So, if the user does not enter an email or password an error message will show.

Step 6. 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");

    }

}

In the example above the index method is placed in the HomeController. The method includes the view after the user loggin.

Step 7. Create login view

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

In "resources/view/auth/login.blade.php" edit file as below:

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

    <title>Wecode101 login auth tutorial laravel 10</title>

    <meta name="description" content="Wecode101 login auth in Laravel 10">
    <meta name="author" content="Wecode101">
    <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>

In the example above the login form that the user will see is created. It is mostly a standard HTML form with Bootstrap used for styling and error messaging has been put in place to alert the user if the input is wrong.

Step 8. Create home view:

Go to "resources/view" and create file "home.blade.php"

<h1>Dashboard</h1>

In the example, a one line h1 tag is created. This just to show that after login you have been redirected successfully to the protected area.

Step 9. Add the routes:

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');

});

In the example above all the routes are added in order to view the login page, process the login on submit and view the home page.

Step 10. Start server using command:

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.

That's it! You now have a basic login authentication system in your Laravel 10 application. You can customize and extend this system as needed for your specific use case.

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