DEV Community

bakle
bakle

Posted on

Laravel URL Presenters

Usually, we always find new ways to make our backend code cleaner, readable and flexible by applying design patters, software principles, refactoring strategies, etc.

This time, the strategy we are going to apply is about communication of backend and frontend and how the backend code can provide much more information to our views.

Most of us render the application routes directly in the view, and sometimes we find that we are repeating these same routes along the view.

Index view

We can see that we are repeating the same url in lines #19 and #28. This is the good way, some people use (see line #2):

Index view 2

So, how can we make this a little bit cleaner and reusable along the application? Well, we can apply a Url Presenter.

There are many ways to do it, so I'm going to show you one of them.

Some people like to do it inside the model, which I think is not the best way because we are giving a responsibility to the model that should not have, I mean, why the model should know about urls?

Let's begin with the first step.
 
 

Creating an interface

When I talk about interface I mean that it could be an abstract class or interface, that depends on your need. This time we are going to make a simple interface for a url resource (index, show, edit, ...).

Interface
 

Creating concrete url presenter

Now, we just create a concrete url presenter, in this case we are going to create a UserUrlPresenter

Concrete
 

Using the presenter

Let's suppose we have our UserController, we just have to pass the url presenter to the view.

Controller
 

Final view

Now, we can use the url presenter inside the view.

Final View

 
 
 

Bonus

I know I said that I am not a fan of url presenters inside the model, but I will give you an example of how to do it.
 

Creating the interface

Interface
 

Creating concrete url presenter

Concrete presenter url 2
 

The presenter in the model

Model
 

Using the presenter

Controller 2
 

Final View

Index 3

Top comments (0)