DEV Community

Reza Khademi
Reza Khademi

Posted on

Using Laravel Controllers, Events, Listeners, Services and Validation Together!

We can put all codes of a web application into controllers but this action sounds crazy and it’s quite not right to do!

In this article we will see how to structure a web-app with a well-known pattern. I must say you can do below examples in other different ways and probably all of them will be right, So this article is just some examples for doing things!

Let me explain the scenario:

Imagine we have a simple medium-app and it will have a Content section which a user can share a blog post and his/her followers will notice when a new article published!

1. Ugly Way

Make a ArticleController and put all codes in it, like below:

Image description

2. Better Way

First, we should replace Request $request an ArticleStoreRequest $request to validate data in a better way:

php artisan make:request ArticleStoreRequest

Don’t forget to return true in authorize() method, so user can do this action:

Image description

Second, we should make the ArticleService to move creation logic from controller to service. Because the only thing that a controller will do is passing data!

So we will make ArticleService in Services folder and write creation code to a simple related method and by considering Single Responsibility Principle move upload image to it’s method like below:

Image description

Let’s have another look at our ArticleController again see what have been changed so far:

Image description

  • Now let’s use Event and Listener for sending emails to followers of article writer:
php artisan make:event ArticlePublishedEventphp artisan make:listener ArticlePublishedListener --event=ArticlePublishedEvent
Enter fullscreen mode Exit fullscreen mode

This philosophy help us to devide operations and the event will fire automatically when ever and where ever we want. Also this will pretend us to repeat ourselves!

The event class should accept the User model and Article model, which is then passed to ANY listener of that event:

Image description

Then, the Event is fired from the Controller, like this:

Image description

And, in the Listener class, we repeat the same logic:

Image description

That’s it…

Oldest comments (0)