DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Handling Validation Errors for Multiple Forms

When dealing with multiple forms on a single page, especially when the forms contain duplicate input names, Laravel’s default validation approach can cause issues. By default, validation errors are tied to the input fields, meaning the error messages are displayed across all forms, not just the one that was submitted. This can be confusing for users.

To resolve this, we can use Named Error Bags, which allow us to store and display validation errors for specific forms separately.

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

public function store(Request $request)
{
    $validation = Validator::make($request->all(), [
        'name'  => 'required|min:25',
        'email' => 'required|unique:users,email,NULL,id,deleted_at,NULL',
    ])->validateWithBag('user');

    return redirect()->withErrors($validation);
}
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use the following version of the code:

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

public function store(Request $request)
{
    $validation = Validator::make($request->all(), [
        // ...
    ]);

    return redirect()->withErrors($validation, 'user');
}
Enter fullscreen mode Exit fullscreen mode

Another option is to use the Form Request class easily:

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * The key to be used for the view error bag.
     *
     * @var string
     */
    protected $errorBag = 'user';

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            //
        ];
    }
}

public function store(StoreRequest $request)
{
    // Perform actions...

    return redirect()->back();
}
Enter fullscreen mode Exit fullscreen mode

Then, to present the validation errors in the blade, you can use one of these approaches:

<form action="{{ route('users.store') }}" method="POST">
    @csrf
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" name="name" required>
        {{-- First approach --}}
        @error('name', 'user')
        <p class="text-danger mt-2">{{ $message }}</p>
        @enderror
        {{-- Second approach --}}
        {{-- <p class="text-danger mt-2">{{ $errors->user->first('name') }}</p> --}}
    </div>
    ...
</form>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.