You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel注册表单middleware验证:重复邮箱提示与表单值保留实现

Building a User Registration Form in Laravel with Email Uniqueness Check & Middleware Validation

Got it, let's walk through building this registration form step by step. We'll use Laravel's built-in Form Request (which acts as a validation middleware under the hood) to handle the rules, preserve user input on errors, and show the custom email uniqueness message.

1. Create the Registration View

First, make a Blade template for the form. We'll use the old() helper to keep user input if validation fails, and display error messages where needed.

<!-- resources/views/auth/register.blade.php -->
<form method="POST" action="{{ route('register') }}">
    @csrf

    <!-- Name Field -->
    <div>
        <label for="name">Name</label>
        <input id="name" type="text" name="name" value="{{ old('name') }}" required autofocus>
        @error('name')
            <span class="text-red-500">{{ $message }}</span>
        @enderror
    </div>

    <!-- Email Field -->
    <div>
        <label for="email">Email</label>
        <input id="email" type="email" name="email" value="{{ old('email') }}" required>
        @error('email')
            <span class="text-red-500">{{ $message }}</span>
        @enderror
    </div>

    <!-- Mobile Field -->
    <div>
        <label for="mobile">Mobile Number</label>
        <input id="mobile" type="text" name="mobile" value="{{ old('mobile') }}" required>
        @error('mobile')
            <span class="text-red-500">{{ $message }}</span>
        @enderror
    </div>

    <!-- Submit Button -->
    <div>
        <button type="submit">Register</button>
    </div>
</form>

2. Create a Form Request (Validation Middleware)

Laravel's Form Request is a specialized middleware that runs before your controller method to handle validation logic. Generate one with this Artisan command:

php artisan make:request RegisterUserRequest

Now open app/Http/Requests/RegisterUserRequest.php and update the rules and custom error messages:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        // Allow anyone to access the registration form
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users', // Checks for unique email in users table
            'mobile' => 'required|string|max:20', // Adjust rules based on your mobile format requirements
        ];
    }

    /**
     * Custom validation messages
     */
    public function messages(): array
    {
        return [
            'email.unique' => 'email is already in used', // Your custom error message
        ];
    }
}

3. Set Up Routes & Controller

Add these routes to routes/web.php:

use App\Http\Controllers\AuthController;

Route::get('/register', [AuthController::class, 'showRegistrationForm'])->name('register');
Route::post('/register', [AuthController::class, 'register']);

Now create or update the AuthController to handle the registration flow:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterUserRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * Show the registration form
     */
    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    /**
     * Handle registration request
     */
    public function register(RegisterUserRequest $request)
    {
        // The request is already validated at this point (thanks to the Form Request middleware)
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'mobile' => $request->mobile,
            'password' => Hash::make($request->password), // Add a password field to your form if needed
        ]);

        // Optionally log the user in or redirect to a dashboard
        return redirect()->route('dashboard')->with('success', 'Registration successful!');
    }
}

How It All Comes Together

  • Input Preservation: The old() helper automatically retains user input if validation fails, since Laravel flashes the input to the session when redirecting back to the form.
  • Validation Middleware: The RegisterUserRequest runs before the register controller method. If validation fails, it automatically redirects back with error messages and the user's original input.
  • Email Uniqueness: The unique:users rule checks the email column in your users table, and our custom message replaces the default error text with "email is already in used".

内容的提问来源于stack exchange,提问作者Ram Agrawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:05:02