For the past few years, we've been using the laracasts/flash package to flash messages in all projects. In case you don't know: a flash message is a message that is being passed from a request to only the next request. The Laracasts package does its job pretty well. It has support for multiple flash messages, overlay messages. It comes with bootstrap styling out of the box and a few messaging levels preconfigured.

We've noticed that in our projects we only use a tiny bit of functionality from the laracasts/flash. That's why we whipped up our own lightweight package called spatie/laravel-flash. In this blog post, I'd like to introduce it to you.

Our flash package can only send one flash message at the time. Because it just needs that capability, we can keep our API very clean. Here's an example of how you can use it.

class MyController
{
    public function store()
    {
        // …

        flash('My message', 'my-class');

        return back();
    }
}

Let's take a look at how we can display the flash message. We don't have a view included in our package. You have to create a partial view in your own app. This is what the content of that view could be:

@if(flash()->message)
    <div class="{{ flash()->class }}">
        {{ flash()->message }}
    </div>
@endif

Pretty simple right?

You've probably noticed in the php example above that we specified a concrete CSS class name - my-class - as the second parameter to the flash function. In a real app you probably just want to specify it the message is a success, warning or error message and not specify that concrete class name. The package makes it easy to define message levels and associate them with CSS classes. Here's how you can do that:

// this would probably go in a service provider

\Spatie\Flash\Flash::levels([
    'success' => 'alert-success',
    'warning' => 'alert-warning',
    'error' => 'alert-eror',
]);

Now you can do this to set a flash message:

flash()->success('My message');

// alternatively you can do this
flash('My message', 'success');

In the next request flash()->class will return alert-success.

And that's all there is to the package. We intended to keep this package very slim because we never need more features to flash messages. I hope spatie/laravel-flash will come in handy in your projects too. Be sure also to take a look at the many packages our team has created previously.