If you find PHPFlasher useful, please consider giving it a ⭐ star on GitHub 😊. If you spot any typos or have suggestions, feel free to contribute to the documentation 📝. Your feedback helps keep the project up-to-date and well-maintained. Thank you
Requirements
PHPFlasher helps you easily add flash notifications to your Laravel projects, improving user feedback with minimal setup.
To use PHPFlasher with Laravel, you need:
PHP v8.2 or higher Laravel v11.0 or higher
Installation
PHPFlasher is modular, so you can install only the parts you need.
Run this command to install it:
composer require php-flasher/flasher-laravel
After installing, run this command to set up the required assets:
php artisan flasher:install
Usage
To show a notification message, you can use the flash()
helper function or get an instance of flasher
from the service container. Before you return a view or redirect, call one of the notification methods like success()
and pass in the message you want to display.
#/ PHPFlasher
use Flasher\Prime\FlasherInterface;
class BookController
{
public function saveBook()
{
// ...
flash()->success('Your question has been submitted.');
flash('Your feedback has been submitted.');
// ... redirect or render a view
}
/**
* if you prefer to use dependency injection
*/
public function register(FlasherInterface $flasher)
{
// ...
$flasher->success('Your account has been re-activated.');
// ... redirect or render a view
}
}
Choose a message that is clear and tells the user what happened. For example, "Book has been created successfully!"
is a good message, but you can adjust it to fit your application’s context and language.
Using this package is easy. You can add notifications to your application with just one line of code.
#/ usage success
flash()->success('Your address has been updated.');
#/ usage error
flash()->error('There was a problem re-verifying your account.');
#/ usage warning
flash()->warning('Warning: This may be irreversible.');
#/ usage info
flash()->info('Your email has been verified and a confirmation email has been sent.');
These four methods — success()
, error()
, warning()
, and info()
— are shortcuts for the flash()
method. They let you specify the type
and message
in one method call instead of passing them separately to flash()
.
flash()->flash(string $type, string $message, array $options = [], string $title = null)
#/ usage flash
flash()->flash('error', 'There was an issue un-suspending your account.');
Parameter | Description |
---|---|
$type |
Notification type: success, error, warning, info |
$message |
The message you want to show to the user. This can include HTML. If you add links, make sure to add the right classes for your framework. |
$title |
The notification title. Can also include HTML. |
$options |
Custom options for JavaScript libraries (toastr, noty, notyf, etc.). |
The options()
method lets you set multiple options at once by passing an array of key-value pairs. The option()
method lets you set a single option by specifying its name and value. The $append
argument for options()
decides whether the new options should be added to existing ones (true
) or replace them (false
).
flash()->options(array $options, bool $append = true);
#/ usage options
flash()
->options([
'timeout' => 3000, // 3 seconds
'position' => 'top-center',
])
->error('There was an issue receiving your application.');
To set a single option:
flash()->option(string $option, mixed $value);
#/ usage option
flash()
->option('position', 'bottom-right')
->option('timeout', 3000)
->info('Your review has been posted and is being reviewed.');
Set the priority of a flash message. Messages with higher priority appear first.
flash()->priority(int $priority);
#/ usage priority
flash()
->priority(3)
->success('Priority 3 → The operation was successful.');
flash()
->priority(1)
->error('Priority 1 → There was an issue re-verifying your account.');
flash()
->priority(4)
->warning('Priority 4 → Your account may not have been re-activated.');
flash()
->priority(2)
->info('Priority 2 → Your payment has been accepted and a confirmation email has been sent.');
param | description |
---|---|
$priority |
The priority of the notification. Higher numbers are shown first. |
The hops()
method sets how many requests the flash message should last for. By default, flash messages show for one request. Setting the number of hops makes the message stay for multiple requests.
For example, in a multi-page form, you might want to keep messages until all pages are completed.
flash()->hops(int $hops);
flash()
->hops(2)
->success('Your account has been re-verified.');
param | description |
---|---|
$hops |
Number of requests the flash message will persist for |
The translate()
method sets the locale
for translating the flash message. If you provide a locale, the message will be translated to that language. If you pass null
, it uses the default locale.
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 use for translation, or null for the default |
Note: The translate()
method only sets the locale. It doesn’t translate the message by itself.
To translate the message, you need to add the translation keys in your translation files.
For example, to translate the message into Arabic, add these keys to resources/lang/ar/messages.php
:
return [
'Your request was processed successfully.' => 'تمت العملية بنجاح.',
'Congratulations!' => 'تهانينا',
];
Configuration
If you want to change the default settings, you can publish the configuration file:
php artisan flasher:install --config
This will create a file at config/flasher.php
with the following content:
<?php // config/flasher.php
return [
// Default notification library (e.g., 'flasher', 'toastr', 'noty', 'notyf', 'sweetalert')
'default' => 'flasher',
// Path to the main PHPFlasher JavaScript file
'main_script' => '/vendor/flasher/flasher.min.js',
// List of CSS files to style your notifications
'styles' => [
'/vendor/flasher/flasher.min.css',
],
// Set global options for all notifications (optional)
// 'options' => [
// 'timeout' => 5000, // Time in milliseconds before the notification disappears
// 'position' => 'top-right', // Where the notification appears on the screen
// ],
// Automatically inject JavaScript and CSS assets into your HTML pages
'inject_assets' => true,
// Enable message translation using Laravel's translation service
'translate' => true,
// Map Laravel flash message keys to notification types
'flash_bag' => [
'success' => ['success'],
'error' => ['error', 'danger'],
'warning' => ['warning', 'alarm'],
'info' => ['info', 'notice', 'alert'],
],
// Set criteria to filter which notifications are displayed (optional)
// 'filter' => [
// 'limit' => 5, // Maximum number of notifications to show at once
// ],
// Define notification presets to simplify notification creation (optional)
// 'presets' => [
// 'entity_saved' => [
// 'type' => 'success',
// 'title' => 'Entity saved',
// 'message' => 'Entity saved successfully',
// ],
// ],
];
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.
A preset is like a pre-defined message you can use in many places.
For example, create a preset named entity_saved
:
<?php // config/flasher.php
return [
'presets' => [
'entity_saved' => [
'type' => 'success',
'message' => 'Entity saved successfully',
'title' => 'Entity saved',
],
],
];
To use the preset, call the preset()
method and pass the name of the preset:
#/ 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');
Presets can also have variables that you can replace using the translation system. For example, you can have a preset that shows a personalized welcome message.
<?php // config/flasher.php
return [
'presets' => [
'hello_user' => [
'type' => 'success',
'message' => 'welcome_back_user',
],
],
];
In your translation file, define welcome_back_user
with a message containing the variable :username
.
<?php // /resources/lang/vendor/flasher/en/messages.php
return [
'welcome_back_user' => 'Welcome back :username',
];
To replace :username
with the actual username in your controller, pass an array with the values to substitute 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 use right-to-left languages like Arabic
or Hebrew
. It automatically detects the text direction and adjusts accordingly.
Just make sure the translation service is enabled, and PHPFlasher will handle the rest.
#/ phpflasher rtl
flash()
->translate('ar')
->success('Your request was processed successfully.', 'Congratulations!');
Translation
PHPFlasher lets you translate your notification messages
and presets
. It comes with translations for Arabic
, English
, French
, German
, Spanish
, Portuguese
, Russian
, and Chinese
. You can also add your own translations.
To override the English
translations for PHPFlasher, create a file at /resources/lang/vendor/flasher/en/messages.php
.
In this file, define only the translation strings you want to change. Any strings you don’t override will use PHPFlasher’s default translations.
Here are examples of the default translation keys for Arabic
, English
, and French
:
<?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 help you localize notifications to match user preferences, so your application can communicate effectively in different languages.
#/ 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.');