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! 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
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: 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('Registration successful! Please log in.');

            return redirect()->route('login');
        } catch (\Exception $e) {
            flash()->error('Registration failed. Please try again.');

            return back()->withInput();
        }
    }
}

AJAX Requests

Using PHPFlasher with AJAX requests:

APIController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class APIController extends Controller
{
    public function save(Request $request)
    {
        try {
            // Process the data
            $data = $request->validate([
                'title' => 'required|string|max:255',
                'content' => 'required|string',
            ]);

            // Save to database...

            // Flash messages will be available in the next response
            flash()->success('Data saved successfully!');

            if ($request->expectsJson()) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Data saved successfully!'
                ]);
            } else {
                return back();
            }
        } catch (\Exception $e) {
            flash()->error('Failed to save data');

            if ($request->expectsJson()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Failed to save data'
                ], 400);
            } else {
                return back()->withInput();
            }
        }
    }
}
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');
    });
});

Tip: AJAX Integration

PHPFlasher requires explicit JavaScript calls to display notifications in AJAX scenarios. Call flasher methods directly in your JavaScript after receiving a 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

PHPFlasher can be configured to customize its behavior. The configuration file is located at config/flasher.php.

flasher.php
Configuration
<?php

return [
    'default' => env('FLASHER_DEFAULT', 'flasher'),

    'drivers' => [
        'flasher' => [
            'root' => env('FLASHER_ROOT', base_path('vendor/flasher')),
            'translate' => env('FLASHER_TRANSLATE', true),
            'inject_assets' => env('FLASHER_INJECT_ASSETS', true),
        ],
    ],

    'presets' => [
        // Your custom presets here
    ],
];

Presets

PHPFlasher provides configuration presets for different notification styles.

Available Presets

Default

Balanced notifications with standard animations and positioning.

flasher: default

Minimal

Clean notifications with minimal styling and effects.

flasher: minimal

Translations

PHPFlasher supports translation of flash messages using Laravel's translation system.

Enabling Translations

PHPFlasher automatically uses Laravel's current locale. You can set it in your application:

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])
);

Creating Translation Files

Create translation files in the lang/vendor/flasher directory:

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

return [
    'success' => 'Success! :resource was created.',
    'error' => 'Error! Please try again.',
    'warning' => 'Warning! Please review your data.',
    'info' => 'Info: :message',
];

Translation with Parameters

You can use parameters in your translations:

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

flash()
    ->success(
        trans('flasher::messages.welcome_user', ['name' => $user->first_name])
    );

// Or directly with PHPFlasher
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
نجاح! تم إنشاء العنصر.
خطأ! يرجى المحاولة مرة أخرى.