How To Create A Session Based Authentication In Laravel

Laravel comes with built-in support for session-based authentication. You can use Laravel’s authentication scaffolding to quickly set up session-based authentication in your application. Here’s how you can do it:

Step 1: Generate the authentication scaffolding Run the following command in your terminal from the root of your Laravel project:

					php artisan make:auth

This command will generate the necessary views, routes, and controllers for authentication.

Step 2: Configure the authentication guard Open the config/auth.php file and make sure the web guard is configured as follows:

					'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',

Step 3: Create the User model If you don’t have a User model already, create one using the following command:

					php artisan make:model User

Make sure the User model implements the Illuminate\Contracts\Auth\Authenticatable contract.

Step 4: Update the User model In your User model, add the Authenticatable trait and define the getAuthPassword method as shown below:

					use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
    // ...

    public function getAuthPassword()
        return $this->password;

    // ...

Step 5: Protect your routes In your routes file (web.php or api.php), you can protect your routes by applying the auth middleware. For example:

					Route::middleware('auth')->group(function () {
    // Your protected routes here

That’s it! Laravel’s authentication scaffolding takes care of handling the login, registration, and logout functionalities, along with the necessary routes and views.

You can find more details about Laravel’s session-based authentication in the official documentation:

Please note that this is a basic setup, and you may need to customize it further based on your specific requirements.