Laravel is a powerful PHP framework that comes with a built-in authentication system. However, in some cases, you may prefer to implement a login and registration system manually without relying on external libraries. In this tutorial, we’ll guide you through the process of creating a basic login and registration system in Laravel without using any library.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • Laravel installed on your system
  • Basic understanding of Laravel’s MVC structure
  • Familiarity with PHP and web development concepts

Step 1: Set Up the Database

First, we need to create a database table to store user information. Follow these steps:

  1. Run the migration command to generate a migration file:
php artisan make:migration create_users_table

2. Open the generated migration file and define the structure of the users table. Include fields such as id, name, email, password, created_at, and updated_at.

3. Run the migration command to create the users table in the database:

php artisan migrate

Step 2: Create the User Model

Next, we’ll create a User model to interact with the users table. Follow these steps:

  1. Run the command to generate a User model class:
php artisan make:model User

2. Open the generated User model class and define the table name, fillable attributes, and any other required methods or relationships.

Step 3: Define Routes

In this step, we’ll define the routes for registration, login, and logout. Here’s an example:

Route::get('/register', 'AuthController@showRegistrationForm')->name('register');
Route::post('/register', 'AuthController@register');
Route::get('/login', 'AuthController@showLoginForm')->name('login');
Route::post('/login', 'AuthController@login');
Route::post('/logout', 'AuthController@logout')->name('logout');

Step 4: Create the AuthController

Now, we’ll create an AuthController to handle user registration, login, and logout. Follow these steps:

  1. Run the command to generate a controller class:
php artisan make:controller AuthController

2. Open the generated AuthController class and implement the necessary methods. Here’s an example:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
public function showRegistrationForm()
{
return view('register');
}

public function register(Request $request)
{
    // Validation
    $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6',
    ]);

    // Create a new user
    $user = new User();
    $user->name = $request->input('name');
    $user->email = $request->input('email');
    $user->password = Hash::make($request->input('password'));
    $user->save();

    // Redirect to login page with success message
    return redirect('/login')->with('success', 'Registration successful!');
}

 public function showLoginForm()
    {
        return view('login');
    }

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

        if (auth()->attempt($credentials)) {
            // Authentication successful
            return redirect('/home');
        } else {
            // Invalid credentials
            return back()->withErrors(['email' => 'Invalid credentials']);
        }
    }

    public function logout()
    {
        auth()->logout();

        // You can customize this redirect based on your needs
        return redirect('/login')->with('success', 'Logged out successfully!');
    }
}

Step 5: Create the Registration and Login Views

Now, we’ll create the blade templates for the registration and login forms. Here are examples of the register.blade.php and login.blade.php files:

register.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
</head>
<body>
    <h2>Register</h2>

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <form method="POST" action="{{ route('register') }}">
        @csrf

        <div>
            <label for="name">Name</label>
            <input type="text" id="name" name="name" value="{{ old('name') }}" required autofocus>
        </div>

        <div>
            <label for="email">Email</label>
            <input type="email" id="email" name="email" value="{{ old('email') }}" required>
        </div>

        <div>
            <label for="password">Password</label>
            <input type="password" id="password" name="password" required>
        </div>

        <div>
            <label for="password_confirmation">Confirm Password</label>
            <input type="password" id="password_confirmation" name="password_confirmation" required>
        </div>

        <button type="submit">Register</button>
    </form>
</body>
</html>

login.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <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>

        <button type="submit">Login</button>
    </form>
</body>
</html>

Step 6: Protect Routes Requiring Authentication

If you have any routes that should only be accessible to authenticated users, protect them using the auth middleware. Here’s an example:

Route::get('/home', 'HomeController@index')->middleware('auth');

This ensures that only logged-in users can access the /home route.

Conclusion

In this tutorial, we’ve shown you how to create a login and registration system in Laravel without using any external libraries. While this approach gives you complete control over the implementation, it’s important to note that Laravel provides a robust built-in authentication system and using a well-tested library is often recommended for security reasons and development efficiency.

Categorized in: