DEV Community

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on • Edited on

Simplify Generate URL for Resourceful Controller

Today I come across a use case where I need to minimise writing route('resources.index)` and so on, all related to resourceful routes.

Can it be more simpler if based on given model, I can simply get the model's resourceful URL without think much what's the name of the resourceful route?

What I mean, I don't want to remember anything about given model, what's its route names. I assumed it should be some sort of standard naming convention.

For instance, if given model is \App\Models\User, it's URI always in lower case, plural and kebab case - http://domain.com/users for users.index, http://domain/users/1 for users.show.

It's quite simple if you developing a small application.

BUT, if you are handling a huge application, multiple modules and features in it, best to keep it consistent and easy to maintain.

Here how I solve the use case:

InteractsWithResourceRoute

Use this trait in any models, and the usage:

Usage

With this solution, I make two things clear:

  1. A standard naming convention for my URIs.
  2. A seamless way to get model's URI

And an absolute rule:

  1. Your model need to use the trait.
  2. Your route for the model need to be resourceful.

Another question, do you need to apply this to all models? Yes, but work smart - create a base model that later on, all models extend from the base class. Again, you model is maintainable for future use.

Top comments (0)