Laravel Broadcast Admin Notification

User
Notify admin to if anyone post a new post laravel broadcast
Assistant
To notify the admin when a new post is created in your Laravel application using broadcasting, follow these steps:

### 1. **Setup Laravel Broadcasting**
Ensure Laravel broadcasting is configured correctly:
1. Install Pusher or Redis (or any broadcasting driver you prefer).
2. Update the `.env` file with your broadcasting driver:

BROADCAST_DRIVER=pusher

3. Add the Pusher credentials or Redis configuration to your `.env` file.

### 2. **Create an Event**
Create an event for broadcasting when a new post is created:

php artisan make:event PostCreated

In the generated event class (`app/Events/PostCreated.php`), add the necessary properties and logic:

namespace AppEvents;

use AppModelsPost;
use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;

class PostCreated implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $post;

    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function broadcastOn()
    {
        return new Channel('admin-notifications');
    }

    public function broadcastAs()
    {
        return 'post.created';
    }
}

### 3. **Trigger the Event**
Trigger the `PostCreated` event in your `store` method in the controller where posts are created:

use AppEventsPostCreated;

public function store(Request $request)
{
    $post = Post::create($request->all());

    // Broadcast the event
    broadcast(new PostCreated($post));

    return response()->json(['message' => 'Post created successfully']);
}

### 4. **Set Up Frontend Listener**
In your admin dashboard (Vue.js), listen for the broadcast event. Make sure Laravel Echo is configured in your frontend.

#### Install Laravel Echo
Install Laravel Echo with Pusher:

yarn add laravel-echo pusher-js

#### Configure Echo
In your Vue.js app, add Echo to `resources/js/bootstrap.js` or your main JavaScript file:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
    forceTLS: true
});

#### Listen to the Event
In your Vue.js admin dashboard component:

mounted() {
    Echo.channel('admin-notifications')
        .listen('.post.created', (event) => {
            console.log('New post created:', event.post);
            // Show a notification or update UI
            alert(`New post created: ${event.post.title}`);
        });
}

### 5. **Broadcast Configuration**
Publish the broadcasting configuration:

php artisan vendor:publish --tag=laravel-broadcasting

Update `config/broadcasting.php` for Pusher or your preferred driver.

### 6. **Run Queue Worker**
If you're using queues, ensure the queue worker is running:

php artisan queue:work

Now, whenever a post is created, the `PostCreated` event will be broadcasted, and admins listening to the `admin-notifications` channel will receive real-time notifications!

User
admin using admin guard to login their section using different table
now I want add private chanel based on admin auth to view notification
Assistant
To implement a private channel for admin-specific notifications using a custom guard, follow these steps:

### 1. **Update Admin Authentication**
Make sure your custom `admin` guard is properly configured in `config/auth.php` and uses a separate `admins` table. For example:

'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => AppModelsAdmin::class,
    ],
],

### 2. **Create a Private Channel**
Private channels are authenticated for specific users (admins, in your case).

#### Define the Channel in `routes/channels.php`:
Add a route for the private channel:

use IlluminateSupportFacadesBroadcast;

Broadcast::channel('admin-notifications.{id}', function ($user, $id) {
    return $user->id === (int) $id && auth('admin')->check();
});

Here, `admin-notifications.{id}` is the private channel, and only the authenticated admin with a matching `id` can subscribe.

### 3. **Broadcast the Event**
Create an event that will be broadcasted to the private channel.

#### Generate the Event:

php artisan make:event AdminNotification

#### Update the Event:
In `AppEventsAdminNotification.php`:

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateQueueSerializesModels;

class AdminNotification implements ShouldBroadcast
{
    use SerializesModels;

    public $message;
    public $adminId;

    public function __construct($message, $adminId)
    {
        $this->message = $message;
        $this->adminId = $adminId;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('admin-notifications.' . $this->adminId);
    }

    public function broadcastAs()
    {
        return 'notification.received';
    }
}

### 4. **Trigger the Event**
Broadcast the event when a notification is created for an admin. For example, in your controller:

use AppEventsAdminNotification;

public function notifyAdmin(Request $request)
{
    $adminId = $request->admin_id; // ID of the admin to notify
    $message = "New post created";

    broadcast(new AdminNotification($message, $adminId));

    return response()->json(['message' => 'Notification sent to admin']);
}

### 5. **Authenticate Admin for the Private Channel**
Ensure that the custom `admin` guard is used for channel authentication. Update the broadcasting middleware in `app/Http/Kernel.php`:

protected $middlewareGroups = [
    'web' => [
        // Other middlewares...
        IlluminateSessionMiddlewareAuthenticateSession::class,
    ],
];

Additionally, in `AppProvidersBroadcastServiceProvider`, update the `authenticate` method to include the `admin` guard:

Broadcast::auth(function ($request) {
    return auth('admin')->user();
});

### 6. **Listen to the Private Channel (Frontend)**
In your admin dashboard (Vue.js or any frontend framework), configure Laravel Echo to listen for private channel events.

#### Update Laravel Echo Configuration:
Ensure Laravel Echo uses your `admin` guard for authentication. For example:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
    authEndpoint: '/broadcasting/auth', // Default auth endpoint
    auth: {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('admin_token')}`, // Use admin token if applicable
        },
    },
});

#### Listen to the Private Channel:
In your admin Vue.js component:

mounted() {
    Echo.private(`admin-notifications.${this.adminId}`)
        .listen('.notification.received', (event) => {
            console.log('Notification received:', event.message);
            // Display the notification (e.g., show a toast)
            alert(event.message);
        });
}

### 7. **Test the Private Channel**
1. Log in as an admin using the `admin` guard.
2. Trigger a notification for the admin (`/notifyAdmin` endpoint).
3. Verify that the notification is broadcasted to the specific admin's private channel and received in the frontend.

Now, only the authenticated admin will receive their specific notifications via the private channel! ๐ŸŽ‰

User
make private channel without admin id
Assistant
If you want to create a private channel without using the `admin id` and instead use a generic private channel for all authenticated admins, you can achieve this by using a **single private channel** based on the `admin` guard. Here's how to set it up:

### 1. **Define the Private Channel**
In `routes/channels.php`, define a private channel for all authenticated admins. Since we are not using the `admin id`, authentication will simply check if the user is authenticated via the `admin` guard.

use IlluminateSupportFacadesBroadcast;

Broadcast::channel('admin-notifications', function ($user) {
    return auth('admin')->check();
});

This will allow all authenticated admins to listen to the `admin-notifications` channel.

### 2. **Broadcast the Event**
You will need to create an event to broadcast notifications on this channel.

#### Generate the Event:

php artisan make:event AdminNotification

#### Update the Event:
In `AppEventsAdminNotification.php`, use a private channel named `admin-notifications`:

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateQueueSerializesModels;

class AdminNotification implements ShouldBroadcast
{
    use SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('admin-notifications');
    }

    public function broadcastAs()
    {
        return 'notification.received';
    }
}

Here, the `broadcastOn` method specifies the `admin-notifications` private channel.

### 3. **Trigger the Event**
Broadcast the event when you want to notify all authenticated admins. For example, in your controller:

use AppEventsAdminNotification;

public function notifyAdmins(Request $request)
{
    $message = "A new post has been created";

    broadcast(new AdminNotification($message));

    return response()->json(['message' => 'Notification sent to all admins']);
}

### 4. **Authenticate Admins for the Private Channel**
Ensure that the `admin` guard is used to authenticate access to the private channel. Update the `authenticate` method in `AppProvidersBroadcastServiceProvider`:

Broadcast::auth(function ($request) {
    return auth('admin')->user();
});

### 5. **Listen to the Private Channel (Frontend)**
In your Vue.js or frontend admin dashboard, configure Laravel Echo to listen for the private channel events.

#### Update Laravel Echo Configuration:
Make sure Laravel Echo is using your `admin` guard for authentication:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
    authEndpoint: '/broadcasting/auth', // Default Laravel auth endpoint
    auth: {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('admin_token')}`, // Use admin token if applicable
        },
    },
});

#### Listen to the Private Channel:
In your Vue.js admin dashboard component:

mounted() {
    Echo.private('admin-notifications')
        .listen('.notification.received', (event) => {
            console.log('Notification received:', event.message);
            // Display the notification (e.g., show a toast or update UI)
            alert(event.message);
        });
}

### 6. **Run the Queue Worker**
If you're using a queue for broadcasting, make sure your queue worker is running:

php artisan queue:work

### 7. **Test the Notification**
1. Log in as an admin using the `admin` guard.
2. Trigger the notification (e.g., call the `notifyAdmins` endpoint).
3. Verify that the notification is broadcasted to the `admin-notifications` private channel and received on the frontend.

This setup ensures that all authenticated admins listening to the `admin-notifications` private channel will receive notifications without requiring the admin ID. ๐ŸŽ‰

User
write
Echo.private(`postapproved.${user.id}`)
.listen('PostApproved', (event) => {
console.log('Post Approved:', event);
toast(event.post+' is approved', {
autoClose: 5000,
type: 'success',
theme: 'colored',
position: toast.POSITION.TOP_RIGHT,
});
// Handle post approval (e.g., update the UI)
});
in blade template
Assistant
To use the `Echo.private` setup directly in a Blade template, you can include the JavaScript code within a “ tag in your Blade file. Here's how you can do it:

### 1. **Include Necessary Scripts**
Make sure Laravel Echo and any dependencies (e.g., Pusher) are properly included in your project. Add them to your `app.js` file if not already added.

If you're using `vite`, ensure you include the compiled assets in your Blade template:

@vite(['resources/js/app.js', 'resources/css/app.css'])

### 2. **Pass Data from Blade to JavaScript**
Pass the authenticated user's ID or other necessary data to the JavaScript code in your Blade template. Use Laravel's `auth()` helper to get the current user's ID.

### 3. **JavaScript Code in Blade**
Here's how the code might look in your Blade template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post Approval Notification</title>
    @vite(['resources/js/app.js', 'resources/css/app.css'])
</head>
<body>
    <h1>Welcome, {{ auth()->user()->name }}</h1>

    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>

    <script>
        // Ensure Laravel Echo is included
        import Echo from "laravel-echo";
        import Pusher from "pusher-js";

        const userId = {{ auth()->id() }}; // Pass the authenticated user's ID

        window.Echo = new Echo({
            broadcaster: "pusher",
            key: "{{ env('PUSHER_APP_KEY') }}", // Replace with your Pusher key
            cluster: "{{ env('PUSHER_APP_CLUSTER') }}",
            forceTLS: true,
        });

        Echo.private(`postapproved.${userId}`)
            .listen('PostApproved', (event) => {
                console.log('Post Approved:', event);
                toast(`${event.post} is approved`, {
                    autoClose: 5000,
                    type: 'success',
                    theme: 'colored',
                    position: 'top-right',
                });
                // Handle post approval (e.g., update the UI)
            });
    </script>
</body>
</html>

### 4. **Install Required Dependencies**
Ensure you have the required dependencies installed in your project:
– Laravel Echo
– Pusher
– Toastify (or any notification library)

Install them using Yarn or npm:

yarn add laravel-echo pusher-js toastify-js

### 5. **Event Handling on the Backend**
Ensure you have set up the `PostApproved` event in your Laravel backend and are broadcasting it to the appropriate private channel. Here's an example:

#### Broadcasting Event Example:

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateQueueSerializesModels;

class PostApproved implements ShouldBroadcast
{
    use SerializesModels;

    public $post;

    public function __construct($post)
    {
        $this->post = $post;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('postapproved.' . auth()->id());
    }

    public function broadcastAs()
    {
        return 'PostApproved';
    }
}

### 6. **Test the Setup**
1. Ensure the authenticated user is subscribed to the private channel.
2. Trigger the `PostApproved` event.
3. Verify that the notification appears in the browser as expected.

With this setup, your Blade template will listen for `PostApproved` events and display a toast notification whenever a post is approved.

Leave a Comment

Your email address will not be published. Required fields are marked *