Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created March 28, 2019 20:34
Show Gist options
  • Save calebporzio/08fd6b48cce29fb0fbe3ef9cddbedc8b to your computer and use it in GitHub Desktop.
Save calebporzio/08fd6b48cce29fb0fbe3ef9cddbedc8b 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;
});
}
@MarceauKa
Copy link

@jartaud
Copy link

jartaud commented Mar 30, 2019

@MarceauKa yours is for BS only.

@27Saidou
Copy link

it's very #interesting

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