Skip to content

bilfeldt/laravel-flash-message

Repository files navigation

Flash multiple advanced messages with both text, messages and links

bilfeldt/laravel-flash-message

Latest Version on Packagist GitHub Tests Action Status StyleCI Code Style Status Total Downloads

An opinionated solution for flashing multiple advanced messages from the backend and showing these on the frontend using prebuild customizable Tailwind CSS alert blade components.

Installation

Install the package via composer and you are ready to add messages and show these on the frontend.

composer require bilfeldt/laravel-flash-message

You are now ready to use the blade components to show the messages on the frontend.

Optional: In case you wish to use the message flashing feature allowing messages to be made available on the next request (useful in combination with redirects) simply add the ShareMessagesFromSession middleware to the web group defined in app/Http/Kernel.php just after the ShareErrorsFromSession middleware:

// app/Http/Kernel.php

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Bilfeldt\LaravelFlashMessage\Http\Middleware\ShareMessagesFromSession::class, // <------ ADDED HERE
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
    ...

Usage

Alert blade components

Simple usage of the alert blade components (message, info, success, warning, error):


```blade
<x-flash::info
    :title="__('Information')"
    :text="__('This is a message which is relevant for you')"
    :messages="[__('Bullet 1'), __('Bullet 2')]"
    :links="[__('Read more') => 'https://example.com', __('Contact us') => 'https://example.com/contact']"
/>

Validation errors

Validation errors are made available as $errors by default in Laravel and it is possilbe to render these easily using:

<x-flash::errors
    :title="__('Validation errors')"
    :text="__('Please correct the following errors:')"
/>

Passing notifications from the backend

The most basic usage of this package is creating a message inside a controller and passing it to the view:

<?php

namespace App\Http\Controllers;

use Bilfeldt\LaravelFlashMessage\Message;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param  Request  $request
     */
    public function index(Request $request)
    {
        $message = Message::warning('This is a simple message intended for you') // message/success/info/warning/error
            ->title('This is important')
            ->addMessage('account', 'There is 10 days left of your free trial')
            ->addLink('Read more', 'https://example.com/signup');
            
        return view('posts')->withMessage($message);
    }
}

Redirects

Sometimes a redirect is returned to the user instead of a view. In that case the message must be flashed to the session so that they are available on the subsequent request. This is simply done by flashing the $message:

<?php

namespace App\Http\Controllers;

use Bilfeldt\LaravelFlashMessage\Message;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param  Request  $request
     */
    public function index(Request $request)
    {
        $message = Message::warning('This is a simple message intended for you') // message/success/info/warning/error
            ->title('This is important')
            ->addMessage('account', 'There is 10 days left of your free trial')
            ->addLink('Read more', 'https://example.com/signup');
            
        return redirect('/posts')->withMessage($message); // This will flash the message to the Laravel session
    }
}

Note that for this to work you will need to add the ShareMessagesFromSession middleware to app/Http/Kernel.php as described in the installation section above.

In the situations where we need to flash a message to session without access to a redirect, like in a Laravel Livewire component, then we have added a small helper method session_message($message) which does the same.

Adding message from anywhere in the code

Messages can be adding bacially anywhere in the codebase using the View facade. Although most usecases will be adding the messages from the controller, then this feature can be really powerful for example conjunction with middlewares:

\Illuminate\Support\Facades\View::withMessage($message);

Multiple message bags

There might be situations where it can be usefull to have multiple "MessageBags" (the same approach as Laravel usese for the validation messages) and in this case one can name the bag like so:

return view('posts')->withMessage($message, 'bag-name');
// or 
return redirect('/posts')->withMessage($message, 'bag-name');

and when displaying the messages simply pass the bag name as well:

<x-flash::messages bag='bag-name' />

Tip

You might have a layout where you would always like to flash the messages above the main content or just below the title. You can simply add the <x-flash::messages /> to your layout file in the place you would like the messages to show and that way you do not need to call this in multiple views. In order to avoid issues with the $messages not being set in case the ShareMessagesFromSession has not been applied then it advised to show the message like so:

@isset($messages)
    <x-flash::messages />
@endif

If you need to show specific messages at a specific location simply use a named message bag for these messages and show them at the desired location

Alternatives / Supplements

This package is useful when working with blade files and passing messages from the backend to the frontend during rendering. If you are looking for toast (popup) messages instead have a look at these awesome packages:

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

A package to flash multiple messages using Laravels default session message flashing system

Resources

License

Security policy

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published