Authentication in laravel using username and password step by step guide

Authentication is a crucial aspect of web application development, as it allows you to control access to different areas of your application based on user roles and permissions. Laravel, a popular PHP web framework, provides various ways to implement authentication in your application. In this article, we will explore how to implement authentication using a username and password in Laravel, step by step.

Step 1: Install Laravel

First, install Laravel using Composer. Open your terminal and navigate to the directory where you want to install Laravel. Then, run the following command:

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

This will create a new Laravel project in the directory project-name.

Step 2: Set up the Database

Next, set up your database by editing the .env file in the root directory of your project. Set the following variables to match your database configuration:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
DB_PASSWORD=password

Step 3: Create the User Model

Create a new model for the users table by running the following command:

php artisan make:model User

This will create a new User model in the app/Models directory.

Step 4: Set up the User Table

Next, create the users table in your database by running the following command:

php artisan make:migration create_users_table

This will create a new migration file in the database/migrations directory. Open this file and add the following code:

public function up(){    Schema::create('users', function (Blueprint $table) {      $table->id();       $table->string('name');      $table->string('email')->unique();      $table->timestamp('email_verified_at')->nullable();      $table->string('password');      $table->rememberToken();      $table->timestamps();    });}public function down(){     Schema::dropIfExists('users');}

This code sets up the users table with the necessary columns.

Step 5: Create the Auth Controller

Create a new controller for handling authentication by running the following command:

php artisan make:controller AuthController

This will create a new AuthController in the app/Http/Controllers directory.

Step 6: Define the Routes

Define the following routes in the routes/web.php file:

// Route for login pageRoute::get('/login', 'AuthController@login')->name('login');// Route for handling login requestRoute::post('/login', 'AuthController@authenticate');// Route for logoutRoute::get('/logout', 'AuthController@logout');

Step 7: Define the Login View

Create a new view for the login page by running the following command:

php artisan make:view auth.login

This will create a new login.blade.php file in the resources/views/auth directory. Add the following code to the file:

<form method="POST" action="{{ route('login') }}">    @csrf    <div>        <label for="email">Email:</label>        <input type="email" id="email" name="email" value="{{ old('email') }}" required autofocus>    </div>    <div>        <label for="password">Password:</label>        <input type="password" id="password" name="password" required>    </div>    <div>        <button type="submit">Login</button>    </div></form>

Step 8: Implement the Authenticate Method

Open the AuthController and add the following code to the authenticate method:

use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;public function authenticate(Request $request){    $credentials = $request->only(['email','password']);       if (Auth::attempt($credentials)) {      // Authentication passed...     return redirect()->intended('dashboard');  }}

This code uses Laravel’s built-in attempt method to attempt to authenticate the user with the provided credentials. If the authentication is successful, the user is redirected to the dashboard page.

Step 9: Implement the Login and Logout Methods

Add the following code to the login and logout methods in the AuthController:

public function login(){    return view('auth.login');}public function logout(){    Auth::logout();    return redirect()->route('login');}

The login method simply returns the login view, while the logout method logs the user out and redirects them back to the login page.

Step 10: Protect Routes

To protect certain routes, such as the dashboard page, you can use Laravel’s built-in auth middleware. Add the following code to the routes/web.php file:

Route::get('/dashboard', function () {    return view('dashboard');})->middleware(['auth'])->name('dashboard');

This code defines a dashboard route and applies the auth middleware to it, ensuring that the user must be authenticated to access this page.

And that’s it! You should now have a fully functional username/password authentication system in your Laravel application.

Conclusion

Laravel provides developers with a simple and effective way to implement authentication in their web applications. By following the step-by-step guide outlined in this article, you can quickly and easily implement a username and password authentication system in your Laravel application. However, it is essential to note that security is a critical concern when it comes to authentication, and it is vital to follow best practices to ensure the security of your application. Additionally, Laravel provides many other authentication methods, such as OAuth and Two-Factor Authentication, which you can explore to add more layers of security to your application.

Comments