Palestinian Flag Solidarity with Palestine. We seek justice and peace, and strongly oppose all forms of injustice and genocide.
Enjoying PHPFlasher? Show your support with a star on GitHub! It helps others discover this tool and motivates us to keep improving it. Thank you

Requirements

PHPFlasher helps you easily add flash notifications to your Laravel projects, improving user feedback with minimal setup.

Required

PHP Version

v8.2 or higher
Required

Laravel Version

v11.0 or higher

Using older PHP or Laravel versions?

If you need to use PHP < v8.2 or Laravel < v11.0, use PHPFlasher v1 instead. It supports PHP ≥ v5.3 and Laravel ≥ v5.0. Check out the v1 documentation here .

Installation

PHPFlasher is modular. You can install only the parts you need.

Run this command to install it:

Terminal
Installation
Laravel Installation
composer require php-flasher/flasher-laravel

After installing, run this command to set up the required assets:

Terminal
Setup Assets
php artisan flasher:install

Ready in under a minute!

That's it! No need for complex configuration - PHPFlasher works right out of the box with sensible defaults.

Best Practice

Commit the installed assets to your version control system to ensure everyone on your team has the same notification experience.

Usage

Basic Usage

Here's a basic example of using PHPFlasher in a Laravel controller:

ProductController.php
<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function store(Request $request)
    {
        // Validate the request
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric',
        ]);

        // Create the product
        Product::create($validated);

        // Add a success notification
        flash()->success('Product created successfully!');

        return redirect()->route('products.index');
    }
}

Pro Tip: Three Ways to Use PHPFlasher

PHPFlasher provides three ways to create notifications:

  • Helper function: flash()->success('Message');
  • Facade: use Flasher\Laravel\Facade\Flasher; Flasher::success('Message');
  • Dependency injection: public function __construct(private FlasherInterface $flasher) {}

Notification Types

PHPFlasher supports different types of notifications:

NotificationTypes.php
// Success message
flash()->success('Your changes have been saved!');

// Error message
flash()->error('Something went wrong!');

// Warning message
flash()->warning('Please review your data before proceeding.');

// Info message
flash()->info('The system will be down for maintenance tonight.');
Success

Your changes have been saved!

Error

Something went wrong!

Warning

Please review your data before proceeding.

Info

The system will be down for maintenance tonight.

Adding a Title

You can add a title to your notifications:

Title.php
flash()->success('Your profile has been updated successfully.', 'Profile Updated');
Profile Updated

Your profile has been updated successfully.

Notification Options

Customize your notifications with various options:

Options.php
flash()
    ->option('position', 'top-center')  // Position on the screen
    ->option('timeout', 5000)           // How long to display (milliseconds)
    ->option('rtl', true)               // Right-to-left support
    ->success('Your changes have been saved!');

Positioning

top-right top-left top-center bottom-right bottom-left bottom-center

Timing

Control how long notifications display with the timeout option (milliseconds).

Set to 0 to require manual dismissal.

Animations

Choose from various animations:

fade slide zoom flip

Common Examples

Here are some common examples of using PHPFlasher in your Laravel applications.

CRUD Operations

A complete example showing notifications for Create, Read, Update, and Delete operations:

PostController.php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ]);

        Post::create($validated);

        flash()->success('Post created successfully!', 'Success');

        return redirect()->route('posts.index');
    }

    public function update(Request $request, Post $post)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ]);

        $post->update($validated);

        flash()->success('Post updated successfully!');

        return redirect()->route('posts.index');
    }

    public function destroy(Post $post)
    {
        $post->delete();

        flash()->info('Post was deleted');

        return redirect()->route('posts.index');
    }
}

Best Practice: Consistent Messaging

Use the same notification style and wording for similar operations across your application. This provides a consistent user experience.

Form Validation Feedback

Show validation errors with meaningful notifications:

RegisterController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email|unique:users,email',
                'password' => 'required|min:8|confirmed',
            ]);

            User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => Hash::make($validated['password']),
            ]);

            flash()->success('Your account has been created successfully!', 'Welcome!');

            return redirect()->route('login');
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Return back with validation errors
            flash()->error('Please fix the errors in the form.', 'Registration Failed');

            return back()->withErrors($e->validator)->withInput();
        }
    }
}

AJAX Support

PHPFlasher can be used with AJAX requests, but requires explicit handling in your JavaScript code:

ApiController.php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function saveData(Request $request)
    {
        try {
            // Process data...
            $success = true; // Assuming operation succeeded

            if ($success) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Data saved successfully!'
                ]);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Failed to save data'
                ], 400);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred: ' . $e->getMessage()
            ], 500);
        }
    }
}
script.js
// Import flasher in your JS file
import flasher from '@flasher/flasher';

document.getElementById('saveForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch('/api/save', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
        // Explicitly call flasher methods based on the response
        if (data.status === 'success') {
            flasher.success(data.message);
        } else {
            flasher.error(data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        flasher.error('An unexpected error occurred');
    });
});

Alternative: Dedicated Flash Message API

You can also create a dedicated endpoint that returns flash messages as part of your API response:

FlashController.php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class FlashController extends Controller
{
    public function getFlashMessages()
    {
        // Get all flash messages as an array
        $messages = flash()->render('array');

        return response()->json($messages);
    }
}
fetch-flash.js
import flasher from '@flasher/flasher';

// Function to fetch and display flash messages
function fetchFlashMessages() {
    fetch('/api/flash', {
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(messages => {
        // Render the flash messages using PHPFlasher
        flasher.render(messages);
    })
    .catch(error => {
        console.error('Error fetching flash messages:', error);
    });
}

// Call this after operations that might set flash messages on the server
// or periodically if needed
fetchFlashMessages();

Expert Tip: AJAX Integration

PHPFlasher requires explicit JavaScript calls to display notifications in AJAX scenarios. You have several options:

  • 1 Call flasher methods directly in your JavaScript after receiving a response
  • 2 Use the render() method with a dedicated endpoint that returns flash messages
  • 3 Integrate with frameworks like InertiaJS to automatically include flash messages in each response

Using with Laravel Middleware

You can add notifications from middleware for actions like authorization:

AdminAccessMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminAccessMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user() || !$request->user()->isAdmin()) {
            flash()->error('You do not have access to this area.', 'Access Denied');

            return redirect()->route('home');
        }

        return $next($request);
    }
}

Configuration

If you want to change the default settings, you can publish the configuration file:

Terminal
Generate Config
php artisan flasher:install --config

This will create a file at config/flasher.php with the following content:

config/flasher.php
<?php

declare(strict_types=1);

use Flasher\Prime\Configuration;

/*
 * Default PHPFlasher configuration for Laravel.
 *
 * This configuration file defines the default settings for PHPFlasher when
 * used within a Laravel application. It uses the Configuration class from
 * the core PHPFlasher library to establish type-safe configuration.
 *
 * @return array PHPFlasher configuration
 */
return Configuration::from([
    // 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,

    // URL patterns to exclude from asset injection and flash_bag conversion
    'excluded_paths' => [],

    // 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',
    //     ],
    // ],
]);

Common Configuration Examples

Change Default Position

<?php // config/flasher.php

return [
    'options' => [
        'position' => 'bottom-right',
    ],
];

Change Default Timeout

<?php // config/flasher.php

return [
    'options' => [
        'timeout' => 8000,  // 8 seconds
    ],
];

Expert Advice

The default configuration works great for most projects. Only customize if you need specific behaviors like:

  • Changing the default notification theme (Toastr, SweetAlert, etc.)
  • Setting global position/timing for all notifications
  • Using custom paths for assets

Converting Laravel Session Flash Messages

PHPFlasher automatically converts Laravel's native session flash messages to PHPFlasher notifications, making migration easy:

LegacyController.php
// Your existing Laravel flash messages still work
session()->flash('success', 'Changes were saved!');

// Or with the helper
$request->session()->flash('error', 'Something went wrong!');

// They will be converted to PHPFlasher notifications automatically
// You can gradually migrate your codebase to use PHPFlasher directly

Presets

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

What are presets?

Presets are pre-defined notification configurations that you can reuse throughout your application. They help maintain consistent messaging and reduce code duplication.

For example, create a preset named entity_saved:

config/flasher.php
<?php // config/flasher.php

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

        'payment_received' => [
            'type' => 'success',
            'message' => 'Payment of %amount% has been received.',
            'title' => 'Payment Confirmed',
            'options' => [
                'timeout' => 8000,
                'position' => 'top-center',
            ],
        ],

        'account_locked' => [
            'type' => 'error',
            'message' => 'Your account has been locked due to multiple failed attempts.',
            'title' => 'Security Alert',
            'options' => [
                'timeout' => 0,  // Requires manual dismissal
                'position' => 'center',
            ],
        ],
    ],
];

To use the preset, call the preset() method and pass the name of the preset:

BookController.php
<?php

namespace App\Http\Controllers;

use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{
    public function store(Request $request)
    {
        // Save the book...

        // Use a preset for the notification
        flash()->preset('entity_saved');

        return redirect()->route('books.index');
    }
}

class PaymentController extends Controller
{
    public function confirm(Request $request)
    {
        // Process payment...

        // Use a preset with parameters
        flash()->preset('payment_received', [
            'amount' => '€50.00'
        ]);

        return redirect()->route('payment.receipt');
    }
}

The first example is the same as:

EquivalentCode.php
<?php

namespace App\Http\Controllers;

class BookController extends Controller
{
    public function store()
    {
        // Without preset, would need to do:
        flash()->success('Entity saved successfully', 'Entity saved');

        return redirect()->route('books.index');
    }
}

Common Preset Use Cases

  • CRUD Operations

    Create consistent notifications for create, update, and delete operations

  • User Feedback

    Standardize welcome messages, payment confirmations, and other user communications

  • Error Handling

    Create consistent error notifications with custom styling and actionable messages

Best Practice: Centralized Message Management

Store all your notification presets in one place to ensure consistent messaging across your application. This makes it easy to update notification wording or styling globally.

Dynamic Presets with Parameters

You can create more flexible presets using parameters:

config/flasher.php
<?php // config/flasher.php

return [
    'presets' => [
        'order_created' => [
            'type' => 'success',
            'message' => 'Order #%order_id% has been created successfully. Total: %amount%',
            'title' => 'Order Created'
        ],
    ],
];

Then use the preset with parameters:

OrderController.php
// Parameters are passed as an array
flash()->preset('order_created', [
    'order_id' => '12345',
    'amount' => '$99.99'
]);

// This will display: "Order #12345 has been created successfully. Total: $99.99"

Translations & RTL Support

PHPFlasher integrates perfectly with Laravel's translation system, making it easy to display notifications in multiple languages.

Basic Translation

Use the translate() method to set the language for a notification:

TranslationExample.php
// Translation will automatically use the current locale from Laravel's App::getLocale()
flash()->success('The resource was created');

// Or explicitly specify a language
flash()->translate('fr')->success('The resource was created');
flash()->translate('ar')->success('The resource was created');

Translation Files

Define your translations in PHP files in the resources/lang/vendor/flasher/ directory:

<?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',
];

Right-to-Left (RTL) Support

PHPFlasher automatically handles right-to-left languages like Arabic and Hebrew. The layout adjusts based on the language:

تهانينا

تمت العملية بنجاح.

RTLExample.php
// Using Arabic language automatically enables RTL
flash()
    ->translate('ar')
    ->success('Your request was processed successfully.', 'Congratulations!');

// Or explicitly set RTL mode
flash()
    ->option('rtl', true)
    ->success('Your request was processed successfully.', 'Congratulations!');

Using Laravel's App Locale

PHPFlasher automatically uses Laravel's current locale:

LocaleExample.php
// Set the locale in Laravel
App::setLocale('fr');

// PHPFlasher automatically uses the current locale
flash()->success('The resource was created');

// With parameters
flash()->success(
    trans('messages.welcome', ['name' => $user->name])
);

Translation with Parameters

You can use parameters in your translations:

TranslationWithParams.php
// In resources/lang/vendor/flasher/en/messages.php:
// 'welcome.user' => 'Welcome, :name!'

flash()
    ->success(
        trans('welcome.user', ['name' => $user->first_name])
    );

// Or directly with PHPFlasher (if using presets with placeholders)
flash()->preset('welcome_user', ['name' => $user->first_name]);

Best Practice: Centralize Your Translations

Store all user-facing notification messages in translation files rather than hardcoding them. This makes it much easier to update wording or add new languages later.

🇺🇸

English

en
Success! Item was created.
Error! Please try again.
🇫🇷

French

fr
Succès! L'élément a été créé.
Erreur! Veuillez réessayer.
🇲🇦

Arabic

ar
نجاح! تم إنشاء العنصر.
خطأ! يرجى المحاولة مرة أخرى.

Additional Features

Multiple Themes

Choose from 6+ themes including Toastr, SweetAlert, Notyf, Noty and more.

View themes

Livewire Support

Seamless integration with Laravel Livewire for dynamic notifications without page reload.

Learn more

AJAX Support

Show notifications from AJAX responses automatically with JSON responses.

Learn more

Ready to elevate your Laravel UI?

Start using PHPFlasher today and give your users beautiful notifications in minutes!