Introduction

A user registration system is a fundamental component of many web applications. In this tutorial, we will guide you through creating a user registration system in Laravel, a popular PHP framework, step by step.


Prerequisites

Before we begin, ensure you have the following prerequisites in place:

  • Laravel installed and set up.
  • A running web server (e.g., Apache or Nginx).
  • A database (we'll use MySQL in this example).

Step 1: Create the User Model and Migration

In Laravel, the first step is to create a user model and a corresponding database table. Use the following Artisan command to generate these:


            
php artisan make:model User -m

After running the command, you will find a migration file in the

database/migrations
directory. Customize the migration file to define user fields like name, email, and password. Run the migration to create the database table:


            
php artisan migrate

Step 2: Create User Registration Form

Next, create an HTML registration form with fields for name, email, and password. Be sure to include CSRF protection:


            
<form method="POST" action="{{ route('register') }}">
@csrf
<label for="name">Name</label>
<input type="text" name="name" id="name" required>
<label for="email">Email</label>
<input type="email" name="email" id="email" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<button type="submit">Register</button>
</form>

Step 3: Create Registration Controller

Generate a registration controller to handle form submissions and user creation. Use the following command:


            
php artisan make:controller Auth\RegisterController

In the controller, create methods to show the registration form and handle registration logic.


Step 4: Implement Registration Logic

In the registration controller, implement the logic to create a new user, save the user's information to the database, and redirect to a success page:


            
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($validatedData['password']),
]);
// Redirect to a success page
return redirect('/registration-success');
}

Conclusion

Congratulations, you've now built a user registration system in Laravel! Users can sign up, and their information is stored in the database. Further enhancements can be made, such as sending email verification links or implementing user authentication.