Dinesh Suthar
Dinesh Suthar

Reputation: 880

How to broadcast errors and warnings in laravel?

I am using Laravel 5.6 and socket.io to broadcast messages in admin panel of my application.

In my application, there is a requirement to broadcast all the errors and warnings generated before logging them into laravel logs files to admin.

I just wanted to know how can I achieve this functionality. What are the other easy ways since I am new to Laravel framework.

This is what I did so far:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ErrorBroadcasting implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $errorContent;

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

    public function broadcastOn()
    {
        return new PresenceChannel('error-broadcasting-channel');
    }
}

And this is how I am consuming the channel in my blade.

<script>

        window.Echo = new Echo({
            broadcaster: 'socket.io',
            host: window.location.hostname + ':6001',
        });

        var buyer = Echo.channel(`error-broadcasting-channel`);
        buyer.listen("ErrorBroadcasting", e => {
            $('#error_container').append("<div class=\"row chat-snippet\">\n" +
                "                                        <div class=\"col-lg-12\">\n" +
                "                                            <small>Buyer:</small>\n" +
                "                                            <p>"+e.errorContent+"</p>\n" +
                "                                        </div>\n" +
                "                                    </div>");
        });
</script>

And this how I modified my app\Exceptions\Handler.php

public function report(Exception $exception)
    {
        if (config('app.mail_exception') && $this->shouldReport($exception)) {
            $this->sendEmail($exception); // sends an email
        }
        broadcast(new ErrorBroadcasting($exception))->toOthers();
        parent::report($exception);
    }

Upvotes: 0

Views: 608

Answers (1)

FULL STACK DEV
FULL STACK DEV

Reputation: 15971

In your

app/Exceptions/Handler.php

In this class inside the render method you can

 public function report(Exception $exception)
    {

        broadcast($yourEvent)
        parent::report($exception);
    }

Upvotes: 1

Related Questions