Evergreenbrain

Laravel Authentication: Implementing User Registration and Login

Laravel Authentication: Implementing User Registration and Login

Authentication is a critical aspect of web application development, ensuring that users can securely access their accounts and personal data. Laravel, one of the most popular PHP frameworks, provides powerful tools for implementing authentication seamlessly. In this article, we’ll explore how to implement user registration and login functionality using Laravel’s built-in features.

Setting Up Laravel

Before diving into authentication, ensure you have Laravel installed on your system. You can install Laravel using Composer, a dependency manager for PHP. Once Composer is installed, you can create a new Laravel project by running the following command in your terminal:

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

Navigate into your newly created project directory:

bash
cd your-project-name

Database Configuration

Laravel uses Eloquent ORM (Object-Relational Mapping) to interact with databases. You’ll need to configure your database connection details in the .env file located at the root of your Laravel project. Update the following variables with your database credentials:

plaintext
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Ensure that you create the specified database in your MySQL server before running migrations.

Migration and Model Creation

Laravel provides a convenient way to create database tables and manage their structure using migrations. Run the following command to create a migration for the users table:

bash
php artisan make:migration create_users_table --create=users

This command will generate a new migration file in the database/migrations directory. Open the generated migration file and define the structure of the users table:

php

// database/migrations/xxxx_xx_xx_create_users_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
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’);
}
}

After defining the table structure, run the migration to create the users table in your database:

bash
php artisan migrate

Next, let’s create a model for the User. Laravel’s Eloquent ORM makes it easy to interact with the database. Run the following command to create the User model:

bash
php artisan make:model User

User Registration

With the database structure and model in place, we can now proceed to implement user registration functionality. In Laravel, this process typically involves creating a registration form, validating user input, and storing user records in the database.

Creating Routes

Define routes for user registration in the routes/web.php file:

php

// routes/web.php

use App\Http\Controllers\RegisterController;

Route::get(‘/register’, [RegisterController::class, ‘showRegistrationForm’]);
Route::post(‘/register’, [RegisterController::class, ‘register’]);

Creating the Controller

Generate a new controller for handling user registration:

bash
php artisan make:controller RegisterController

Open the generated controller file (app/Http/Controllers/RegisterController.php) and define the methods for showing the registration form and handling the registration process:

php

// app/Http/Controllers/RegisterController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class RegisterController extends Controller
{
public function showRegistrationForm()
{
return view(‘auth.register’);
}

public function register(Request $request)
{
$request->validate([
‘name’ => ‘required|string|max:255’,
’email’ => ‘required|string|email|max:255|unique:users’,
‘password’ => ‘required|string|min:8|confirmed’,
]);

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();

return redirect(‘/login’)->with(‘success’, ‘Registration successful. Please log in.’);
}
}

Creating the Registration Form View

Create a new Blade view file named register.blade.php in the resources/views/auth directory. This file will contain the HTML form for user registration:

html

<!-- resources/views/auth/register.blade.php -->

<form method=“POST” action=“{{ route(‘register’) }}”>
@csrf

<div>
<label for=“name”>Name</label>
<input id=“name” type=“text” name=“name” value=“{{ old(‘name’) }}” required autofocus>
</div>

<div>
<label for=“email”>E-Mail Address</label>
<input id=“email” type=“email” name=“email” value=“{{ old(’email’) }}” required>
</div>

<div>
<label for=“password”>Password</label>
<input id=“password” type=“password” name=“password” required autocomplete=“new-password”>
</div>

<div>
<label for=“password-confirm”>Confirm Password</label>
<input id=“password-confirm” type=“password” name=“password_confirmation” required>
</div>

<div>
<button type=“submit”>
Register
</button>
</div>
</form>

User Login

After implementing user registration, the next step is to enable users to log in to their accounts securely.

Creating Routes

Define routes for user login in the routes/web.php file:

php

// routes/web.php

use App\Http\Controllers\LoginController;

Route::get(‘/login’, [LoginController::class, ‘showLoginForm’])->name(‘login’);
Route::post(‘/login’, [LoginController::class, ‘login’]);

Creating the Controller

Generate a new controller for handling user login:

bash
php artisan make:controller LoginController

Open the generated controller file (app/Http/Controllers/LoginController.php) and define the methods for showing the login form and handling the login process:

php

// app/Http/Controllers/LoginController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
public function showLoginForm()
{
return view(‘auth.login’);
}

public function login(Request $request)
{
$credentials = $request->validate([
’email’ => ‘required|email’,
‘password’ => ‘required’,
]);

if (Auth::attempt($credentials)) {
$request->session()->regenerate();

return redirect()->intended(‘/’);
}

return back()->withErrors([
’email’ => ‘The provided credentials do not match our records.’,
]);
}
}

Creating the Login Form View

Create a new Blade view file named login.blade.php in the resources/views/auth directory. This file will contain the HTML form for user login:

html

<!-- resources/views/auth/login.blade.php -->

<form method=“POST” action=“{{ route(‘login’) }}”>
@csrf

<div>
<label for=“email”>E-Mail Address</label>
<input id=“email” type=“email” name=“email” value=“{{ old(’email’) }}” required autofocus>
</div>

<div>
<label for=“password”>Password</label>
<input id=“password” type=“password” name=“password” required autocomplete=“current-password”>
</div>

<div>
<button type=“submit”>
Login
</button>
</div>
</form>

Conclusion

In this article, we’ve covered the process of implementing user registration and login functionality in Laravel. By following Laravel’s conventions and utilizing its built-in features such as routing, controllers, and views, we’ve created a secure authentication system for our web application. With Laravel’s powerful tools and straightforward approach to authentication, you can easily customize and extend these features to meet the specific requirements of your project.