laravelformsvalidationrequestlaravel-blade

How to show error message with @error() blade with named bag error?


I've implemented simple Validation Form Request with NamedBag

$validator = Validator::make($request->all(),
  ['name' => 'required|max:255',
   'second_name' => 'required|max:255',
  ]
)->validateWithBag('create');

if ($validator->fails()) {
  return redirect()->back()
    ->withErrors($validator, 'create')
    ->withInput();
}

Question is: how to intercept error message with @error()

@error('namedBag.name')
  <div class="alert alert-danger">{{ $message }}</div>
@enderror

my solution is

 @if($errors->create->has('name'))
    <div class="alert alert-danger">{{ $errors->create->first('name') }}</div>
 @endif

is possible to use @error() directive?


Solution

  • You can provide the name of an error bag as the second argument to the @error directive to get validation error messages. Below is an example of what the syntax looks like.

    @error('fieldName', 'errorBagName')
      <div class="alert alert-danger">{{ $message }}</div>
    @enderror
    

    So in your case, it is something like this

    @error('name', 'create')
      <div class="alert alert-danger">{{ $message }}</div>
    @enderror
    

    Here is the official documentation for this - https://laravel.com/docs/11.x/blade#validation-errors