Skip to content

Instantly share code, notes, and snippets.

@npostman
Last active June 17, 2022 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npostman/273b9a8d165b5b1872a62e90cdb33098 to your computer and use it in GitHub Desktop.
Save npostman/273b9a8d165b5b1872a62e90cdb33098 to your computer and use it in GitHub Desktop.
Laravel Blade directive @error to allow array input
<?php
namespace App\Providers;
use Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('error', function ($expression) {
return '<?php $__errorArgs = ['.$expression.'];
$__bag = $errors->getBag($__errorArgs[1] ?? \'default\');
$__errorArgs[0] = is_array($__errorArgs[0]) ? $__errorArgs[0] : [$__errorArgs[0]];
if ($__bag->hasAny($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = "";
$__i = 0;
while ($message === "") {
$message = $__bag->first($__errorArgs[0][$__i++]);
} ?>';
});
Blade::directive('enderror', function ($expression) {
return '<?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag, $__i); ?>';
});
}
}
@npostman
Copy link
Author

These blade directives override the default @error blade directive.

When implemented, you can pass an array of error bag keys to the directive. It then will assign the first message it encounters in the order of the keys to the $message variable.

So you can use it like this:

<input type="password" class="form-control @error(['email', 'failed', 'password']) is-invalid @enderror">
<label for="password">{{ trans('labels.password') }}</label>
@error(['email', 'failed', 'password'])
                <div id="passwordFeedback" class="invalid-feedback">{{ $message }}</div>
@enderror

The PR (laravel/framework#42825) for this didn't get included.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment