Another basic however excruciating element in web applications is passing messages between different segments of the application, when the finished objective is to impart them to the client. Your controller, for instance, might need to send an approval message: “The email field must be a legitimate email address.” However, that particular message needs to make it not just to the perspective layer; it very to survive a sidetrack and afterward wind up in the perspective layer of an alternate page. How would we structure this messaging logic ?

Illuminate\Support\MessageBag is a class tasked with storing, categorizing, and returning messages that are intended for the end user. It groups all messages by key, which are likely to be something like errors and messags (@todo is that actually right?), and provides convenience methods for getting all its stored messages or only those for a particular key, and for outputting these messages in various formats.

You could always just spin up a new instance of MessageBag manually like in code below

Manually creating and using MessageBag
$messages = [
    'errors' => [
        'Somethign went wrong with edit 1!'
    ],
    'messages' => [
        'Edit 2 was successful.'
    ]
];
$messagebag = new \Illuminate\Support\MessageBag($messages);

// Check for errors; if there are any, decorate and echo
if ($messagebag->has('errors')) {
    echo '<ul id="errors">';
    foreach ($messagebag->get('errors', '<li><b>:message</b></li>') as $error) {
        echo $error;
    }
    echo '</ul>';
}

Message bags are also closely connected to Laravel’s validators: when validators return errors, they actually return an instance of MessageBag, which you can then pass to your view or attach to a redirect using redirect(route)→withErrors($messagebag).

Advertisements