This is Laravel 4.2
Laravel will make the $error MessageBag available to views. This can be populated with flash messages in the previous page by redirecting ->withErrors()
. That is fine if you are redirecting to a new page.
return Redirect::route('my_route')->withErrors($validator);
I am generating some errors in the controller, not validating a form, and want to put those messages into the $errors MessageBag that Laravel automatically passes into the views. But how? The MessageBag is somewhere, but how do I get to it, and how do I add some messages to it to display in the current page?
It looks like I can inject messages when the view is created.
My controller passes the required view, with the data it collects, to the content of the page template like this:
$this->layout->content = View::make('my.view', $view_data);
Errors can be passed in like this:
$this->layout->content = View::make('my.view', $view_data)->withErrors($my_errors);
where $my_errors can be null or array() (for "no additional errors"), an array of text messages, or a MessageBag.
My outer page template then just picks up the messages if they exist, and displays them at the top of the page:
@if ( $errors->count() > 0 )
...An error occured...
@foreach( $errors->all() as $message )
...{{ $message }}...
@endforeach
@endif
(with markup where appropriate)
I have done that with some custom validations. What you need is something like this:
use Illuminate\Support\MessageBag;
class MyCustomValidator
{
protected $errors = array();
protected $messageBag;
public function __construct(MessageBag $messageBag)
{
$this->messageBag = $messageBag;
}
public function setErrors($errors = array())
{
for($i = 0; $i < count($errors); $i++) {
$this->messageBag->add($i, $errors[$i]);
}
$this->errors = $this->messageBag;
}
public function getErrors()
{
return $this->errors->all();
}
}
In your controller you have to call something like
$validator = new MyCustomValidator();
$validator->getErrors();
You can access the full documentation for the MessageBag in the docs.
Laravel 5
$validator = .......
$validator->after(function($validator) {
.....
$validator->errors()->add('tagName', 'Error message');
.....
});
Mind that the anonimous function is in the scope of the class, not in that of the function where you use it. If you need the value of some variable from the outside world it must be a class variable!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With