Build a Signup and Login System with Laravel 11 Authentication

Build a Signup and Login System with Laravel 11 Authentication

Steps to Build the System

1. Set Up Laravel Project

  1. Install Laravel 11:

    composer create-project laravel/laravel my-auth-system
    cd my-auth-system
  2. Set Up the Database:

    • Update .env with your database details:
      DB_CONNECTION=mysql
      DB_HOST=127.0.0.1
      DB_PORT=3306
      DB_DATABASE=your_database
      DB_USERNAME=your_username
      DB_PASSWORD=your_password
  3. Run Migrations:

    php artisan migrate

2. Install Laravel Breeze for Authentication

Laravel Breeze provides a simple authentication system.

  1. Install Breeze:

    composer require laravel/breeze --dev
    php artisan breeze:install
  2. Install front-end assets (optional if using TailwindCSS):

    npm install && npm run dev
  3. Run migrations and seed the database:

    php artisan migrate

3. Add Multiple Authentication Options

You can include three types of authentication (e.g., email/password, social login, and OTP-based login).

A. Email and Password Authentication (Default Breeze)

  • Breeze already handles email/password authentication.
  • Modify the User model (app/Models/User.php) if you need additional fields for user data.

B. Social Login (Using Laravel Socialite)

  1. Install Socialite:

    composer require laravel/socialite
  2. Configure social login providers:

    • Add credentials for providers in .env:

      GOOGLE_CLIENT_ID=your_google_client_id
      GOOGLE_CLIENT_SECRET=your_google_client_secret
      GOOGLE_REDIRECT_URL=http://yourdomain.com/auth/google/callback
      
      FACEBOOK_CLIENT_ID=your_facebook_client_id
      FACEBOOK_CLIENT_SECRET=your_facebook_client_secret
      FACEBOOK_REDIRECT_URL=http://yourdomain.com/auth/facebook/callback
    • Add Socialite routes in routes/web.php:

      use App\Http\Controllers\Auth\SocialLoginController;
      
      Route::get('/auth/{provider}', [SocialLoginController::class, 'redirectToProvider']);
      Route::get('/auth/{provider}/callback', [SocialLoginController::class, 'handleProviderCallback']);
    • Create SocialLoginController:

      namespace App\Http\Controllers\Auth;
      
      use Laravel\Socialite\Facades\Socialite;
      use App\Http\Controllers\Controller;
      use App\Models\User;
      use Illuminate\Support\Facades\Auth;
      
      class SocialLoginController extends Controller
      {
          public function redirectToProvider($provider)
          {
              return Socialite::driver($provider)->redirect();
          }
      
          public function handleProviderCallback($provider)
          {
              $socialUser = Socialite::driver($provider)->stateless()->user();
      
              $user = User::firstOrCreate(
                  ['email' => $socialUser->getEmail()],
                  ['name' => $socialUser->getName(), 'password' => bcrypt(str()->random(16))]
              );
      
              Auth::login($user);
      
              return redirect('/dashboard');
          }
      }

C. OTP-Based Authentication

  1. Install a package for OTP (e.g., Laravel OTP or implement manually).

  2. Add OTP column to the users table:

    php artisan make:migration add_otp_to_users_table
    • Update the migration file:

      public function up()
      {
          Schema::table('users', function (Blueprint $table) {
              $table->string('otp')->nullable();
              $table->timestamp('otp_expires_at')->nullable();
          });
      }
    • Run migration:

      php artisan migrate
  3. Create OTP login routes in routes/web.php:

    use App\Http\Controllers\Auth\OTPController;
    
    Route::get('/otp/login', [OTPController::class, 'showLoginForm']);
    Route::post('/otp/send', [OTPController::class, 'sendOTP']);
    Route::post('/otp/verify', [OTPController::class, 'verifyOTP']);
  4. Create OTPController:

    namespace App\Http\Controllers\Auth;
    
    use App\Http\Controllers\Controller;
    use App\Models\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    
    class OTPController extends Controller
    {
        public function showLoginForm()
        {
            return view('auth.otp-login');
        }
    
        public function sendOTP(Request $request)
        {
            $request->validate(['email' => 'required|email']);
    
            $user = User::where('email', $request->email)->firstOrFail();
            $otp = rand(100000, 999999);
    
            $user->update([
                'otp' => $otp,
                'otp_expires_at' => now()->addMinutes(10),
            ]);
    
            // Send OTP (e.g., via email or SMS)
            // Mail::to($user->email)->send(new SendOtpMail($otp));
    
            return back()->with('message', 'OTP sent to your email!');
        }
    
        public function verifyOTP(Request $request)
        {
            $request->validate(['email' => 'required|email', 'otp' => 'required|numeric']);
    
            $user = User::where('email', $request->email)->where('otp', $request->otp)->first();
    
            if ($user && $user->otp_expires_at->isFuture()) {
                Auth::login($user);
                return redirect('/dashboard');
            }
    
            return back()->withErrors(['otp' => 'Invalid or expired OTP.']);
        }
    }
  5. Create a Blade view for OTP login form (resources/views/auth/otp-login.blade.php):

    <form method="POST" action="/otp/send">
        @csrf
        <input type="email" name="email" placeholder="Enter your email" required>
        <button type="submit">Send OTP</button>
    </form>
    
    <form method="POST" action="/otp/verify">
        @csrf
        <input type="email" name="email" placeholder="Enter your email" required>
        <input type="text" name="otp" placeholder="Enter OTP" required>
        <button type="submit">Verify OTP</button>
    </form>

4. Test the System

  • Signup/Login: Test email/password functionality provided by Breeze.
  • Social Login: Ensure Google/Facebook login works and creates new users.
  • OTP Login: Test OTP generation, email sending, and verification.

5. Optional Enhancements

  • Middleware: Restrict routes to authenticated users.
  • Role-Based Access Control (RBAC): Use Spatie Laravel Permissions for roles and permissions.
  • Two-Factor Authentication (2FA): Consider adding Google Authenticator or SMS-based 2FA.

With these steps, you will have a signup and login system with three authentication methods using Laravel 11. Let me know if you need help with a specific part!