banku
banku

Reputation: 119

How to avoid user take long time to wait while controller is processing

let's me explain example

  1. User click button
  2. run function trigger in Controller
  3. User wait 30sec because MyModel::doSomeThing take long time to process

MyModel::doSomeThing do many thing. I don't want user to wait for it.

Is it possible to run MyModel::doSomeThing by don't care about result and return to user immediately?

function trigger(Request $request){ 

   $id= $request->get('id');
   MyModel::doSomeThing($id);  // this one take 30 sec.    
   return response()->json([], 200);

}

Upvotes: 1

Views: 790

Answers (1)

zlatan
zlatan

Reputation: 3951

If the result of doSomeThing() method isn't necessary for your response & can be done in background, I suggest using Events and Listeners, which will use queues to run in the background, and the user won't need to wait for this procces to finish. The process is fairly simple. Create event and it's listened with these two commands:

php artisan make:event YourEvent

php artisan make:listener YourListener --event=YourEvent

After that, register your event and listener in the App\Providers\EventServiceProvider, under the $listen array:

protected $listen = [
    YourEvent::class => [
        YourListener::class,
    ],
];

Now, when you have that sorted out, you need to build your event instance. Inside your newly created method, in the construct method, add this:

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

After you created your model, time to edit your listener, which will hanlde all the logic ghat you need. Inside this handle method, you will have the access to $yourModel instance that we defined in our event:

public function handle(YourEvent $event)
{
    // Access your model using $event->yourModel...
    YourModel::doSomeThing($event->yourModel);
    
}

The only thing left do to is to make your listener queueable. You can do this by adding implements ShouldQueue your listened definition:

class YourListener implements ShouldQueue
{
    //
}

Now when we have everything setup, you can change your controller code to call this newly created event, and let the queue handle all the logic:

function trigger(Request $request){ 

   $id= $request->get('id');
   YourEvent::dispatch($id); //Calling event which will handle all the logic
   return response()->json([], 200);

}

And that should be it. I haven't tested this code, so if you encounter any problems, let me know.

Upvotes: 3

Related Questions