DEV Community

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on โ€ข Edited on

2 1

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.

Sentry workshop image

Flaky tests got you down?

Learn how to merge your code without having to hit โ€œrerunโ€ every 5 minutes ๐Ÿ˜ฎโ€๐Ÿ’จ

Save your spot now.

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay