> ## Documentation Index
> Fetch the complete documentation index at: https://veekthoven-laravel-inertia-toast-24-61.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Toaster class

> The core Toaster class that manages toast notifications in Laravel Inertia Toast

The `Toaster` class is the core service that manages toast notifications. It's bound to the Laravel service container and is accessed through the `Toast` facade or the `toast()` helper function.

## Class overview

```php theme={null}
namespace InertiaToast;

class Toaster
{
    protected array $pending = [];
    
    // Public methods documented below
}
```

## Public methods

### success()

Add a success toast notification.

```php theme={null}
public function success(
    string $message,
    ?string $title = null,
    ?int $duration = null
): static
```

<ParamField path="message" type="string" required>
  The success message to display.
</ParamField>

<ParamField path="title" type="string | null" default="null">
  An optional title for the toast.
</ParamField>

<ParamField path="duration" type="int | null" default="null">
  Duration in milliseconds. If not provided, uses the default from configuration.
</ParamField>

**Returns:** The `Toaster` instance for method chaining

**Example:**

```php theme={null}
$toaster = app(Toaster::class);
$toaster->success('Operation completed');
$toaster->success('User created', 'Success', 5000);
```

### error()

Add an error toast notification.

```php theme={null}
public function error(
    string $message,
    ?string $title = null,
    ?int $duration = null
): static
```

<ParamField path="message" type="string" required>
  The error message to display.
</ParamField>

<ParamField path="title" type="string | null" default="null">
  An optional title for the toast.
</ParamField>

<ParamField path="duration" type="int | null" default="null">
  Duration in milliseconds. If not provided, uses the default from configuration.
</ParamField>

**Returns:** The `Toaster` instance for method chaining

**Example:**

```php theme={null}
$toaster->error('Something went wrong');
$toaster->error('Failed to save', 'Error', 7000);
```

### info()

Add an informational toast notification.

```php theme={null}
public function info(
    string $message,
    ?string $title = null,
    ?int $duration = null
): static
```

<ParamField path="message" type="string" required>
  The informational message to display.
</ParamField>

<ParamField path="title" type="string | null" default="null">
  An optional title for the toast.
</ParamField>

<ParamField path="duration" type="int | null" default="null">
  Duration in milliseconds. If not provided, uses the default from configuration.
</ParamField>

**Returns:** The `Toaster` instance for method chaining

**Example:**

```php theme={null}
$toaster->info('Please check your email');
$toaster->info('New updates available', 'Notice', 6000);
```

### warning()

Add a warning toast notification.

```php theme={null}
public function warning(
    string $message,
    ?string $title = null,
    ?int $duration = null
): static
```

<ParamField path="message" type="string" required>
  The warning message to display.
</ParamField>

<ParamField path="title" type="string | null" default="null">
  An optional title for the toast.
</ParamField>

<ParamField path="duration" type="int | null" default="null">
  Duration in milliseconds. If not provided, uses the default from configuration.
</ParamField>

**Returns:** The `Toaster` instance for method chaining

**Example:**

```php theme={null}
$toaster->warning('This cannot be undone');
$toaster->warning('Low disk space', 'Warning', 8000);
```

### add()

Add a toast notification with a specific level.

```php theme={null}
public function add(
    string $message,
    ToastLevel $level = ToastLevel::Info,
    ?string $title = null,
    ?int $duration = null
): static
```

<ParamField path="message" type="string" required>
  The message to display in the toast notification.
</ParamField>

<ParamField path="level" type="ToastLevel" default="ToastLevel::Info">
  The level/type of the toast. One of: `ToastLevel::Success`, `ToastLevel::Error`, `ToastLevel::Info`, or `ToastLevel::Warning`.
</ParamField>

<ParamField path="title" type="string | null" default="null">
  An optional title for the toast.
</ParamField>

<ParamField path="duration" type="int | null" default="null">
  Duration in milliseconds. If not provided, uses the default from configuration.
</ParamField>

**Returns:** The `Toaster` instance for method chaining

**Example:**

```php theme={null}
use InertiaToast\Enums\ToastLevel;

$toaster->add('Custom notification', ToastLevel::Success);
$toaster->add('Alert message', ToastLevel::Warning, 'Alert', 5000);
```

### hasPending()

Check if there are pending toasts that have been added but not yet flashed.

```php theme={null}
public function hasPending(): bool
```

**Returns:** `bool` - `true` if there are pending toasts, `false` otherwise

**Example:**

```php theme={null}
if ($toaster->hasPending()) {
    // There are toasts queued for display
}
```

### getPending()

Get all pending toast messages. This method is primarily used for testing.

```php theme={null}
public function getPending(): array
```

**Returns:** `ToastMessage[]` - Array of pending toast messages

**Example:**

```php theme={null}
$pending = $toaster->getPending();
foreach ($pending as $toast) {
    echo $toast->message;
}
```

### getPropKey()

Get the Inertia prop key used for toast notifications.

```php theme={null}
public function getPropKey(): string
```

**Returns:** `string` - The prop key from configuration (default: `'toasts'`)

**Example:**

```php theme={null}
$key = $toaster->getPropKey(); // 'toasts'
```

## How it works

The `Toaster` class manages toast notifications through a simple workflow:

1. When you call a method like `success()`, `error()`, etc., it creates a new `ToastMessage` instance
2. The toast message is added to the internal `$pending` array
3. The toasts are immediately flashed to Inertia using `Inertia::flash()`
4. The toasts are available in your frontend Inertia props under the configured prop key

```php theme={null}
// Internal workflow
public function add(string $message, ToastLevel $level, ?string $title, ?int $duration): static
{
    // Create a new toast message
    $this->pending[] = new ToastMessage($message, $level, $title, $duration);
    
    // Flash to Inertia immediately
    Inertia::flash(
        $this->getPropKey(),
        array_map(fn (ToastMessage $t) => $t->toArray(), $this->pending),
    );
    
    return $this;
}
```

## ToastMessage class

Each toast is represented by a `ToastMessage` instance:

```php theme={null}
namespace InertiaToast;

use InertiaToast\Enums\ToastLevel;

class ToastMessage
{
    public function __construct(
        public readonly string $message,
        public readonly ToastLevel $level = ToastLevel::Info,
        public readonly ?string $title = null,
        public readonly ?int $duration = null,
    ) {}
}
```

### Properties

<ResponseField name="message" type="string" required>
  The toast message content.
</ResponseField>

<ResponseField name="level" type="ToastLevel" default="ToastLevel::Info">
  The toast level (Success, Error, Info, or Warning).
</ResponseField>

<ResponseField name="title" type="string | null" default="null">
  Optional title for the toast.
</ResponseField>

<ResponseField name="duration" type="int | null" default="null">
  Optional duration in milliseconds.
</ResponseField>

### toArray()

Convert the toast message to an array format for JSON serialization.

```php theme={null}
public function toArray(): array
```

**Returns:** Array with keys: `message`, `level`, `title`, `duration`

**Example output:**

```php theme={null}
[
    'message' => 'User created successfully',
    'level' => 'success',
    'title' => 'Success',
    'duration' => 5000,
]
```

## ToastLevel enum

The `ToastLevel` enum defines the available toast types:

```php theme={null}
namespace InertiaToast\Enums;

enum ToastLevel: string
{
    case Success = 'success';
    case Error = 'error';
    case Info = 'info';
    case Warning = 'warning';
}
```

## Method chaining

All toast methods return the `Toaster` instance, allowing for method chaining:

```php theme={null}
$toaster->success('First notification')
    ->info('Second notification')
    ->warning('Third notification');
```

## Service container binding

The `Toaster` class is bound to the Laravel service container as a singleton:

```php theme={null}
// Resolve from container
$toaster = app(Toaster::class);

// Or use dependency injection
class UserController extends Controller
{
    public function __construct(protected Toaster $toaster)
    {
    }
    
    public function store(Request $request)
    {
        $user = User::create($request->validated());
        
        $this->toaster->success('User created successfully');
        
        return redirect()->route('users.index');
    }
}
```

<Note>
  Most developers will use the `Toast` facade or `toast()` helper instead of interacting with the `Toaster` class directly. However, understanding the underlying class is useful for advanced use cases and testing.
</Note>

## Testing

The `Toaster` class provides methods useful for testing:

```php theme={null}
use InertiaToast\Toaster;

class UserControllerTest extends TestCase
{
    public function test_user_creation_shows_toast()
    {
        $toaster = app(Toaster::class);
        
        $this->post('/users', ['name' => 'John']);
        
        $this->assertTrue($toaster->hasPending());
        
        $pending = $toaster->getPending();
        $this->assertCount(1, $pending);
        $this->assertEquals('User created successfully', $pending[0]->message);
    }
}
```
