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 IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;
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);
}
Alternatively, you can use the following version of the code:
use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
// ...
]);
return redirect()->withErrors($validation, 'user');
}
Another option is to use the Form Request class easily:
use IlluminateFoundationHttpFormRequest;
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 here...
return redirect()->back();
}
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>