Virebot's avatar

Parameterize links

I have a url path: places/5

But I want it to be friendly: places/5-central-city-colorado

In Rails, we have to_param in the model to achieve this. This is what I did in Eloquent:

public function sluggedPath(): string
  {
     return strval($this->id) . '-' . Str::slug($this->city) . '-' .Str::slug($this->state);
  }

Is this the way? Am I missing something in the docs? Thanks in advance.

0 likes
8 replies
LaryAI's avatar
Level 58

The solution provided by the user seems to be correct. They are using the Str::slug() method to generate a slug from the city and state attributes of the model, and then concatenating it with the ID to create a unique and friendly URL.

To use this method in a link, you can simply call the sluggedPath() method on the model instance and use it as the URL path. For example:

<a href="{{ url('places/' . $place->sluggedPath()) }}">View Place</a>

This will generate a link with the URL places/5-central-city for a place with ID 5, city "Central City", and state "Some State".

PovilasKorop's avatar

@virebot you're generally doing things ok but you didn't show how exactly you use that sluggedPath() method, are you doing it when saving the value or retrieving it, or in Route Model binding.

Virebot's avatar

@PovilasKorop Thanks for asking. I am using it in the view like so:

<a href="{{ route('places.show', ['slugified_id' => $previous-> sluggedPath()]) }}">
  {{ $previous->title }}
</a>
dacfabre's avatar
dacfabre
Best Answer
Level 3

if your $previous is a model, what you need is accessor

Laravel 8 and below

public function getSluggedPathAttribute()
{
    return "{$this->id}-{$this->city}-{$this->state}";
}

laravel 9+

public function fullName(): Attribute
{
    return new Attribute(
        get: fn () => "{$this->id}-{$this->city}-{$this->state}";
    );
}

doc here: https://laravel.com/docs/10.x/eloquent-mutators

2 likes

Please or to participate in this conversation.