Last active
August 29, 2019 06:42
-
-
Save adamcrampton/8e3f67375c5e087039c0dde6c8859c8b to your computer and use it in GitHub Desktop.
Laravel macro for returning validation errors to front end using Form class
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 | |
/** | |
* 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