### Install Livewire Toaster Source: https://context7.com/masmerise/livewire-toaster/llms.txt Install the package using Composer and optionally publish configuration and view files. ```bash composer require masmerise/livewire-toaster # Publish config (optional) php artisan vendor:publish --tag=toaster-config # Publish views for customization (optional) php artisan vendor:publish --tag=toaster-views ``` -------------------------------- ### Install Livewire Toaster with Composer Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Install the package using Composer. This is the first step to integrate Livewire Toaster into your Laravel project. ```bash composer require masmerise/livewire-toaster ``` -------------------------------- ### Setup Toaster Hub Component Source: https://context7.com/masmerise/livewire-toaster/llms.txt Include the `` component in your master layout to render the toast container and initialize the front-end hub. ```html @vite(['resources/css/app.css', 'resources/js/app.js']) {{ $slot }} {{-- Required: place before --}} ``` -------------------------------- ### Run Composer Tests Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Execute the project's tests using Composer. Ensure you have Composer installed and the project dependencies are set up. ```bash composer test ``` -------------------------------- ### Custom Collector Decorator Example Source: https://context7.com/masmerise/livewire-toaster/llms.txt Implement the `Collector` interface to create custom decorators that intercept, transform, or augment toast collection. This example logs toasts to the database before forwarding them. ```php use Masmerise\Toaster\Collector; use Masmerise\Toaster\Toast; // Custom decorator: log every dispatched toast to the database final readonly class AuditingCollector implements Collector { public function __construct(private Collector $next) {} public function collect(Toast $toast): void { ToastAudit::create([ 'message' => $toast->message->value, 'type' => $toast->type->value, 'created_at' => now(), ]); $this->next->collect($toast); // always forward to the inner collector } public function release(): array { return $this->next->release(); } } // Register in AppServiceProvider::register() use Masmerise\Toaster\Collector; public function register(): void { $this->app->extend( Collector::class, static fn (Collector $next) => new AuditingCollector($next) ); } ``` -------------------------------- ### Toaster Facade - Basic Usage Source: https://context7.com/masmerise/livewire-toaster/llms.txt Demonstrates how to dispatch simple success, error, info, and warning toasts using the Toaster facade. ```APIDOC ## Toaster Facade - Basic Usage ### Description Dispatch simple toast notifications for success, error, information, or warning messages. ### Method `Toaster::[type](message)` ### Parameters - **type** (string) - The type of toast to display (e.g., `success`, `error`, `info`, `warning`). - **message** (string) - The content of the toast notification. ### Request Example ```php use Masmerise\Toaster\Toaster; Toaster::success('User registered successfully!'); Toaster::error('Something went wrong.'); Toaster::info('Your session will expire soon.'); Toaster::warning('Disk usage is above 90%.'); ``` ``` -------------------------------- ### Toaster Facade - With Translation Source: https://context7.com/masmerise/livewire-toaster/llms.txt Shows how to dispatch toasts using translation keys for internationalization, with optional parameters. ```APIDOC ## Toaster Facade - With Translation ### Description Dispatch toasts using Laravel translation keys for automatic i18n resolution. This requires `'translate' => true` in the `config/toaster.php` file. ### Method `Toaster::[type](translation_key, parameters)` ### Parameters - **type** (string) - The type of toast to display (e.g., `success`, `error`, `info`, `warning`). - **translation_key** (string) - The key for the translation string. - **parameters** (array, optional) - An array of parameters to pass to the translation function. ### Request Example ```php use Masmerise\Toaster\Toaster; // Assuming 'auth.registered' is a translation key Toaster::success('auth.registered', ['name' => $user->name]); // This will resolve to something like: __('auth.registered', ['name' => 'Alice']) → "Welcome, Alice!" ``` ``` -------------------------------- ### Configure Livewire Toaster Source: https://context7.com/masmerise/livewire-toaster/llms.txt Customize toast behavior like accessibility, alignment, duration, and translation through the published config file. ```php // config/toaster.php return [ // Adds 1 extra second per 100 words to ensure readability of long toasts 'accessibility' => true, // Vertical alignment of the toast container: "bottom" | "middle" | "top" 'alignment' => 'bottom', // Show a close button on each toast: true | false 'closeable' => true, // On-screen duration in milliseconds (minimum: 3000) 'duration' => 3000, // Horizontal position of toasts: "center" | "left" | "right" 'position' => 'right', // Replace similar toasts instead of stacking (takes precedence over suppress) 'replace' => false, // Suppress duplicate toasts while an identical one is still on-screen 'suppress' => false, // Auto-translate messages passed as Laravel translation keys 'translate' => true, ]; ``` -------------------------------- ### Publish Toaster Configuration Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Publish the package's configuration file to customize its behavior. This allows you to modify settings like toast duration, position, and accessibility. ```bash php artisan vendor:publish --tag=toaster-config ``` -------------------------------- ### Toaster::toast() / PendingToast Source: https://context7.com/masmerise/livewire-toaster/llms.txt Use the `Toaster::toast()` facade method or `PendingToast::create()` to build and dispatch toasts. The toast is automatically dispatched on object destruction if not already dispatched. ```APIDOC ## `Toaster::toast()` / `PendingToast` Returns a `PendingToast` builder for fine-grained, conditional toast composition. The toast is automatically dispatched on object destruction if not already dispatched. ```php use Masmerise\Toaster\PendingToast; use Masmerise\Toaster\Toaster; // Via Toaster facade Toaster::toast() ->message('Operation complete') ->success(); // Direct PendingToast construction with conditional logic PendingToast::create() ->when( $user->isAdmin(), fn (PendingToast $t) => $t->message('Admin account created'), fn (PendingToast $t) => $t->message('User account created'), ) ->success(); // Conditional error with unless() PendingToast::create() ->unless( $payment->wasSuccessful(), fn (PendingToast $t) => $t->message('Payment failed. Try again.')->error() ); ``` ``` -------------------------------- ### Toaster Facade - Multiple Toasts Source: https://context7.com/masmerise/livewire-toaster/llms.txt Illustrates dispatching multiple toast notifications within a single request. ```APIDOC ## Toaster Facade - Multiple Toasts ### Description Dispatch multiple toast notifications sequentially within a single request. They will be displayed in the order they are dispatched. ### Method `Toaster::[type](message)` ### Parameters - **type** (string) - The type of toast to display (e.g., `success`, `error`, `info`, `warning`). - **message** (string) - The content of the toast notification. ### Request Example ```php use Masmerise\Toaster\Toaster; Toaster::info('Step 1 complete.'); Toaster::info('Step 2 complete.'); Toaster::success('All steps finished!'); ``` ``` -------------------------------- ### Dispatch Toasts with Toaster Facade Source: https://context7.com/masmerise/livewire-toaster/llms.txt Use the `Toaster` facade to dispatch success, error, info, or warning toasts. Supports automatic translation key resolution. ```php use Masmerise\Toaster\Toaster; // Simple typed dispatches Toaster::success('User registered successfully!'); Toaster::error('Something went wrong.'); Toaster::info('Your session will expire soon.'); Toaster::warning('Disk usage is above 90%.'); // With automatic translation key resolution (requires translate => true in config) Toaster::success('auth.registered', ['name' => $user->name]); // Resolves: __('auth.registered', ['name' => 'Alice']) → "Welcome, Alice!" // Multiple toasts dispatched in a single request Toaster::info('Step 1 complete.'); Toaster::info('Step 2 complete.'); Toaster::success('All steps finished!'); ``` -------------------------------- ### Publish Toaster Views for Customization Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Publish Toaster's views using the `vendor:publish` Artisan command to customize the appearance of toasts. The `hub.blade.php` view will be available in `resources/views/vendor/toaster`. ```bash php artisan vendor:publish --tag=toaster-views ``` -------------------------------- ### Send Success Toast with Toaster Facade Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Use the Toaster facade to dispatch a success toast message from your backend Livewire component. This is the standard recommended method. ```php use Masmerise\Toaster\Toaster; final class RegistrationForm extends Component { public function submit(): void { $this->validate(); User::create($this->form); Toaster::success('User created!'); // 👈 } } ``` -------------------------------- ### RTL Support Configuration Source: https://context7.com/masmerise/livewire-toaster/llms.txt Enable right-to-left layout by setting the `dir="rtl"` attribute on the HTML root element. The toaster automatically adjusts alignment and positioning using Tailwind's `rtl:` variants. ```html ... ... ``` -------------------------------- ### Livewire Toaster Configuration File Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md This is the default configuration file for Livewire Toaster. It allows you to control various aspects of toast notifications, such as accessibility, alignment, duration, and more. ```php return [ /** * Add an additional second for every 100th word of the toast messages. * * Supported: true | false */ 'accessibility' => true, /** * The vertical alignment of the toast container. * * Supported: "bottom", "middle" or "top" */ 'alignment' => 'bottom', /** * Allow users to close toast messages prematurely. * * Supported: true | false */ 'closeable' => true, /** * The on-screen duration of each toast. * * Minimum: 3000 (in milliseconds) */ 'duration' => 3000, /** * The horizontal position of each toast. * * Supported: "center", "left" or "right" */ 'position' => 'right', /** * New toasts immediately replace similar ones, ensuring only one toast of a kind is visible at any time. * Takes precedence over the "suppress" option. * * Supported: true | false */ 'replace' => false, /** * Prevent the display of duplicate toast messages. * * Supported: true | false */ 'suppress' => false, /** * Whether messages passed as translation keys should be translated automatically. * * Supported: true | false */ 'translate' => true, ]; ``` -------------------------------- ### Dispatch Toasts from Front-end with Toaster Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Invoke the globally available `Toaster` instance from HTML to dispatch toast messages. Available methods include `error`, `info`, `warning`, and `success`. ```html ``` -------------------------------- ### Activate Toaster Frontend Hub Source: https://context7.com/masmerise/livewire-toaster/llms.txt Import the toaster JavaScript in your `app.js` to activate the front-end hub for handling toast notifications. ```javascript // resources/js/app.js — import Toaster to activate the front-end hub import './bootstrap'; import '../../vendor/masmerise/livewire-toaster/resources/js'; ``` -------------------------------- ### Dispatch Toasts from a Toastable Class Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Make a class Toastable by using the Toastable trait to dispatch toast messages directly from its methods, such as warnings. ```php use Masmerise\Toaster\Toastable; final class ProductListing extends Component { use Toastable; // 👈 public function check(): void { $result = Product::query() ->tap(new Available()) ->count(); if ($result < 5) { $this->warning('The quantity on hand is critically low.'); // 👈 } } } ``` -------------------------------- ### Import Toaster in app.js Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Import the Toaster JavaScript bundle at the top of your resources/js/app.js file to enable toast notifications. ```javascript import './bootstrap'; import '../../vendor/masmerise/livewire-toaster/resources/js'; // 👈 // other app stuff... ``` -------------------------------- ### Chain Toasts onto Redirects using Redirect Macros Source: https://context7.com/masmerise/livewire-toaster/llms.txt Utilize the Toaster package's redirect macros to chain toast notifications directly onto `RedirectResponse` and `Redirector` instances. This allows toasts to be displayed after a redirect, commonly used in standard controllers. ```php use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; final class CompanyController extends Controller { public function store(Request $request): RedirectResponse { $data = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:companies', ]); Company::create($data); return redirect()->route('companies.index') ->success('Company created successfully!'); } public function destroy(Company $company): RedirectResponse { $company->delete(); return redirect()->back() ->warning('Company "' . $company->name . '" was deleted.'); } public function update(Request $request, Company $company): RedirectResponse { if ($request->isNotFilled('name')) { return redirect()->back() ->error('Name field is required.'); } $company->update($request->only('name')); return redirect()->route('companies.show', $company) ->info('Company details updated.'); } } ``` -------------------------------- ### Compose Toasts with Toaster::toast() and PendingToast Source: https://context7.com/masmerise/livewire-toaster/llms.txt Use `Toaster::toast()` or `PendingToast::create()` for fine-grained, conditional toast composition. The toast is dispatched automatically on object destruction if not already sent. Conditional logic can be applied using `when()` and `unless()` methods. ```php use Masmerise\Toaster\PendingToast; use Masmerise\Toaster\Toaster; // Via Toaster facade Toaster::toast() ->message('Operation complete') ->success(); // Direct PendingToast construction with conditional logic PendingToast::create() ->when( $user->isAdmin(), fn (PendingToast $t) => $t->message('Admin account created'), fn (PendingToast $t) => $t->message('User account created'), ) ->success(); // Conditional error with unless() PendingToast::create() ->unless( $payment->wasSuccessful(), fn (PendingToast $t) => $t->message('Payment failed. Try again.')->error() ); ``` -------------------------------- ### Redirect Macros Source: https://context7.com/masmerise/livewire-toaster/llms.txt Toaster provides macros for `RedirectResponse` and `Redirector`, enabling you to chain toast messages directly onto any redirect, including those from standard controllers. ```APIDOC ## Redirect Macros — `RedirectResponse` / `Redirector` Toaster mixes toast methods directly onto `RedirectResponse` and `Redirector` so toasts can be chained onto any redirect, including from standard controllers. ```php use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; final class CompanyController extends Controller { public function store(Request $request): RedirectResponse { $data = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:companies', ]); Company::create($data); return redirect()->route('companies.index') ->success('Company created successfully!'); } public function destroy(Company $company): RedirectResponse { $company->delete(); return redirect()->back() ->warning('Company "' . $company->name . '" was deleted.'); } public function update(Request $request, Company $company): RedirectResponse { if ($request->isNotFilled('name')) { return redirect()->back() ->error('Name field is required.'); } $company->update($request->only('name')); return redirect()->route('companies.show', $company) ->info('Company details updated.'); } } ``` ``` -------------------------------- ### Adjust Toaster Import in app.js Source: https://github.com/masmerise/livewire-toaster/blob/master/UPGRADING.md Update your app.js to reflect changes in Alpine.js and Toaster registration. Alpine.js is now registered automatically by Livewire, so direct calls to Alpine.plugin or Alpine.start should be removed. ```diff import './bootstrap'; + import '../../vendor/masmerise/livewire-toaster/resources/js'; - import Alpine from 'alpinejs'; - import Toaster from '../../vendor/masmerise/livewire-toaster/resources/js'; - Alpine.plugin(Toaster); - window.Alpine = Alpine; - Alpine.start(); ``` -------------------------------- ### Enable RTL Support Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Add the `dir="rtl"` attribute to the `` tag in your HTML document to enable Right-To-Left support for UI elements and text alignment. ```html ... ``` -------------------------------- ### Extend Collector Behavior for Daily Counting Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Create a custom `Collector` implementation to extend Toaster's behavior, such as tracking daily toast dispatches. This involves implementing the `collect` and `release` methods. ```php final readonly class DailyCountingCollector implements Collector { public function __construct(private Collector $next) {} public function collect(Toast $toast): void { // increment the counter on durable storage $this->next->collect($toast); } public function release(): array { return $this->next->release(); } } ``` -------------------------------- ### Integrate Toasts into Livewire Components with Toastable Trait Source: https://context7.com/masmerise/livewire-toaster/llms.txt Mix the `Toastable` trait into your Livewire components to directly use toast dispatch methods like `success()`, `info()`, `warning()`, and `error()` without needing to reference the facade explicitly. This simplifies toast notifications within component logic. ```php use Masmerise\Toaster\Toastable; use Livewire\Component; final class OrderForm extends Component { use Toastable; // adds error(), info(), success(), warning(), toast() public function submit(): void { $this->validate(); $order = Order::create($this->form); if ($order->requiresApproval()) { $this->info('Your order is pending approval.'); } else { $this->success('Order placed successfully!'); } } public function cancel(Order $order): void { $order->cancel(); $this->warning('Order #' . $order->id . ' has been cancelled.'); } } ``` -------------------------------- ### Include Toaster Hub Component in Template Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Add the `` component to your master template to enable toast notifications. This component should be placed before the closing `` tag. ```html ``` -------------------------------- ### Chain Toaster Methods on Redirects Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Chain Toaster methods like `error` or `info` directly onto a RedirectResponse to dispatch toast messages upon redirection. ```php final class CompanyController extends Controller { /** @throws ValidationException */ public function store(Request $request): RedirectResponse { $validator = Validator::make($request->all(), [...]); if ($validator->fails()) { return Redirect::back() ->error('The form contains several errors'); // 👈 } Company::create($validator->validate()); return Redirect::route('dashboard') ->info('Company created!'); // 👈 } } ``` -------------------------------- ### Front-end JavaScript Toaster Methods Source: https://context7.com/masmerise/livewire-toaster/llms.txt Use these methods to display success, error, info, or warning toasts from your JavaScript. The duration is controlled by the configuration default. ```javascript // Available front-end methods (no duration parameter — uses config default) Toaster.success('Operation successful'); Toaster.error('An error occurred'); Toaster.info('Did you know?'); Toaster.warning('Proceed with caution'); ``` -------------------------------- ### ToastBuilder - Low-level Builder API Source: https://context7.com/masmerise/livewire-toaster/llms.txt The `ToastBuilder` provides an immutable value-object builder for manually constructing `Toast` instances. This is particularly useful for service classes and event listeners that receive the `Collector` via dependency injection. ```APIDOC ## `ToastBuilder` — Low-level Builder API An immutable value-object builder for constructing `Toast` instances manually, useful for service classes and event listeners that receive the `Collector` via dependency injection. ```php use Masmerise\Toaster\Collector; use Masmerise\Toaster\ToastBuilder; use Masmerise\Toaster\ToasterConfig; final readonly class SendWelcomeNotification { public function __construct( private Collector $toasts, private ToasterConfig $config, ) {} public function handle(UserRegistered $event): void { $toast = ToastBuilder::create() ->duration($this->config->duration) // int milliseconds ->message("Welcome, {$event->user->name}!") ->success() // sets type to "success" ->get(); // returns Toast value object $this->toasts->collect($toast); } } // Register listener in EventServiceProvider protected $listen = [ UserRegistered::class => [SendWelcomeNotification::class], ]; ``` ``` -------------------------------- ### Build Toasts Manually with ToastBuilder API Source: https://context7.com/masmerise/livewire-toaster/llms.txt The `ToastBuilder` provides an immutable API for constructing `Toast` instances manually. This is particularly useful in service classes or event listeners where you might receive a `Collector` via dependency injection and need to create a toast programmatically. ```php use Masmerise\Toaster\Collector; use Masmerise\Toaster\ToastBuilder; use Masmerise\Toaster\ToasterConfig; final readonly class SendWelcomeNotification { public function __construct( private Collector $toasts, private ToasterConfig $config, ) {} public function handle(UserRegistered $event): void { $toast = ToastBuilder::create() ->duration($this->config->duration) // int milliseconds ->message("Welcome, {$event->user->name}!") ->success() // sets type to "success" ->get(); // returns Toast value object $this->toasts->collect($toast); } } // Register listener in EventServiceProvider protected $listen = [ UserRegistered::class => [SendWelcomeNotification::class], ]; ``` -------------------------------- ### Configure Tailwind CSS for Toaster (v<4) Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Register the Toaster view path with Tailwind's purge list in your tailwind.config.js file for versions prior to v4.x. ```javascript module.exports = { content: [ './resources/**/*.blade.php', './vendor/masmerise/livewire-toaster/resources/views/*.blade.php', // 👈 ], } ``` -------------------------------- ### Unit Testing Toaster Dispatches Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Use `Toaster::fake()` to mock the toaster instance during unit tests. Assert that specific messages have been dispatched or that nothing has been dispatched. ```php use Masmerise\Toaster\Toaster; final class RegisterUserControllerTest extends TestCase { #[Test] public function users_can_register(): void { // Arrange Toaster::fake(); Toaster::assertNothingDispatched(); // Act $response = $this->post('users', [ ... ]); // Assert $response->assertRedirect('profile'); Toaster::assertDispatched('Welcome!'); } } ``` -------------------------------- ### Configure Tailwind CSS Content Path (v4+ fallback) Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Alternatively, for Tailwind CSS v4+, you can add the Toaster view path to the content array in your tailwind.config.js file. ```javascript /** @type {import('tailwindcss').Config} */ export default { content: [ "./resources/**/*.blade.php", "./resources/**/*.js", "./resources/**/*.vue", "./vendor/masmerise/livewire-toaster/resources/views/*.blade.php", // 👈 ], plugins: [], }; ``` -------------------------------- ### Configure Tailwind CSS for Toaster Views Source: https://context7.com/masmerise/livewire-toaster/llms.txt Register Toaster's views with Tailwind's content scan to prevent utility classes from being purged. ```javascript // tailwind.config.js (Tailwind < v4) module.exports = { content: [ './resources/**/*.blade.php', './vendor/masmerise/livewire-toaster/resources/views/*.blade.php', // required ], }; ``` ```css /* app.css (Tailwind v4+) */ @import "tailwindcss"; @source '../../vendor/masmerise/livewire-toaster/resources/views/*.blade.php'; ``` -------------------------------- ### Inline Alpine.js Usage for Toasts Source: https://context7.com/masmerise/livewire-toaster/llms.txt Trigger success or error toasts directly from button clicks using Alpine.js event listeners. ```html ``` ```html
``` -------------------------------- ### Automatic Translation of Messages in Toaster Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Configure `translate` to `true` to use translation keys directly for toast messages. This simplifies localization compared to manually calling Laravel's `Lang::get`. ```php Toaster::success('path.to.translation', ['replacement' => 'value']); ``` ```php Toaster::info('user.created', ['name' => $user->full_name]); Toaster::info('You now have full access!'); ``` -------------------------------- ### Front-end JavaScript API Source: https://context7.com/masmerise/livewire-toaster/llms.txt The globally available `Toaster` object dispatches `toaster:received` DOM events. It provides methods to trigger success, error, info, and warning toasts directly from JavaScript. ```APIDOC ## Front-end JavaScript API — `window.Toaster` The globally available `Toaster` object dispatches `toaster:received` DOM events consumed by the Alpine hub. Useful for triggering toasts from form submissions, Alpine components, or any custom JavaScript. ### Methods - `Toaster.success(message)`: Displays a success toast. - `Toaster.error(message)`: Displays an error toast. - `Toaster.info(message)`: Displays an informational toast. - `Toaster.warning(message)`: Displays a warning toast. *Note: The duration parameter is not available in the front-end API and uses the default configuration.* ``` -------------------------------- ### Toastable Trait Source: https://context7.com/masmerise/livewire-toaster/llms.txt The `Toastable` trait allows you to mix toast dispatch methods directly into your classes, typically Livewire components, eliminating the need to explicitly reference the facade. ```APIDOC ## `Toastable` Trait Mixes toast dispatch methods directly into any class (typically Livewire components), removing the need to reference the facade explicitly. ```php use Masmerise\Toaster\Toastable; use Livewire\Component; final class OrderForm extends Component { use Toastable; // adds error(), info(), success(), warning(), toast() public function submit(): void { $this->validate(); $order = Order::create($this->form); if ($order->requiresApproval()) { $this->info('Your order is pending approval.'); } else { $this->success('Order placed successfully!'); } } public function cancel(Order $order): void { $order->cancel(); $this->warning('Order #' . $order->id . ' has been cancelled.'); } } ``` ``` -------------------------------- ### Registering Extended Collector in AppServiceProvider Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Extend the `Collector` binding in `AppServiceProvider` to use your custom collector, like `DailyCountingCollector`, ensuring it wraps the original collector. ```php public function register(): void { $this->app->extend(Collector::class, static fn (Collector $next) => new DailyCountingCollector($next) ); } ``` -------------------------------- ### Inject Collector and Use ToastBuilder in PHP Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Inject the `Collector` contract and use `ToastBuilder` to dispatch toasts in a PHP class. This approach is useful for keeping logic pure and managing toasts programmatically. ```php use Masmerise\Toaster\Collector; use Masmerise\Toaster\ToasterConfig; use Masmerise\Toaster\ToastBuilder; final readonly class SendEmailVerifiedNotification { public function __construct( private ToasterConfig $config, private Collector $toasts, ) {} public function handle(Verified $event): void { $toast = ToastBuilder::create() ->duration($this->config->duration) ->success() ->message("Thank you, {$event->user->name}!") ->get(); $this->toasts->collect($toast); } } ``` -------------------------------- ### Send Conditional Toasts with PendingToast Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md Utilize the PendingToast class for fine-grained control over toast messages, allowing conditional dispatching based on logic within your component. ```php use Masmerise\Toaster\PendingToast; final class RegistrationForm extends Component { public function submit(): void { $this->validate(); $user = User::create($this->form); // 👇 PendingToast::create() ->when($user->isAdmin(), fn (PendingToast $toast) => $toast->message('Admin created') ) ->unless($user->isAdmin(), fn (PendingToast $toast) => $toast->message('User created') ) ->success(); } } ``` -------------------------------- ### Unit Testing with Toaster::fake() Source: https://context7.com/masmerise/livewire-toaster/llms.txt Use `Toaster::fake()` to replace the real collector with a testable version for assertions in PHPUnit tests. Assert that specific messages were dispatched or not dispatched. ```php use Masmerise\Toaster\Toaster; use PHPUnit\Framework\Attributes\Test; final class RegistrationTest extends TestCase { #[Test] public function successful_registration_dispatches_welcome_toast(): void { // Arrange Toaster::fake(); Toaster::assertNothingDispatched(); // Act $response = $this->post('/register', [ 'name' => 'Alice', 'email' => 'alice@example.com', 'password' => 'secret123', 'password_confirmation' => 'secret123', ]); // Assert $response->assertRedirect('/dashboard'); Toaster::assertDispatched('Welcome, Alice!'); } #[Test] public function validation_failure_does_not_dispatch_any_toast(): void { Toaster::fake(); $this->post('/register', ['email' => 'not-an-email']); Toaster::assertNothingDispatched(); } } ``` -------------------------------- ### Unit Testing with `Toaster::fake()` Source: https://context7.com/masmerise/livewire-toaster/llms.txt Use `Toaster::fake()` in your PHPUnit tests to replace the real `Collector` with a testable version. This allows you to assert that specific toast messages were dispatched or not dispatched. ```APIDOC ## `Toaster::fake()` — Unit Testing Replaces the real `Collector` binding with `TestableCollector` for PHPUnit-based assertions. Assert that specific messages were (or were not) dispatched during a test. ### Methods - `Toaster::fake()`: Replaces the real collector with a testable one. - `Toaster::assertDispatched(message)`: Asserts that a toast with the given message was dispatched. - `Toaster::assertNothingDispatched()`: Asserts that no toasts were dispatched. *Note: When `translate => true` is active, assert against the translation key (e.g., `'auth.welcome'`), not the resolved string, as translation does not run during unit tests.* ```php use Masmerise\Toaster\Toaster; use PHPUnit\Framework\Attributes\Test; final class RegistrationTest extends TestCase { #[Test] public function successful_registration_dispatches_welcome_toast(): void { // Arrange Toaster::fake(); Toaster::assertNothingDispatched(); // Act $response = $this->post('/register', [ 'name' => 'Alice', 'email' => 'alice@example.com', 'password' => 'secret123', 'password_confirmation' => 'secret123', ]); // Assert $response->assertRedirect('/dashboard'); Toaster::assertDispatched('Welcome, Alice!'); } #[Test] public function validation_failure_does_not_dispatch_any_toast(): void { Toaster::fake(); $this->post('/register', ['email' => 'not-an-email']); Toaster::assertNothingDispatched(); } } ``` ``` -------------------------------- ### Configure Tailwind CSS for Toaster (v>=4) Source: https://github.com/masmerise/livewire-toaster/blob/master/README.md For Tailwind CSS v4.0+, add the Toaster view path using the @source directive in your app.css file or in the tailwind.config.js file. ```css @import "tailwindcss"; ... @source '../../vendor/masmerise/livewire-toaster/resources/views/*.blade.php'; /* 👈 */ ``` -------------------------------- ### Extending Custom `Collector` Decorators Source: https://context7.com/masmerise/livewire-toaster/llms.txt The `Collector` interface supports the decorator pattern, allowing you to wrap the existing collector to intercept, transform, or augment toast collection without modifying the core. ```APIDOC ## Extending — Custom `Collector` Decorators The `Collector` interface follows the decorator pattern. Wrap the existing collector to intercept, transform, or augment toast collection without modifying the core. ```php use Masmerise\Toaster\Collector; use Masmerise\Toaster\Toast; // Custom decorator: log every dispatched toast to the database final readonly class AuditingCollector implements Collector { public function __construct(private Collector $next) {} public function collect(Toast $toast): void { ToastAudit::create([ 'message' => $toast->message->value, 'type' => $toast->type->value, 'created_at' => now(), ]); $this->next->collect($toast); // always forward to the inner collector } public function release(): array { return $this->next->release(); } } // Register in AppServiceProvider::register() use Masmerise\Toaster\Collector; public function register(): void { $this->app->extend( Collector::class, static fn (Collector $next) => new AuditingCollector($next) ); } ``` ``` -------------------------------- ### Toaster Hub Blade Component Source: https://context7.com/masmerise/livewire-toaster/llms.txt This is the main Blade component for the toaster hub. It uses Alpine.js for dynamic behavior and displays toasts based on their type and visibility. Ensure x-data, x-init, and x-for are present on the wrapper and template. ```blade {{-- resources/views/vendor/toaster/hub.blade.php --}} {{-- Available variables: $alignment, $closeable, $config, $position, $toasts --}}
{{-- x-data, x-init on the wrapper and x-for on the template are REQUIRED --}}
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.