moshemo's avatar
Level 12

Path Function for URL With ID and Slug

I am referencing this episode: https://laracasts.com/series/laravel-6-from-scratch/episodes/28?autoplay=true

In that episode, Jeffrey creates the following function in the Article model:

  public function path() {
    return route('article.show', $this);
  }

Now, this works just fine and returns the following url structure: www.mydomain.com/article/{id}

However, I would like to tweak it a bit. I want my url structure to be like this: www.mydomain.com/article/{id}/{slug}

So, what I want to know is how do I have to modify the path function in order to return this url structure - i.e., the one with both the id and the slug?

0 likes
4 replies
Snapey's avatar

since the whole model is passed to the route helper, it will look at the placeholders in the Route and fill in any parameters required.

So in web.php you will have something like

Route::get('article/{id}', 'ArticleController@show');

It should be enough to just add the slug

Route::get('article/{id}/{slug}', 'ArticleController@show');
moshemo's avatar
Level 12

I tried that, but I still get an error when testing it out in tinker. Here is my web.php file looks like:

Route::get('articles/{article}/{slug}', 'ArticleController@show')->name('articles.show');

And here is my path function:

public function path() {
    return route('articles.show', $this);
  }

I then fire up tinker and run that path function and get the following error:

Illuminate/Routing/Exceptions/UrlGenerationException with message 'Missing required parameters for [Route: articles.show] [URI: articles/{article}/{slug}].'

Any idea why?

Snapey's avatar
Snapey
Best Answer
Level 122

You don't have a model column called article. either change it to {id} or be explicit in the route helper

public function path() {
    return route('articles.show', ['article' => $this->id, 'slug' => $this->slug]);
  }
1 like

Please or to participate in this conversation.