Moshe
Moshe

Reputation: 6997

Path Function in Laravel for URL With ID and Slug

I have created the following method in an News model in a Laravel project:

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

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

However, I would like to tweak it a bit. I want my url structure to be like this: www.mydomain.com/news/{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?

Here is one solution that I tried:

// web.php
Route::get('news/{article}/{slug}', 'NewsController@show')->name('news.show');

// News.php
class News extends Model
{
  public function path() {
    return route('news.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: news.show] [URI: news/{article}/{slug}].'

I have tried other variations -- but nothing seems to work.

Any idea how to tweak this so that it does work?

Thanks.

Upvotes: 0

Views: 213

Answers (1)

Lijesh Shakya
Lijesh Shakya

Reputation: 2540

// web.php
Route::get('news/{id}/{slug}', 'NewsController@show')->name('news.show');

You need to pass article id and slug

// News.php
class News extends Model
{
  public function path() {
    return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
  }
}

Upvotes: 1

Related Questions