Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ManojKiranA/4de987d9d9db23efe4c22972d1fc5bf2 to your computer and use it in GitHub Desktop.
Save ManojKiranA/4de987d9d9db23efe4c22972d1fc5bf2 to your computer and use it in GitHub Desktop.
A little Blade directive to make working with validation errors a bit nicer.
<?php
// Usage:
// Before
@if ($errors->has('email'))
<span>{{ $errors->first('email') }}</span>
@endif
// After:
@error('email')
<span>{{ $message }}</span>
@enderror
// Include the following in your "app/Providers/AppServiceProvider.php":
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('error', function ($expression) {
return <<<EOT
<?php
if (\$errors->has({$expression})) :
if (isset(\$message)) { \$messageCache = \$message; }
\$message = \$errors->first({$expression});
?>
EOT;
});
Blade::directive('enderror', function () {
return <<<EOT
<?php
unset(\$message);
if (isset(\$messageCache)) { \$message = \$messageCache; }
endif;
?>
EOT;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment