Last active
June 17, 2022 07:16
-
-
Save npostman/273b9a8d165b5b1872a62e90cdb33098 to your computer and use it in GitHub Desktop.
Laravel Blade directive @error to allow array input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); ?>'; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
The PR (laravel/framework#42825) for this didn't get included.