1
\$\begingroup\$

I have a web application where users can uploads image documents.

Now, after a new document is uploaded into the system, it should:

1) Be optimized. (OCR)

2) Perform various rules on the OCR output.

For this, I rely on Events in Laravel.

I have registered below events for my model Document.php:

protected $dispatchesEvents = [
    'created' => DocumentCreated::class, //Once document has been uploaded.
    'updated' => DocumentUpdated::class, //Once OCR has been performed.
];

Now, for each event, I have also defined listeners.

This is my EventServiceProvider.php:

DocumentCreated::class => [
    PerformOCROnDocument::class,
],
DocumentUpdated::class => [
    ParseDocument::class,
],

So when a new document is created, it will:

1) Perform OCR on the document. This class PerformOCROnDocument will do various tasks. Most importantly, PerformOCROnDocument will ultimately call:

$document->save();

Since I have defined updated on my Document model, once the save() method is called, it will trigger the next event: DocumentUpdated.

2) Now, ParseDocument will run, and do some various tasks as well.

Important:

The ParseDocument cannot run before PerformOCROnDocument has finished.

Now my question is: is this the correct way of doing this and handling events? Ultimately, my events will implement ShouldQueue so everything will be added to a queue and handled async.

Alternative solution

Now, what I could also do was to trigger an event inside PerformOCROnDocument, like this:

$document->save();
event(new OCRFinished($document));

And then in EventSerivceProvider.php, do like this:

OCRFinished::class => [
    ParseDocument::class,
],
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.