PHPFlasher is modular and consists of multiple libraries, allowing users to install and use only the specific components they need for their project.
Requirements
- PHP 8.2 or higher
- Composer
- Laravel 11+ or Symfony 7+
Installation
PHPFlasher can be installed using composer :
Laravel:
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
This command publishes the required JavaScript and CSS files to your public/vendor/flasher directory. These assets are automatically injected into your HTML responses.
Symfony:
composer require php-flasher/flasher-symfony
After installation, you need to run another command to set up the necessary assets for PHPFlasher:
php bin/console flasher:install
This command publishes the required JavaScript and CSS files to your public/vendor/flasher directory. These assets are automatically injected into your HTML responses.
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('Your profile has been updated.');
flash()->success('The process was completed successfully.');
app('flasher')->success('Task completed successfully.');
// ... redirect or render the view
}
/**
* if you prefer to use dependency injection
*/
public function register(FlasherInterface $flasher)
{
// ...
$flasher->success('Your account has been linked.');
// ... 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 password has been changed.');
#/ usage error
flash()->error('There was an issue receiving your application.');
#/ usage warning
flash()->warning('Your donation may not have been received.');
#/ usage info
flash()->info('Your address has been updated and a confirmation email has been sent.');
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('success', 'The process 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.) |
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',
])
->warning('Warning: This may be irreversible.');
| 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)
->warning('Your order may not have been shipped.');
| 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)
->success('Priority 3 → Your account has been linked.');
flash()
->priority(1)
->error('Priority 1 → There was an issue receiving your donation.');
flash()
->priority(4)
->warning('Priority 4 → Your subscription may not have been activated.');
flash()
->priority(2)
->info('Priority 2 → Your contact has been added 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 |
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 contact has been added and a confirmation email has been sent.');
| 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')
->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 |
Note that the translate() method only sets the locale; it does not 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!' => 'تهانينا',
];
PHPFlasher provides convenient methods for common CRUD operations. These methods automatically generate appropriate success messages with the resource name.
flash()->created(string|object|null $resource = null): Envelope
flash()->updated(string|object|null $resource = null): Envelope
flash()->saved(string|object|null $resource = null): Envelope
flash()->deleted(string|object|null $resource = null): Envelope
#/ usage created
// Basic usage - displays "The resource was created"
flash()->created();
// With a string - displays "The user was created"
flash()->created('user');
// With an object - automatically resolves the class name
flash()->created($user); // displays "The User was created"
#/ usage updated
flash()->updated('post');
#/ usage deleted
flash()->deleted('comment');
| param | description |
|---|---|
$resource |
A string name, an object (class name will be extracted), or null (defaults to “resource”) |
If you pass an object that implements a
getFlashIdentifier()method, that value will be used as the resource name.
Use when() and unless() to conditionally display notifications without wrapping your code in if statements.
flash()->when(bool|\Closure $condition): static
flash()->unless(bool|\Closure $condition): static
#/ usage when
// Only show notification if condition is true
flash()
->when($user->isVerified())
->success('Profile updated successfully!');
// Using a closure for more complex conditions
flash()
->when(fn() => $order->total() > 100)
->success('You qualify for free shipping!');
#/ usage unless
// Show notification unless condition is true
flash()
->unless($user->hasVerifiedEmail())
->warning('Please verify your email address.');
| param | description |
|---|---|
$condition |
A boolean or a Closure that returns a boolean |
The keep() method increments the notification’s hop count by 1, allowing it to persist through an additional request. This is useful when you need a notification to survive one more redirect.
flash()->keep(): static
// Notification will persist through one additional redirect
flash()
->keep()
->success('This message will survive one more redirect.');
| behavior | description |
|---|---|
| Default | Notifications are shown once and then removed |
| With keep() | Notification persists through one additional request |
The
keep()method is a shorthand for incrementing the current hops by 1. For more control, use thehops()method directly.
The delay() method sets a delay (in milliseconds) before the notification is displayed. This is useful for staggered notifications or giving users time to focus on content before showing a message.
flash()->delay(int $delay): static
#/ usage delay
// Notification appears after 2 seconds
flash()
->delay(2000) // 2000 milliseconds = 2 seconds
->info('Check out our new features!');
| param | description |
|---|---|
$delay |
Delay in milliseconds before showing the notification |
Presets allow you to define reusable notification configurations in your config file, then reference them by name in your code.
flash()->preset(string $preset, array $parameters = []): Envelope
First, define presets in your configuration file:
Laravel - config/flasher.php:
return [
'presets' => [
'entity_saved' => [
'type' => 'success',
'title' => 'Saved',
'message' => 'The :entity has been saved successfully.',
],
'welcome' => [
'type' => 'info',
'message' => 'Welcome back, :name!',
'options' => [
'timeout' => 3000,
],
],
],
];
Symfony - config/packages/flasher.yaml:
flasher:
presets:
entity_saved:
type: success
title: Saved
message: 'The :entity has been saved successfully.'
welcome:
type: info
message: 'Welcome back, :name!'
options:
timeout: 3000
Then use the preset in your code:
// Use a preset with parameter substitution
flash()->preset('entity_saved', [':entity' => 'product']);
// Another example
flash()->preset('welcome', [':name' => $user->name]);
| param | description |
|---|---|
$preset |
The name of the preset as defined in your configuration |
$parameters |
Key-value pairs for placeholder substitution in the message |
PHPFlasher fully supports long-running PHP processes like Laravel Octane, FrankenPHP, Swoole, and RoadRunner. The library automatically resets its internal state between requests to prevent notification leakage.
Laravel Octane
PHPFlasher automatically integrates with Laravel Octane. No additional configuration is required. The library listens for the RequestReceived event and resets all internal state including:
- Notification logger (tracked notifications)
- Fallback session storage (used when session is not started)
// This works seamlessly with Octane - no special handling needed
flash()->success('Welcome back!');
Symfony with FrankenPHP / Swoole / RoadRunner
PHPFlasher uses Symfony’s kernel.reset mechanism to automatically reset state between requests. The following services are registered with the kernel.reset tag:
flasher.notification_logger_listener- Resets the notification trackingflasher.worker_listener- Resets fallback session storage
No additional configuration is required. Just install PHPFlasher as usual and it will work correctly in worker mode.
// This works seamlessly in worker mode - no special handling needed
flash()->success('Operation completed!');
Hotwire / Turbo Drive
PHPFlasher includes built-in support for Hotwire Turbo Drive. The library:
- Marks notification containers with
data-turbo-temporaryto prevent caching - Listens for
turbo:before-cacheevents to clean up notifications before page caching - Properly renders notifications after Turbo Drive navigation
// Notifications work seamlessly with Turbo Drive navigation
flash()->success('Profile updated successfully!');
No additional JavaScript configuration is required. PHPFlasher handles Turbo Drive integration automatically.
Solidarity with Palestine.