PHPackages                             laragear/alerts - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. laragear/alerts

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

laragear/alerts
===============

Set multiple alerts from your backend, render them in the frontend.

v5.0.0(2mo ago)401621MITPHPPHP ^8.3CI passing

Since Feb 16Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Laragear/Alerts)[ Packagist](https://packagist.org/packages/laragear/alerts)[ Fund](https://github.com/sponsors/DarkGhostHunter)[ Fund](https://paypal.me/darkghosthunter)[ RSS](/packages/laragear-alerts/feed)WikiDiscussions 5.x Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (24)Used By (0)

Alerts
======

[](#alerts)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c7eb56da7fc5a18dcc4e73902036eca2078e764d143151f76d68cc58bbd61e1c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c617261676561722f616c657274732e737667)](https://packagist.org/packages/laragear/alerts)[![Latest stable test run](https://github.com/Laragear/Alerts/workflows/Tests/badge.svg)](https://github.com/Laragear/Alerts/actions)[![Codecov coverage](https://camo.githubusercontent.com/773b6ed03a2e70c5f199c63b5838d6c18197bffcdd255b4a4a360bf9034e7eac/68747470733a2f2f636f6465636f762e696f2f67682f4c617261676561722f416c657274732f67726170682f62616467652e7376673f746f6b656e3d5536514258444b394251)](https://codecov.io/gh/Laragear/Alerts)[![Maintainability](https://camo.githubusercontent.com/9f1f703fcef05d4e87c25b0ff8c1816270de807f5ff07ff77787ac9481641ad4/68747470733a2f2f716c74792e73682f67682f4c617261676561722f70726f6a656374732f416c657274732f6d61696e7461696e6162696c6974792e737667)](https://qlty.sh/gh/Laragear/projects/Alerts)[![Sonarcloud Status](https://camo.githubusercontent.com/fb15693e136e48607238ac5389979e298d12b4219b765575eb1cc280878872d1/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d4c617261676561725f416c65727473266d65747269633d616c6572745f737461747573)](https://sonarcloud.io/dashboard?id=Laragear_Alerts)[![Laravel Octane Compatibility](https://camo.githubusercontent.com/70359a356da237cd29561bc5d0bb80baae775b5ff62f288ed324755382858342/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2532304f6374616e652d436f6d70617469626c652d737563636573733f7374796c653d666c6174266c6f676f3d6c61726176656c)](https://laravel.com/docs/10.x/octane#introduction)

Set multiple alerts from your backend, render them in the frontend with any HTML.

```
use App\Alerts\FluxCallout;

FluxCallout::push(['body' => 'This is awesome!']);
```

```

    This is awesome! 😍

```

Become a sponsor
----------------

[](#become-a-sponsor)

[![](.github/assets/support.png)](https://github.com/sponsors/DarkGhostHunter)

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can **[spread the word!](http://x.com/share?text=I%20am%20using%20this%20cool%20PHP%20package&url=https://github.com%2FLaragear%2FAlerts&hashtags=PHP,Laravel)**

Requirements
------------

[](#requirements)

- PHP 8.3 or later
- Laravel 12 or later

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require laragear/alerts
```

Creating Alerts
---------------

[](#creating-alerts)

Laragear Alerts allows pushing your own custom Alerts into any frontend, being Blade views, Livewire responses or Inertia applications.

This approach makes it compatible with any type of frontend you have: Flux UI, Vuetify, Flowbite, Nuxt UI, DaisyUI, TallStackUI, Wire UI, you name it!

First, create your own alert using the `alert:create` Artisan command with the name of your alert. For example, we will create one for [Flux UI Callouts](https://fluxui.dev/components/callout).

```
php artisan alert:create FluxCallout
```

You will receive a class with some common defaults inside the `app\Views\Alerts` directory, and a view at the `resources/views/alerts` using the name of the alert in `slug-case`.

```
namespace App\Views\Alerts;

use Laragear\Alerts\Alert;

class FluxCallout extends Alert
{
    /**
     * @inheritDoc
     */
    public function toHtml()
    {
        return view('alerts.flux-callout', $this->all());
    }
}
```

```

    {{ $body }}

```

Once your alert is created, you can start modifying to match your frontend.

### Adding methods

[](#adding-methods)

Alerts are simple classes, so you can add any method you see fit to make filling your Alert data more convenient.

For example, you may create a static method to create a "successful" Alert, or automatically escape data that may include user-generated content with the [`e()`](https://laravel.com/docs/strings#method-e) helper.

```
use Illuminate\Support\Str;

/**
 * Add actions to the Flux UI Callout.
 *
 * @return $this
 */
public function actions(array $actions): static
{
    return $this->set('actions', $actions);
}

/**
 * Create a successful Flux UI callout.
 *
 * @return $this
 */
public static function success(string $heading, string $text = '', string $icon = ''): static
{
    return static::push(array_filter([
        'heading' => $heading,
        'text' => e($text)
        'icon' => $icon ?: 'check'
    ]));
}
```

Important

When adding objects, consider some [serialization caveats](#serialization).

### Default values

[](#default-values)

If you need to create Alerts with a set of default values, use the `getDefaults()` method to return an array of these values. These will be copied into the Alert attributes when it is instanced.

```
/**
 * Returns an array of default values.
 */
protected function getDefaults(): array
{
    return [
        'color' => 'secondary',
    ];
}
```

Pushing Alerts
--------------

[](#pushing-alerts)

Alerts are *pushed* to the frontend using the `push()` static method. After pushed, you can still modify the Alert, like adding a title, text, links or anything you want.

The `push()` accepts an array of raw attributes you can add to your Alert in one go, but you're not limited to that. If you defined convenience methods, you can also use them.

```
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Alerts\FluxCallout;
use App\Models\Invoice;

class InvoiceController extends Controller
{
    /**
     * Confirm the invoice payment.
     */
    public function confirm(Request $request, Invoice $invoice)
    {
        $invoice->markAsConfirmed();

        FluxCallout::push([
            'color' => 'green',
            'heading' => 'Invoice paid',
        ])->actions([
            ['label' => 'Follow order', 'href' => route('order.show', $invoice->order)]
        ]);

        return to_route('invoice.show', $invoice);
    }
}
```

You may also use the `pushToBag()` method after it has been instanced to move the Alert to the bag, especially if you use the `make()` static method to create instance. This is great to use when combined with conditional methods, like `when()`.

```
FluxCallout::make([
    'color' => 'green',
    'heading' => 'Invoice paid',
])->actions([
    ['label' => 'Follow order', 'href' => route('order.show', $invoice->order)]
])->when($invoice->isPaid())->pushToBag();
```

Note

The `make()` static method **doesn't add the alert to the bag**. It's just syntactic sugar for `new Alert()`.

### Localization

[](#localization)

Localization for your Alert is done at class-level. In other words, when you set a given string, you may use Laravel's `trans()` or `transChoice()` methods *inside* the class method to translate the string, instead of doing it outside, thus making it consistent across your application.

```
/**
 * Add a localized title.
 */
public function heading(...$arguments)
{
    return $this->set('heading', trans(...$arguments));
}
```

```
FluxCallout::push()->heading('payment.success');
```

### Conditions

[](#conditions)

You can also push an Alert if a condition evaluates to true or false by using `pushWhen()` and `pushUnless()`, respectively. Further method calls will be sent to the void.

```
use Illuminate\Support\Facades\Auth;
use App\Alerts\FluxCallout;

FluxCallout::pushWhen(Auth::check())
    ->heading('You are authenticated');

FluxCallout::pushUnless(Auth::user()->mailbox()->isNotEmpty())
    ->heading('You have messages in your inbox');
```

### Persistence

[](#persistence)

Alerts only last for the actual response being sent. On redirects, these are [flashed into the session](https://laravel.com/docs/session#flash-data) so these are available on the next request (the redirection target).

To make any alert persistent, you can use the `persistAs()` method with a key to identify the alert.

```
use App\Alerts\FluxCallout;

FluxCallout::push(['title' => 'Your disk size is almost full'])
    ->color('red')
    ->persistAs('disk.full');
```

Note

Setting a persistent alert replaces any previous set with the same key.

Once you're done, you can delete the persistent Alert using `abandon()` method directly from the helper using the key of the persisted Alert. For example, we can abandon the previous alert if the disk is no longer full.

```
use App\Alerts\FluxCallout;

if ($disk->notFull()) {
    FluxCallout::abandon('disk.full');
}
```

Rendering
---------

[](#rendering)

To render alerts in the frontend, use the `` Blade component which will take care of the magic, anywhere you want to put it.

```

    Welcome to my site

```

The component cycles through each alert and calls `toHtml()` to render them in your view. You're free to alter the `toHtml()` method of your alert with custom data.

```
public function toHtml()
{
    return view('alerts.flux-callout', [
        'heading' => $this->heading,
        'text' => $this->text,
        'actions' => $this->actions,
    ]);
}
```

The container view is set as `laragear::alerts.container`. You're free to change the container as you see fit for your application.

### Filter by class

[](#filter-by-class)

When using the [Alerts directive](#rendering), all the alerts will be rendered in the order these were instanced.

You can *filter* the alerts to be rendered using the `filter` attribute of the directive. Only matching FQN names of the classes alerts will be rendered.

```

```

Alerts as Notifications
-----------------------

[](#alerts-as-notifications)

If you're deep into Laravel Notifications, you can easily create notifications for your frontend, especially if these are broadcasted, using the Alert Channel.

Use the `Laragear\Alerts\AlertChannel` class as a channel, and the `toAlert()` method in your notification with an Alert instance.

```
use App\Alerts\FluxCallout;
use App\Models\Invoice;
use Laragear\Alerts\Alert;
use Laragear\Alerts\AlertChannel;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification
{
    /**
     * Create a new Invoice Paid instance.
     */
    public function __construct(protected Invoice $invoice)
    {
        //
    }

    /**
     * Get the notification channels.
     */
    public function via(object $notifiable): string
    {
        return AlertChannel::class;
    }

    /**
     * Get the alert representation of the notification.
     */
    public function toAlert(object $notifiable): Alert
    {
        return FluxCallout::make()
            ->title('InvoicePaid')
            ->text('You will receive a copy of the transaction in your email')
            ->actions(
                ['label' => 'Follow order', 'href' => route('orders.show', $this->invoice->order)],
                ['label' => 'See all orders', 'href' => route('orders.index')],
            );
    }
}
```

It's recommended to use `make()` instead of `push()` if you expect to test your notifications outside a request lifecycle.

Configuration
-------------

[](#configuration)

Alerts will work out-of-the-box with some common defaults, but if you need a better approach for your particular application, you can configure some parameters. First, publish the configuration file.

```
php artisan vendor:publish --provider="Laragear\Alerts\AlertsServiceProvider" --tag="config"
```

Let's examine the configuration array, which is quite simple:

```
return [
    'session' => true,
    'key' => '_alerts',
];
```

### Session

[](#session)

```
return [
    'session' => true,
];
```

When your application frontend is detached from the backend, like when using JavaScript or SPA, there is little to no benefit on storing the alerts into the session, especially when your alerts are meant to be ephemeral (like toasts). You will probably send them through your application JSON response [using the included middleware](#sending-json-alerts).

By disabling this with `false`, your session may be leaner since that logic is bypassed.

### Session Key

[](#session-key)

```
return [
    'key' => '_alerts',
];
```

When alerts are flashed or persisted, these are stored in the Session by a given key, which is `_alerts` by default. If you're using this key name for other things, you may want to change it.

This key is also used when [sending JSON alerts](#sending-json-alerts).

Serialization
-------------

[](#serialization)

Alerts implement the `__serialize()` and `__unserialize()` to only save its attributes and the persistence key. The rest of the class properties will not be serialized.

If you depend on custom serialization, like restoring object instances or other data, you may override the serialization methods to store a storable representation of your data. For example, when you have to deal with object instances like Container Services or Eloquent Models.

```
use App\Models\User;

protected User $user;

public function __serialize(): array
{
    return array_merge(parent::__serialize(), [
        'user' => $this->user->getKey(),
    ];
}

public function __unserialize(array $data): void
{
    parent::__unserialize($data);

    $this->user = User::findOrFail($data['user']);
}
```

### JSON

[](#json)

Alerts can be serialized into an array and a JSON string automatically, using `toArray()` and `toJson()`, respectively. This means you can send an Alert as a JSON response. By default, it will expose all its attributes.

```
{
    "heading": "Invoice paid",
    "text": "Follow your order in your dashboard.",
    "color": "green"
}
```

Note

If you want to alter how these are serialized, alter the `toArray()` or `toJson()` methods.

### Receiving JSON Alerts

[](#receiving-json-alerts)

Sometimes your application may receive a JSON Alert from an external service using this package. You can quickly add this JSON as an Alert to your application using the `fromJson()` method.

```
{
    "data" : {
        "items": "..."
    },
    "alerts": [
        {
            "heading": "Invoice paid",
            "text": "Follow your order in your dashboard.",
            "color": "green"
        }
    ]
}
```

```
use Illuminate\Http\Request;
use App\Alerts\FluxCallout;

public function fromServer(Request $request)
{
    // Add the alerts from the response
    $request->collect('alerts')->map(FluxCallout::push(...))
}
```

### Sending JSON Alerts

[](#sending-json-alerts)

This library has a convenient way to add Alerts into your JSON Responses. This can be invaluable to add your alerts to each response being sent to the browser, like combining this package with [Laravel Jetstream](https://jetstream.laravel.com/).

[Add the `alerts.json` middleware](https://laravel.com/docs/middleware#registering-middleware) into your `api` routes or, if you're using [Laravel Jetstream](https://jetstream.laravel.com/) or similar, as a [global middleware](https://laravel.com/docs/middleware#global-middleware).

When you return a `JsonResponse` to the browser, the middleware will append the alert as JSON using the same [session key](#session-key) defined in the configuration, which is `_alerts` by default. It also accepts the `key` parameter to use as an alternative, compatible with `dot.notation`.

```
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\UserController;

Route::prefix('api')
    ->middleware('alerts.json:_status.alerts')
    ->controller(UserController::class, function () {

        Route::post('user/create', 'create');
        Route::post('user/{user}/update', 'update');

    });
```

When you receive a JSON Response, you will see the alerts appended to whichever key you issued. Using the above example, we should see the `alerts` key under the `_status` key:

```
{
    "resource": "users",
    "url": "/v1/users",
    "_status": {
        "timestamp":  "2019-06-05T03:47:24Z",
        "action" : "created",
        "id": 648,
        "alerts": [
            {
                "heading": "Invoice paid",
                "text": "Follow your order in your dashboard.",
                "color": "green"
            }
        ]
    }
}
```

Warning

If your key is already present in the JSON response, **the key will be overwritten**.

#### Sending Alerts to Laravel Inertia

[](#sending-alerts-to-laravel-inertia)

If you're using Laravel Inertia, you may want to use the `alerts.inertia` middleware instead of the `alerts.json`. The middleware will add the alerts **only** to Inertia requests/responses, bypassing redirects.

```
use Illuminate\Support\Facades\Route;
use App\Models\User;
use Inertia\Inertia;
use Laragear\Alerts\Facades\Alert;

Route::middleware('alerts.inertia')
    ->get('users', function () {
        // Push an alert to the frontend.
        FluxCallout::make()
            ->title('All users accounted for!')
            ->color('red');

        return Inertia::render('users/index', [
            'users' => User::paginate()
        ]);
    });
```

Then, you can retrieve them in your frontend page as [shared data](https://inertiajs.com/shared-data#accessing-shared-data).

```

import { usePage } from '@inertiajs/vue3'

const page = usePage()

const alerts = page.props._alerts

```

Testing
-------

[](#testing)

To test if alerts were generated, you can use `fake()` from the `Alert` facade, which works like any other faked services. It returns a fake Alert Bag that holds a copy of all alerts generated, which exposes some convenient assertion methods.

```
use Laragear\Alerts\Facades\Alert;

public function test_alert_sent()
{
    $alert = Alert::fake();

    $this->post('/comment', ['body' => 'cool'])->assertOk();

    $alert->assertHasOne();
}
```

The following assertions are available:

MethodDescription`assertEmpty()`Check if the alert bag doesn't contains alerts.`assertNotEmpty()`Check if the alert bag contains any alert.`assertHasOne()`Check if the alert bag contains only one alert.`assertHas($count)`Check if the alert bag contains the exact amount of alerts.`assertHasPersistent()`Check if the alert bag contains at least one persistent alert.`assertHasNoPersistent()`Check if the alert bag doesn't contains a persistent alert.`assertPersistentCount()`Check if the alert bag contains the exact amount of persistent alerts.### Asserting specific alerts

[](#asserting-specific-alerts)

The fake Alert bag allows building conditions for the existence (or nonexistence) of alerts with specific properties, by using `assertAlert()`, followed by the `with()` method to build expectations. Once you build your expectations, you can use `exists()` to check if any alert matches, or `missing()` to check if no alert should match.

```
use Laragear\Alerts\Facades\Alert;

$bag = Alert::fake();

$bag->assertAlert()->with('heading', 'Hello world!')->exists();

$bag->assertAlert()->with(fn ($alert) => 'green' === $alert->color)->missing();
```

Note

Alternatively, you can use `count()` if you expect a specific number of alerts to match the given conditions, or `unique()` for matching only one alert.

Finally, to test if an alert is persisted or not, use the `persisted()` and `notPersisted()`, respectively.

```
use Laragear\Alerts\Facades\Alert;

$bag = Alert::fake();

$bag->assertAlert()->persisted()->count(2);
```

Laravel Octane compatibility
----------------------------

[](#laravel-octane-compatibility)

- The Bag is registered as singleton. **You shouldn't resolve it at boot time.**
- The Bag contains a stale version of the app config. **You shouldn't change the config.**
- There are no static properties written during a request.

There should be no problems using this package with Laravel Octane if you use this package as intended.

Security
--------

[](#security)

If you discover any security-related issues, please [use the online form](https://github.com/Laragear/Alerts/security).

License
=======

[](#license)

This specific package version is licensed under the terms of the [MIT License](LICENSE.md), at the time of publishing.

[Laravel](https://laravel.com) is a Trademark of [Taylor Otwell](https://github.com/TaylorOtwell/). Copyright © 2011–2026 Laravel LLC.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance88

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity74

Established project with proven stability

 Bus Factor1

Top contributor holds 93.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~88 days

Recently: every ~34 days

Total

18

Last Release

45d ago

Major Versions

1.x-dev → v2.0.02024-03-07

v2.0.1 → v3.0.02025-03-29

v2.1.0 → 3.x-dev2025-09-07

2.x-dev → v4.0.02025-11-14

v4.0.1 → v5.0.02026-03-04

PHP version history (6 changes)v1.0.0PHP ^8.0||^8.1

v1.0.1PHP ^8.0.2

v1.3.0PHP 8.\*

v2.0.0PHP ^8.1

v3.0.0PHP ^8.2

v5.0.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5141911?v=4)[Italo](/maintainers/DarkGhostHunter)[@DarkGhostHunter](https://github.com/DarkGhostHunter)

---

Top Contributors

[![DarkGhostHunter](https://avatars.githubusercontent.com/u/5141911?v=4)](https://github.com/DarkGhostHunter "DarkGhostHunter (128 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (8 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

alertslaravelnotificationsphplaravelnotificationssessionflashalerts

### Embed Badge

![Health badge](/badges/laragear-alerts/health.svg)

```
[![Health](https://phpackages.com/badges/laragear-alerts/health.svg)](https://phpackages.com/packages/laragear-alerts)
```

###  Alternatives

[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[edvinaskrucas/notification

Package for Laravel for helping to manage flash / instant notifications / messages.

520393.9k10](/packages/edvinaskrucas-notification)[prologue/alerts

Prologue Alerts is a package that handles global site messages.

3486.1M30](/packages/prologue-alerts)[devmarketer/laraflash

A powerful and flexible flash notifications system. Improving over built-in Laravel Flash messaging functionality.

6310.3k1](/packages/devmarketer-laraflash)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
