Convert Figma logo to code with AI

mckenziearts logolaravel-notify

Flexible Flash notifications for Laravel

1,733
199
1,733
0

Top Related Projects

Log activity inside your Laravel app

Associate files with Eloquent models

Quick Overview

Laravel Notify is a package for Laravel that provides an easy way to add notifications to your web application. It offers a variety of notification types and styles, allowing developers to quickly implement attractive and informative notifications without extensive custom styling or JavaScript.

Pros

  • Easy integration with Laravel projects
  • Multiple notification types (success, error, info, warning)
  • Customizable styles and animations
  • Supports both session-based and JavaScript-based notifications

Cons

  • Limited to Laravel framework
  • May require additional styling for perfect integration with custom designs
  • Dependency on external CSS and JavaScript files
  • Limited advanced customization options compared to more complex notification libraries

Code Examples

  1. Basic usage:
notify()->success('Welcome to Laravel Notify!');

This code creates a simple success notification.

  1. Custom notification with title:
notify()->preset('custom-preset')
         ->title('Custom Notification')
         ->message('This is a custom notification message.');

This example demonstrates creating a custom notification with a title and message.

  1. JavaScript-based notification:
$notify = notify()->success('This notification was sent from JavaScript!')->toJsObject();

This code prepares a notification to be triggered via JavaScript.

Getting Started

  1. Install the package via Composer:

    composer require mckenziearts/laravel-notify
    
  2. Publish the package assets:

    php artisan vendor:publish --provider="Mckenziearts\Notify\LaravelNotifyServiceProvider"
    
  3. Include the styles and scripts in your layout file:

    <!DOCTYPE html>
    <html>
    <head>
        @notifyCss
    </head>
    <body>
        @include('notify::components.notify')
        @notifyJs
    </body>
    </html>
    
  4. Use the notification in your controller or view:

    notify()->success('Laravel Notify is awesome!');
    

Competitor Comparisons

Log activity inside your Laravel app

Pros of Laravel Activity Log

  • Comprehensive activity logging system for Laravel applications
  • Highly customizable with support for multiple log models and custom attributes
  • Integrates well with Laravel's Eloquent ORM for easy querying and retrieval of logs

Cons of Laravel Activity Log

  • Focused solely on activity logging, lacking notification features
  • May require more setup and configuration compared to simpler notification systems
  • Potentially higher learning curve for developers new to activity logging concepts

Code Comparison

Laravel Activity Log:

activity()
   ->performedOn($article)
   ->causedBy($user)
   ->withProperties(['custom' => 'properties'])
   ->log('Article was updated');

Laravel Notify:

notify()->success('Laravel Notify is awesome!');
notify()->error('Oops! Something went wrong.');
notify()->info('This is a simple info notification.');

Summary

Laravel Activity Log is a robust solution for tracking and logging user activities within Laravel applications, offering extensive customization options. On the other hand, Laravel Notify focuses on providing a simple and elegant way to display notifications to users. While Activity Log excels in detailed activity tracking, Notify shines in its ease of use for quick user feedback. The choice between the two depends on whether the primary need is comprehensive activity logging or straightforward user notifications.

Associate files with Eloquent models

Pros of Laravel Media Library

  • Comprehensive media management with advanced features like file conversions and responsive images
  • Extensive documentation and community support
  • Seamless integration with Laravel's Eloquent ORM

Cons of Laravel Media Library

  • Steeper learning curve due to its extensive feature set
  • May be overkill for simple file upload needs
  • Requires more configuration and setup compared to simpler alternatives

Code Comparison

Laravel Media Library:

$model->addMedia($pathToFile)->toMediaCollection('images');
$model->getMedia('images')->first()->getUrl('thumb');

Laravel Notify:

notify()->success('Laravel Notify is awesome!');
notify()->error('Oops! Something went wrong.');

Summary

Laravel Media Library is a powerful media management solution for Laravel applications, offering advanced features and seamless integration with Eloquent. It's ideal for projects requiring complex media handling but may be excessive for simpler needs.

Laravel Notify, on the other hand, focuses on providing an easy-to-use notification system for Laravel applications. It's more lightweight and straightforward to implement, making it suitable for projects that primarily need user notifications rather than comprehensive media management.

Choose Laravel Media Library for robust media handling capabilities, and Laravel Notify for quick and simple user notifications in your Laravel projects.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Laravel Notify Banner

Build Status Coding Standards Total Downloads Latest Stable Version License

Introduction

Laravel Notify is a lightweight Laravel package for displaying backend-driven notifications in your application.

Installation

You can install the package using composer

composer require mckenziearts/laravel-notify

You can publish the configuration file and assets by running:

php artisan vendor:publish --tag=notify-assets
php artisan vendor:publish --tag=notify-config

Option 1: With Tailwind CSS & Alpinejs

If your project already uses Tailwind CSS 4.x, follow these steps to integrate Laravel Notify directly into your build process.

Step 1: Configure Tailwind to scan package files

In your resources/css/app.css, add the package's Blade files to Tailwind's content sources using the @source directive:

@import "tailwindcss";

@source "../../vendor/mckenziearts/laravel-notify/resources/views/**/*.blade.php";

Step 2: Import the JavaScript

In your resources/js/app.js, import Alpine.js if you haven't already:

import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start()

Step 3: Add the notification component to your layout

In your main Blade layout file (e.g., resources/views/layouts/app.blade.php):

<!-- Add notification component before closing body tag -->
<x-notify::notify />

Step 4: Build your assets

npm run build
# or for development
npm run dev

✅ Done! Tailwind will automatically generate CSS for all the notification styles used in the package.

Option 2: Without Tailwind CSS

If you don't use Tailwind CSS in your project, you can use the pre-compiled CSS and JavaScript files.

Add directives to your layout

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Notify</title>

    <!-- Add Laravel Notify CSS -->
    @notifyCss
</head>
<body>

    <!-- Add notification component -->
    <x-notify::notify />

    <!-- Add Laravel Notify JavaScript -->
    @notifyJs
</body>
</html>

✅ Done! The pre-compiled assets will be loaded from your public/vendor/mckenziearts/laravel-notify/dist/ directory.

Usage

Within your controllers, before you perform a redirect call the notify method with a title.

public function store()
{
    notify()
        ->success()
        ->title('⚡️ Laravel Notify is awesome!')
        ->send();

    return back();
}

Type of notifications

Laravel Notify actually display 5 types of notifications

  1. toast notification, (The default notification for Laravel Notify)
notify()
    ->success()
    ->title('Welcome to Laravel Notify ⚡️')
    ->send();
  1. connectify notification, example of basic usage
notify()
    ->model(NotificationModel::Connect)
    ->success()
    ->title('Connection Found')
    ->message('Success Message Here')
    ->send();
  1. drakify (😎) notification, displays an alert only
// For success alert
notify()
    ->model(NotificationModel::Drake)
    ->success()
    ->send();
// or
notify()
    ->model(NotificationModel::Drake)
    ->error()
    ->send(); // for error alert
  1. smiley notification, displays a simple custom toast notification using the smiley (😊) emoticon
notify()
    ->model(NotificationModel::Smiley)
    ->success()
    ->title('You are successfully reconnected')
    ->send();
  1. emotify notification, displays a simple custom toast notification using a vector emoticon
notify()
    ->model(NotificationModel::Emotify)
    ->success()
    ->title('You are awesome, your data was successfully created')
    ->send();

Setting a duration

By default, notifications are shown for 5 seconds before they're automatically closed. You may customize this using the duration() method:

notify()
    ->success()
    ->title('Saved successfully')
    ->duration(3000) // 3 seconds
    ->send();

If you'd like to make a notification stay open until the user manually closes it, you can set a very long duration:

notify()
    ->warning()
    ->title('Important notice')
    ->duration(999999) // ~16 minutes
    ->send();

You can also configure a default duration for all notifications in the config/notify.php file:

'timeout' => env('NOTIFY_TIMEOUT', 5000),

Adding Actions to Notifications

You can add interactive actions to your notifications, allowing users to perform tasks directly from the notification. Actions support both navigation (redirecting to a URL) and execution (calling a controller action).

Note: Actions are supported only for the following notification models: Toast, Connect, Smiley, and Emotify. The Drake model does not support actions.

Basic Usage

use Mckenziearts\Notify\Action\NotifyAction;

notify()
    ->success()
    ->title('User deleted successfully')
    ->actions([
        NotifyAction::make()
            ->label('Undo')
            ->action(route('users.restore', $user->id)),
        NotifyAction::make()
            ->label('View All')
            ->url(route('users.index')),
    ])
    ->send();

URL Actions (Navigation)

Use the url() method to redirect users to another page. This creates a simple link (GET request):

NotifyAction::make()
    ->label('View details')
    ->url(route('users.show', $user->id));

You can open URLs in a new tab using the openUrlInNewTab() method:

NotifyAction::make()
    ->label('Read documentation')
    ->url('https://laravel.com/docs')
    ->openUrlInNewTab();

Action Actions (Execution)

Use the action() method to execute a controller action. This sends an HTTP request (POST by default) to your controller:

NotifyAction::make()
    ->label('Restore')
    ->action(route('users.restore', $user->id));

You can specify the HTTP method using the method() method:

// DELETE request
NotifyAction::make()
    ->label('Delete permanently')
    ->action(route('users.force-delete', $user->id))
    ->method('DELETE');

// PUT request
NotifyAction::make()
    ->label('Update status')
    ->action(route('users.activate', $user->id))
    ->method('PUT');

If you don't specify a method, it defaults to POST.

Complete Example

public function destroy(User $user)
{
    $user->delete();

    notify()
        ->success()
        ->title('User deleted')
        ->message('The user has been moved to trash')
        ->actions([
            NotifyAction::make()
                ->label('Undo')
                ->action(route('users.restore', $user->id))
                ->method('POST'),
            NotifyAction::make()
                ->label('View Trash')
                ->url(route('users.trash'))
                ->openUrlInNewTab(),
        ])
        ->send();

    return redirect()->route('users.index');
}

Custom Styling

You can customize the appearance of action buttons using the classes() method:

NotifyAction::make()
    ->label('Delete')
    ->action(route('users.delete', $user->id))
    ->method('DELETE')
    ->classes('text-red-600 hover:text-red-500 font-bold');

Important Notes

  • Mutual Exclusivity: You cannot use both action() and url() on the same action. Choose one or the other.
  • Method Restriction: The method() function can only be used with action(). Using it with url() will throw an exception.
  • New Tab Restriction: The openUrlInNewTab() function can only be used with url(). Using it with action() will throw an exception.
  • Auto-close: When an action is executed successfully, the notification automatically closes.
  • CSRF Protection: Action requests automatically include CSRF tokens and proper headers.
  • Supported Models: Actions work with Toast, Connect, Smiley, and Emotify notification models only.

Preset Notifications

If you have a specific notification that is used across multiple different places in your system, you can define it as a preset notification in your config file. This makes it easier to maintain commonly used notifications in one place. Read how to define preset messages in the Config section below.

As an example, to use a preset notification you have defined called 'common-notification', use the following:

notify()->preset('common-notification')->send();

You can override any of the values that are set in the config if you need to. For example, this could be useful if you have a common notification across, but you want to change the icon in one particular place that it's used without having to manually write out a new notification.

To do this, simply pass in an array that has the key of the attribute that you want to override and the value you want to override it with.

As an example, we could override the 'title' of our 'common-notification' by using the following:

notify()->preset('common-notification', ['title' => 'This is the overridden title'])->send();

Config

Config file are located at config/notify.php after publishing NotifyServiceProvider. You can define preset notifications in the config file using the following structure:

use Mckenziearts\Notify\Enums\NotificationType;
use Mckenziearts\Notify\Enums\NotificationModel;

'preset-messages' => [
    'user-updated' => [
        'type'    => NotificationType::Success,
        'model'   => NotificationModel::Toast,
        'title'   => 'User Updated',
        'message' => 'The user has been updated successfully.',
    ],
    'user-deleted' => [
        'type'    => NotificationType::Success,
        'model'   => NotificationModel::Toast,
        'title'   => 'User Deleted',
        'message' => 'The user has been deleted successfully.',
    ],
],

The example above shows the config for two preset notifications: 'user-updated' and 'user-deleted'.

Credits