Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Flash Laravel Package

jambasangsang/flash

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jambasangsang/flash
    

    (Skip service provider registration if using Laravel ≥5.6 with auto-discovery.)

  2. Publish Config:

    php artisan vendor:publish --provider="Jambasangsang\Flash\FlashNotificationServiceProvider" --tag="flash-config"
    

    (Located at config/flash.php.)

  3. First Use Case: Trigger a basic success flash in a controller:

    use Jambasangsang\Flash\Facades\Flash;
    
    public function store(Request $request) {
        $validated = $request->validate([...]);
        // ...
        Flash::success('Record saved successfully!');
        return redirect()->back();
    }
    

Where to Look First

  • Config File: config/flash.php (customize types, durations, or default messages).
  • Facade: Flash::type('message') (e.g., success(), error(), warning()).
  • Blade Integration: Default template at resources/views/vendor/flash/flash.blade.php (override if needed).

Implementation Patterns

Core Workflows

  1. Triggering Flashes:

    // Basic usage
    Flash::success('Action completed!');
    Flash::error('Invalid input.')->important(); // Chaining modifiers
    
    // With data (e.g., for JS handling)
    Flash::info('Updated!', ['key' => 'value']);
    
  2. Conditional Flashes:

    if ($user->save()) {
        Flash::success('Profile updated.');
    } else {
        Flash::error('Update failed.');
    }
    
  3. Redirect Integration:

    return redirect()->route('dashboard')
        ->withFlash('Welcome back!', 'info');
    
  4. Custom Types: Define in config/flash.php:

    'types' => [
        'custom' => [
            'title' => 'Custom Alert',
            'icon' => 'fas fa-rocket',
        ],
    ],
    

    Usage:

    Flash::custom('This is a custom flash!');
    

Integration Tips

  • Blade Overrides: Extend the default template by publishing views:

    php artisan vendor:publish --tag="flash-views"
    

    (Edit resources/views/vendor/flash/flash.blade.php.)

  • JavaScript Handling: Pass data to JS via with():

    Flash::success('Data saved', ['redirect' => route('dashboard')]);
    

    Access in JS:

    @if(session()->has('flash_data'))
        const data = @json(session('flash_data'));
        if (data.redirect) window.location.href = data.redirect;
    @endif
    
  • Middleware for Global Flashes:

    public function handle($request, Closure $next) {
        if ($request->user()->justRegistered()) {
            Flash::success('Registration complete!');
        }
        return $next($request);
    }
    
  • Testing:

    $this->get('/route')
         ->assertSessionHas('flash', ['type' => 'success', 'message' => '...']);
    

Gotchas and Tips

Pitfalls

  1. Session Dependency:

    • Flashes rely on Laravel’s session. Ensure SESSION_DRIVER is configured (e.g., file, redis).
    • Fix: Verify config/session.php and clear old sessions if flashes persist unexpectedly:
      php artisan session:clear
      
  2. Template Overrides Not Loading:

    • If custom views aren’t picked up, check:
      • The view file exists at resources/views/vendor/flash/flash.blade.php.
      • No typos in the @extends directive (default extends layouts.app).
    • Debug: Temporarily add {{ dd('Flash template loaded') }} to the view.
  3. Chaining Methods:

    • Methods like important() or autoDismiss() must be chained immediately after the type call:
      // Works
      Flash::success('Test')->important();
      
      // Fails (returns null)
      $flash = Flash::success('Test');
      $flash->important(); // Error: Call to undefined method
      
  4. CSRF Conflicts:

    • If flashes disappear after form submissions, ensure CSRF tokens are included in redirects:
      return redirect()->route('dashboard')->withFlash('...')->withHeaders([
          'X-CSRF-TOKEN' => csrf_token(),
      ]);
      

Debugging Tips

  • Inspect Session Data: Dump the session to verify flashes are stored:

    dd(session()->all());
    

    Look for flash or flash_data keys.

  • Check Config Overrides: Ensure no other packages (e.g., laravel-notification-channels) are overriding flash behavior.

  • Clear Published Config: If changes to config/flash.php don’t apply, republish:

    php artisan config:clear
    

Extension Points

  1. Custom Flash Types: Extend the FlashNotificationServiceProvider to add dynamic types:

    // In a service provider
    public function boot() {
        Flash::extend('dynamic', function ($message, $data) {
            return [
                'type' => 'dynamic',
                'message' => $message,
                'data' => $data,
                'title' => 'Dynamic Alert',
            ];
        });
    }
    
  2. Queue Flashes for Async Processing: Use Laravel queues to delay flash messages:

    Flash::queue('Processing...')->delay(now()->addMinutes(1));
    

    (Requires custom queue listener implementation.)

  3. Localization: Localize messages via language files (resources/lang/en/flash.php):

    return [
        'success' => 'Operation completed successfully.',
    ];
    

    Usage:

    Flash::success(__('flash.success'));
    
  4. Dark Mode Support: Add a dark modifier to the config:

    'types' => [
        'success' => [
            'title' => 'Success',
            'icon' => 'fas fa-check',
            'classes' => 'bg-green-500 text-white dark:bg-green-700',
        ],
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours