Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a message to the $error MessageBag

Tags:

php

laravel

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?

like image 860
Jason Avatar asked Aug 21 '14 23:08

Jason


3 Answers

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)

like image 110
Jason Avatar answered Nov 01 '22 08:11

Jason


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.

like image 20
Luís Cruz Avatar answered Nov 01 '22 10:11

Luís Cruz


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!

like image 3
Han Hermsen Avatar answered Nov 01 '22 08:11

Han Hermsen