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
PHPFlasher Laravel
PHPFlasher is a trusted and well-supported package that allows you to easily integrate flash notification messages into your Laravel projects.
Its compatibility with Laravel versions 4.0 to 9 makes it a reliable choice for use in a wide range of Laravel projects, ensuring seamless integration and hassle-free functionality.
To use PHPFlasher in a Laravel application, you need :
PHP >= 5.3 Laravel >= 4.0
Installation
PHPFlasher is modular and consists of multiple libraries, allowing users to install and use only the specific components they need for their project.
PHPFlasher can be installed using composer :
composer require php-flasher/flasher-laravel
PHPFlasher includes a default notification style , but users can also install additional adapters to customize the appearance of notifications within their projects such as :
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 addSuccess()
method and pass in the desired message to be displayed.
#/ PHPFlasher
class BookController
{
public function saveBook()
{
// ...
flash('Your form has been submitted.');
flash()->addSuccess('Your product has been shipped.');
flash()
->success('Your question has been submitted.')
->flash();
app('flasher')->addSuccess('Your account has been re-verified.');
// ... redirect or render the view
}
/**
* if you prefer to use dependency injection
*/
public function register(FlasherInterface $flasher)
{
// ...
$flasher->addSuccess('Your account has been re-verified.');
// ... 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 addSuccess
flash()->addSuccess('Your account has been reinstated.');
#/ usage addError
flash()->addError('There was an issue restoring your account.');
#/ usage addWarning
flash()->addWarning('Your application may not have been received.');
#/ usage addInfo
flash()->addInfo('Your account has been deactivated and a confirmation email has been sent.');
These four methods addSuccess()
, addError()
, addWarning()
, addInfo()
are simply convenience shortcuts for the addFlash()
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 addFlash()
method.
flash()->addFlash(string $type, string $message, string $title = null, array $options = [])
#/ usage addFlash
flash()->addFlash('success', 'The action was completed successfully.');
param | description | |
---|---|---|
$type |
Notification type : success, error, warning, info ….etc | |
$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) |
Modifiers
You can specify custom options for the flash messages when using a JavaScript library like toastr
, noty
, or notyf
.
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 $merge
argument for the options()
method can be used to specify whether the new options should be merged with any existing options,
or whether they should overwrite them.
flash()->options(array $options, bool $merge = true);
Refer to the documentation for your chosen JavaScript library to see which options are available and how they should be formatted.
#/ usage options
flash()
->options([
'timeout' => 3000, // 3 seconds
'position' => 'top-center',
])
->addSuccess('Your password has been reset.');
param | description |
---|---|
$options |
Custom options to be passed to the javascript libraries (toastr, noty, notyf …etc) |
$merge |
Merge options if you call the options method multiple times |
Set a single option by specifying its name and value as separate arguments.
flash()->option(string $option, mixed $value);
#/ usage option
flash()
->option('position', 'top-center')
->option('timeout', 3000)
->addInfo('Your information has been saved and a confirmation email has been sent.');
param | description |
---|---|
$option |
Option key |
$value |
Option value |
Sets the priority of a flash message, the highest priority will be displayed first.
flash()->priority(int $priority);
#/ usage priority
flash()
->priority(3)
->addSuccess('Priority 3 → Your information has been saved.');
flash()
->priority(1)
->addError('Priority 1 → There was an issue re-verifying your account.');
flash()
->priority(4)
->addWarning('Priority 4 → Your account may not have been re-activated.');
flash()
->priority(2)
->addInfo('Priority 2 → Your item has been added to your cart, but may not be reserved until checkout.');
param | description |
---|---|
$priority |
The priority of the notification, the higher the priority, the sooner it will be displayed |
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)
->addWarning('Your information may not have been saved.');
param | description |
---|---|
$hops |
indicate how many requests the flash message will persist for |
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')
->addSuccess('Your request was processed successfully.', 'Congratulations!');
#/ usage translate with position
flash()
->translate('ar')
->option('position', 'top-left')
->addSuccess('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
, If you are using Laravel 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
The configuration file will be located at config/flasher.php
and will have the following content:
<?php // config/flasher.php
return [
/*
|--------------------------------------------------------------------------
| Default PHPFlasher library
|--------------------------------------------------------------------------
| This option controls the default library that will be used by PHPFlasher
| to display notifications in your Laravel application. PHPFlasher supports
| several libraries, including "flasher", "toastr", "noty", "notyf",
| "sweetalert" and "pnotify".
|
| The "flasher" library is used by default. If you want to use a different
| library, you will need to install it using composer. For example, to use
| the "toastr" library, run the following command:
| composer require php-flasher/flasher-toastr-laravel
|
| Here is a list of the supported libraries and the corresponding composer
| commands to install them:
|
| "toastr" : composer require php-flasher/flasher-toastr-laravel
| "noty" : composer require php-flasher/flasher-noty-laravel
| "notyf" : composer require php-flasher/flasher-notyf-laravel
| "sweetalert" : composer require php-flasher/flasher-sweetalert-laravel
| "pnotify" : composer require php-flasher/flasher-pnotify-laravel
*/
'default' => 'flasher',
/*
|--------------------------------------------------------------------------
| Main PHPFlasher javascript file
|--------------------------------------------------------------------------
| This option specifies the location of the main javascript file that is
| required by PHPFlasher to display notifications in your Laravel application.
|
| By default, PHPFlasher uses a CDN to serve the latest version of the library.
| However, you can also choose to download the library locally or install it
| using npm.
|
| To use the local version of the library, run the following command:
| php artisan flasher:install
|
| This will copy the necessary assets to your application's public folder.
| You can then specify the local path to the javascript file in the 'local'
| field of this option.
*/
'root_script' => [
'cdn' => 'https://cdn.jsdelivr.net/npm/@flasher/flasher@1.2.4/dist/flasher.min.js',
'local' => '/vendor/flasher/flasher.min.js',
],
/*
|--------------------------------------------------------------------------
| Whether to use CDN for PHPFlasher assets or not
|--------------------------------------------------------------------------
| This option controls whether PHPFlasher should use CDN links or local assets
| for its javascript and CSS files. By default, PHPFlasher uses CDN links
| to serve the latest version of the library. However, you can also choose
| to use local assets by setting this option to 'false'.
|
| If you decide to use local assets, don't forget to publish the necessary
| files to your application's public folder by running the following command:
| php artisan flasher:install
|
| This will copy the necessary assets to your application's public folder.
*/
'use_cdn' => true,
/*
|--------------------------------------------------------------------------
| Translate PHPFlasher messages
|--------------------------------------------------------------------------
| This option controls whether PHPFlasher should pass its messages to the Laravel's
| translation service for localization.
|
| By default, this option is set to 'true', which means that PHPFlasher will
| attempt to translate its messages using the translation service.
|
| If you don't want PHPFlasher to use the Laravel's translation service, you can
| set this option to 'false'. In this case, PHPFlasher will use the messages
| as-is, without attempting to translate them.
*/
'auto_translate' => true,
/*
|--------------------------------------------------------------------------
| Inject PHPFlasher in Response
|--------------------------------------------------------------------------
| This option controls whether PHPFlasher should automatically inject its
| javascript and CSS files into the HTML response of your Laravel application.
|
| By default, this option is set to 'true', which means that PHPFlasher will
| listen to the response of your application and automatically insert its
| scripts and stylesheets into the HTML before the closing `</body>` tag.
|
| If you don't want PHPFlasher to automatically inject its scripts and stylesheets
| into the response, you can set this option to 'false'. In this case, you will
| need to manually include the necessary files in your application's layout.
*/
'auto_render' => true,
'flash_bag' => [
/*
|-----------------------------------------------------------------------
| Enable flash bag
|-----------------------------------------------------------------------
| This option controls whether PHPFlasher should automatically convert
| Laravel's flash messages to PHPFlasher notifications. This feature is
| useful when you want to migrate from a legacy system or another
| library that uses similar conventions for flash messages.
|
| When this option is set to 'true', PHPFlasher will check for flash
| messages in the session and convert them to notifications using the
| mapping specified in the 'mapping' option. When this option is set
| to 'false', PHPFlasher will ignore flash messages in the session.
*/
'enabled' => true,
/*
|-----------------------------------------------------------------------
| Flash bag type mapping
|-----------------------------------------------------------------------
| This option allows you to map or convert session keys to PHPFlasher
| notification types. On the left side are the PHPFlasher types.
| On the right side are the Laravel session keys that you want to
| convert to PHPFlasher types.
|
| For example, if you want to convert Laravel's 'danger' flash
| messages to PHPFlasher's 'error' notifications, you can add
| the following entry to the mapping:
| 'error' => ['danger'],
*/
'mapping' => [
'success' => ['success'],
'error' => ['error', 'danger'],
'warning' => ['warning', 'alarm'],
'info' => ['info', 'notice', 'alert'],
],
],
/*
|-----------------------------------------------------------------------
| Global Filter Criteria
|-----------------------------------------------------------------------
| This option allows you to filter the notifications that are displayed
| in your Laravel application. By default, all notifications are displayed,
| but you can use this option to limit the number of notifications or
| filter them by type.
|
| For example, to limit the number of notifications to 5, you can set
| the 'limit' field to 5:
| 'limit' => 5,
|
| To filter the notifications by type, you can specify an array of
| types that you want to display. For example, to only display
| error notifications, you can set the 'types' field to ['error']:
| 'types' => ['error'],
|
| You can also combine multiple criteria by specifying multiple fields.
| For example, to display up to 5 error notifications, you can set
| the 'limit' and 'types' fields like this:
| 'limit' => 5,
| 'types' => ['error'],
*/
'filter_criteria' => [
'limit' => 5, // Limit the number of notifications to display
],
];
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 addPreset()
method and pass the name of the preset as the first argument:
#/ laravel addPreset
class BookController
{
public function save()
{
flash()->addPreset('entity_saved');
This is equivalent to:
class BookController
{
public function save()
{
flash()->addSuccess('Entity saved successfully', 'Entity saved');
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()->addPreset('hello_user', ['username' => $username]);
Dark Mode
PHPFlasher supports dark mode,
allowing you to seamlessly integrate it with the dark mode of your design.
By default, PHPFlasher uses the prefers-color-scheme
CSS media query to automatically detect the user’s dark mode preference.
However, you can also choose to manually toggle dark mode using the class strategy
.
#/ flasher darkMode
// config/flasher.php
return [
'themes' => [
'flasher' => [
'options' => [
'darkMode' => 'class',
],
],
],
];
Now instead of relying on the prefers-color-scheme
CSS media query, dark mode will be applied whenever .dark class is present earlier in the HTML tree.
To enable dark mode, add dark class to the <html>
or <body>
tag, as follows:
<!-- Dark mode enabled -->
<html class="dark">
or
<!-- Dark mode enabled -->
<body class="dark">
You can even customize the dark mode selector by setting darkMode
to an array with your desired class name as the second item.
return [
'themes' => [
'flasher' => [
'options' => [
'darkMode' => ['class', '[data-mode="dark"]'],
],
],
],
];
And now you can add the [data-mode=”dark”] selector to the <html> or <body> tag, as follows:
<!-- Dark mode enabled -->
<html data-mode="dark">
or
<!-- Dark mode enabled -->
<body data-mode="dark">
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')
->addSuccess('Your request was processed successfully.', 'Congratulations!');
Translation
PHPFlasher allows you to translate your notification messages
, presets
, it comes with Arabic
, English
and French
translations out of the box, but you can easily add your own translations.
For example, if you need 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 is a list of the default translation keys for 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' => '',
];
#/ 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()->addSuccess('The resource was created');
flash()->addError('حدث خطأ أثناء إرسال طلبك.');
flash()->addWarning('يجب إكمال جميع الحقول الإلزامية قبل إرسال النموذج');
flash()->addInfo('سيتم تحديث هذه الصفحة في غضون 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()->addSuccess('The resource was created');
flash()->addError('Une erreur s’est produite lors de l’envoi de votre demande.');
flash()->addWarning('Vous devez remplir tous les champs obligatoires avant de soumettre le formulaire.');
flash()->addInfo('Cette page sera mise à jour dans 10 minutes.');
Laravel version < 5.5
in Laravel version 5.5 and beyond this step can be skipped if package auto-discovery is enabled.
Add the service provider to config/app.php
.
'providers' => [
...
Flasher\Laravel\FlasherServiceProvider::class,
...
];
Optionally include the Facade in config/app.php
.
'Flasher' => Flasher\Laravel\Facade\Flasher::class,