Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Last active August 29, 2019 06:42
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 adamcrampton/8e3f67375c5e087039c0dde6c8859c8b to your computer and use it in GitHub Desktop.
Save adamcrampton/8e3f67375c5e087039c0dde6c8859c8b to your computer and use it in GitHub Desktop.
Laravel macro for returning validation errors to front end using Form class
<?php
/**
* Bootstrap macros in Service Provider.
*
* @return void
*/
public function boot()
{
// Build form error macro to easily set inline error labels.
Form::macro('errorMessage', function($field) {
// Get error array from session.
$errors = Session::get('errors');
// Return HTML for field if error exists.
if ($errors && $errors->has($field)) {
$message = $errors->first($field);
return "<span class='label label-danger'>{$message}</span>";
}
});
}
// Usage in blade template:
{!! Form::text('field_name', null, ['class' => 'form-control', 'placeholder' => 'Field Name']) !!}
{!! Form::errorMessage('field_name') !!}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment