How to notify the user that a job has completed in Laravel?

szaman picture szaman · Feb 11, 2016 · Viewed 16.3k times · Source

in Laravel, you can use jobs to execute tasks in a back-end queue while the rest of the application does other things. i have a job that is initiated by user input. immediately, through javascript, i give the user a notification that the job is being processed.

i would like to be able to give a similar notification after the job has successfully completed.

i am calling my job from within a model like this:

public function doSomething() {
    $job = new \App\Jobs\MyJob();
    app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($job);
}

and this is how my job headers look like:

class MyJob extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels, Queueable;
    ...
}

the model job call is actually triggered from a controller method:

public function getDoSomething($id) {
    $item = Item::findOrFail($id);
    $item->doSomething();

    return response()->json(true);
}

which is handled by an AJAX call:

$.ajax({
    url: $(this).attr('href'),
    type: 'GET',
    dataType: 'json',
    success: $.proxy(function(result) {
        this.application.notification.showMessage('Job is being processed.');
    }, this),
    error: $.proxy(function(result) {
        console.error(result);
    }, this)
});

Answer

linkmarine picture linkmarine · Dec 16, 2017

Probably I'm late for the party guys, but there are several options i can think of. When user clicks button from the front-end you can give attribute disabled to it and some text like 'processing'. Then you can:

  1. Just ping your endpoint to check if what job is performing is finished
  2. Use websockets

I think Forge is doing websockets using pusher the endpoint to see if server is active when you are trying to deploy new code. I can clearly see the communication if you open Devtools->Resources->Sockets.