Let’s Use Laravel Controllers, Events, Listeners, Services and Validation Together!

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

Reza Khademi
3 min readJun 6, 2022

--

While it is possible to place all of the code for a web application into controllers, this approach is not advisable.

In this article, we will explore how to structure a web application using a well-known pattern. It is worth noting that there are various ways to achieve this, and all of them could be correct. Therefore, this article provides only a few examples of how to accomplish this.

Allow me to 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:

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

2. Better Way

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

php artisan make:request ArticleStoreRequest

To ensure that the user is authorized to perform the action, make sure to return true in the authorize() method:

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!

To separate the creation logic from the controller, we will create an ArticleService. This service will handle the creation of new articles, while the controller will simply pass the data to the service:

Laravel single responsibility principle

Now, let’s take another look at our ArticleController to see what changes have been made so far:

  • To notify the followers of the article writer when a new article is published, we will use events and listeners. We will create an event that is triggered when a new article is created, and a listener that sends an email notification to the writer’s followers:
php artisan make:event ArticlePublishedEventphp artisan make:listener ArticlePublishedListener --event=ArticlePublishedEvent

This philosophy helps us to divide operations and ensures that events will automatically fire whenever and wherever we want them to. Additionally, this approach prevents us from repeating ourselves.

The event class should accept both the User and Article models as arguments, which can then be passed to ANY listener of that event:

Laravel Event Listener

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

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

That’s it…

READ MORE:

--

--