🇵🇸 Solidarity with Palestine. We seek justice and peace, and strongly oppose all forms of injustice and genocide.

If you find PHPFlasher useful, we would greatly appreciate your support in the form of a star rating ⭐ on GitHub or by sharing the project on Twitter click here. Your feedback helps us keep the package up-to-date and well-maintained. Thank you


Requirements

PHPFlasher offers a seamless way to incorporate flash notifications in Laravel projects, enhancing user feedback with minimal setup.

Requirements for using PHPFlasher with Laravel:

PHP v8.2 or higher Laravel v11.0 or higher


Installation

PHPFlasher’s modular design lets you select and install only the components your project needs.

composer require php-flasher/flasher-laravel

After installation, you need to run another command to set up the necessary assets for PHPFlasher:

php artisan flasher:install

Usage

To display a notification message, you can either use the flash() helper method or obtain an instance of flasher from the service container. Then, before returning a view or redirecting, call the success() method and pass in the desired message to be displayed.

#/ PHPFlasher

use Flasher\Prime\FlasherInterface;

class BookController
{
    public function saveBook()
    {
        // ...

        flash()->success('Your account has been re-activated.');

        flash('Your account has been restored.');

        // ... redirect or render the view
    }
    
    /**
     * if you prefer to use dependency injection 
     */
    public function register(FlasherInterface $flasher)
    {
        // ...

        $flasher->success('Your account has been re-activated.');

        // ... redirect or render the view
    }
}


It’s important to choose a message that is clear and concise, and that accurately reflects the outcome of the operation.
In this case, "Book has been created successfully!" is already a good message, but you may want to tailor it to fit the specific context and language of your application.

Using this package is actually pretty easy. Adding notifications to your application actually require only one line of code.

#/ usage success

flash()->success('Your form has been submitted.');
#/ usage error

flash()->error('There was an issue generating your report.');
#/ usage warning

flash()->warning('Your password may not have been changed.');
#/ usage info

flash()->info('This may take a while. Do not refresh the page.');

These four methods success(), error(), warning(), info() are simply convenience shortcuts for the flash() method, allowing you to specify the type and message in a single method call rather than having to pass both as separate arguments to the flash() method.

flash()->flash(string $type, string $message, string $title = null, array $options = [])
#/ usage flash

flash()->flash('info', 'Your subscription has been activated and a confirmation email has been sent.');
param description
$type Notification type : success, error, warning, info
$message The body of the message you want to deliver to your user. This may contain HTML. If you add links, be sure to add the appropriate classes for the framework you are using.
$title The notification title, Can also include HTML
$options Custom options for javascript libraries (toastr, noty, notyf …etc)

options

The options() method allows you to set multiple options at once by passing an array of key-value pairs, while the option() method allows you to set a single option by specifying its name and value as separate arguments.

The optional $append argument for the options() method can be used to specify whether the new options should be appended to any existing options, or whether they should overwrite them.

flash()->options(array $options, bool $append = true);
#/ usage options

flash()
    ->options([
        'timeout' => 3000, // 3 seconds
        'position' => 'top-center',
    ])
    ->warning('Your account may not have been re-activated.');

option

Set a single option by specifying its name and value as separate arguments.

flash()->option(string $option, mixed $value);
#/ usage option

flash()
    ->option('position', 'bottom-right')
    ->option('timeout', 3000)
    ->info('Your account has been locked and a confirmation email has been sent.');

priority

Sets the priority of a flash message, the highest priority will be displayed first.

flash()->priority(int $priority);
#/ usage priority

flash()
    ->priority(3)
    ->success('Priority 3 → Your reservation has been confirmed.');

flash()
    ->priority(1)
    ->error('Priority 1 → There was a problem verifying your email.');

flash()
    ->priority(4)
    ->warning('Priority 4 → Your request may not have been received.');

flash()
    ->priority(2)
    ->info('Priority 2 → Your message has been sent and a confirmation email has been sent.');
param description
$priority The priority of the notification, the higher the priority, the sooner it will be displayed

hops

This method sets the number of requests that the flash message should persist for. By default, flash messages are only displayed for a single request and are then discarded. By setting the number of hops, the flash message will be persisted for multiple requests.

As an example, with a multi-page form, you may want to store messages until all pages have been filled.

flash()->hops(int $hops);
flash()
    ->hops(2)
    ->info('Your subscription has been activated and a confirmation email has been sent.');
param description
$hops indicate how many requests the flash message will persist for

translate

This method sets the locale to be used for the translation of the flash message. If a non-null value is provided, the flash message will be translated into the specified language. If null is provided, the default locale will be used.

flash()->translate(string $locale = null);
#/ usage translate

flash()
    ->translate('ar')
    ->success('Your request was processed successfully.', 'Congratulations!');
#/ usage translate with position

flash()
    ->translate('ar')
    ->option('position', 'top-left')
    ->success('Your request was processed successfully.', 'Congratulations!');
param description
$locale The locale to be used for the translation, or null to use the default locale

It is important to note that the translate() method only sets the locale to be used for the translation of the flash message. It does not actually perform the translation itself.

In order to translate the flash message, you will need to provide the appropriate translation keys in your translation files.

In the above example, to translate the flash message into Arabic, you will need to add the following keys to the resources/lang/ar/messages.php file:

return [
    'Your request was processed successfully.' => 'تمت العملية بنجاح.',
    'Congratulations!' => 'تهانينا',
];

Configuration

As optional, if you want to modify the default configuration, you can publish the configuration file:

php artisan flasher:install --config

The configuration file will be located at config/flasher.php and will have the following content:

<?php // config/flasher.php

return [
    // Default notification library (e.g., 'flasher', 'toastr', 'noty', etc.)
    'default' => 'flasher',

    // Path to the main JavaScript file of PHPFlasher
    'main_script' => '/vendor/flasher/flasher.min.js',

    // Path to the stylesheets for PHPFlasher notifications
    'styles' => [
        '/vendor/flasher/flasher.min.css',
    ],

    // Enable translation of PHPFlasher messages using Laravel's translator service
    'translate' => true,

    // Automatically inject PHPFlasher assets in HTML response
    'inject_assets' => true,

    // Global options
    'options' => [
        'timeout' => 5000, // in milliseconds
        'position' => 'top-right',
    ],

    // Configuration for the flash bag (converting Laravel flash messages)
    // Map Laravel session keys to PHPFlasher types
    'flash_bag' => [
        'success' => ['success'],
        'error' => ['error', 'danger'],
        'warning' => ['warning', 'alarm'],
        'info' => ['info', 'notice', 'alert'],
    ],

    // Filter criteria for notifications (e.g., limit number, types)
    'filter' => [
        'limit' => 5, // Limit the number of displayed notifications
    ],
];

Presets

You can create a preset for a custom notification that you want to reuse in multiple places by adding a presets entry in the configuration file.

You can think of a preset as a pre-defined message that you can use in multiple locations.

For example, you can create a preset named entity_saved in the configuration file and then use

<?php // config/flasher.php

return [
    'presets' => [
        'entity_saved' => [
            'type' => 'success',
            'message' => 'Entity saved successfully',
            'title' => 'Entity saved',
        ],
    ],
];

To use the preset, you can call the preset() method and pass the name of the preset as the first argument:

#/ laravel preset

class BookController
{
    public function save()
    {
        flash()->preset('entity_saved');

This is equivalent to:

class BookController
{
    public function save()
    {
        flash()->success('Entity saved successfully', 'Entity saved');

Variables

Presets can also contain variables that can be substituted by using the translation system. Take the following example where you have a preset showing a personalised welcome message to the user.

<?php // config/flasher.php

return [
    'presets' => [
        'hello_user' => [
            'type' => 'success',
            'message' => 'welcome_back_user',
        ],
    ],
];

In the translations file you can define welcome_back_user with the message containing the variable :username.

<?php // /resources/lang/vendor/flasher/en/messages.php

return [
    'welcome_back_user' => 'Welcome back :username',
];

If you want to substitute the :username in the above translation with a username in the controller, you can achieve this by passing an array of values to be substituted as the second argument.

class BookController
{
    public function save()
    {
        $username = 'John Doe';

        flash()->preset('hello_user', ['username' => $username]);

RTL support

PHPFlasher makes it easy to incorporate right-to-left languages like Arabic or Hebrew. it automatically detects the text direction and handles the necessary adjustments for you.

Simply make sure the translation service is enabled and let PHPFlasher handle the rest.

#/ phpflasher rtl

flash()
    ->translate('ar')
    ->success('Your request was processed successfully.', 'Congratulations!');

Translation

PHPFlasher allows you to translate your notification messages and presets, it comes with Arabic, English, French, German, Spanish, Portuguese, Russian, and Chinese translations out of the box. but you can easily add your own translations.

For example, to override the English translation strings for PHPFlasher, you can create a language file at the following location: /resources/lang/vendor/flasher/en/messages.php.

In this file, you should only define the translation strings you want to override. Any translation strings that you don’t override will still be loaded from PHPFlasher’s original language files.

Here are examples of the default translation keys for Arabic, English, and French in PHPFlasher:

<?php // /resources/lang/vendor/flasher/ar/messages.php

return [
        'success' => 'نجاح',
        'error' => 'خطأ',
        'warning' => 'تحذير',
        'info' => 'معلومة',

        'The resource was created' => 'تم إنشاء :resource',
        'The resource was updated' => 'تم تعديل :resource',
        'The resource was saved' => 'تم حفظ :resource',
        'The resource was deleted' => 'تم حذف :resource',

        'resource' => 'الملف',
];
<?php // /resources/lang/vendor/flasher/en/messages.php

return [
    'success' => 'Success',
    'error' => 'Error',
    'warning' => 'Warning',
    'info' => 'Info',

    'The resource was created' => 'The :resource was created',
    'The resource was updated' => 'The :resource was updated',
    'The resource was saved' => 'The :resource was saved',
    'The resource was deleted' => 'The :resource was deleted',

    'resource' => 'resource',
];
<?php // /resources/lang/vendor/flasher/fr/messages.php

return [
        'success' => 'Succès',
        'error' => 'Erreur',
        'warning' => 'Avertissement',
        'info' => 'Information',

        'The resource was created' => 'La ressource :resource a été ajoutée',
        'The resource was updated' => 'La ressource :resource a été mise à jour',
        'The resource was saved' => 'La ressource :resource a été enregistrée',
        'The resource was deleted' => 'La ressource :resource a été supprimée',

        'resource' => '',
];

These translation files facilitate localizing notifications to match user preferences and ensure that your applications can communicate effectively across different linguistic contexts.

#/ laravel arabic translations

use Illuminate\Support\Facades\App;

// Set the locale to be used for the translation
App::setLocale('ar');

// Translate the flash message using the PHPFlasher translation files
flash()->success('The resource was created');

flash()->error('حدث خطأ أثناء إرسال طلبك.');
flash()->warning('يجب إكمال جميع الحقول الإلزامية قبل إرسال النموذج');
flash()->info('سيتم تحديث هذه الصفحة في غضون 10 دقائق.');
#/ laravel french translations

use Illuminate\Support\Facades\App;

// Set the locale to be used for the translation
App::setLocale('fr');

// Translate the flash message using the PHPFlasher translation files
flash()->success('The resource was created');

flash()->error('Une erreur s’est produite lors de l’envoi de votre demande.');
flash()->warning('Vous devez remplir tous les champs obligatoires avant de soumettre le formulaire.');
flash()->info('Cette page sera mise à jour dans 10 minutes.');
Younes

PHPFlasher is a project by Younes ENNAJI.