Using @error directive to target the previous input field from multiple input fields after submit in Laravel 5.8

后端 未结 2 1668
轮回少年
轮回少年 2021-01-27 13:12

The new @error directive was introduced in Laravel 5.8.13. So, instead of doing this:

// old
@if ($errors->has(\'emai         


        
2条回答
  •  攒了一身酷
    2021-01-27 13:45

    Interestingly, the @error directive is not programmatically tied to any input field by an input name. It is only spatially related to an input field by proximity and can be placed any where on the page.

    Also, you can conveniently use any string within the @error directive as long as same is passed to the withErrors() call in the controller.

    So, solving the problem of targeting the appropriate input among multiple ones becomes as simple as using any unique string (not necessarily the target input name) as key in the withErrors() method call and retrieving the error message by passing the same string to the @error directive. In my case, I chose to use the account id as the unique string.

    In AccountController.php:

    public function update(Request $request, Account $account)
    {
        if($request->input('credit') < 0)
        {
            return back()->withErrors([$account->id=>'enter a positive amount']);
        }
        // ... other logic
    }
    

    And in the html blade template:

    @forelse($accounts as $account)
        
    @csrf
    @error($account->id) {{ $message }} @enderror
    @empty @endforelse

    NOTE: Using a non existent key in any @error directive breaks the code for other @error directives and will cause no error messages to be displayed.

提交回复
热议问题