moshemo
2 weeks ago

Accessing Path Function in Model in Index File

Posted 2 weeks ago by moshemo

I have set up the following function in my model:

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

I would now like to access that function in my index.blade.php file -- like this:

  @foreach ($articles as $article)
  <a href="{{ $article->path() }}">
	// rest of code goes here
  </a>
  @endforeach

But when I try this, I get the following error:

Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: news.show] [URI: news/{id}/{slug}]. (View: C:\laragon\www\startup-reporter\resources\views\news\index.blade.php)

Here is what my routes (web.php) looks like:

Route::get('news', '[email protected]')->name('news.index');
Route::get('news/create', '[email protected]')->name('news.create');
Route::get('news/{id}/{slug}', '[email protected]')->name('news.show');
Route::get('news/{id}/edit', '[email protected]')->name('news.edit');

Route::post('news', '[email protected]')->name('news.store');
Route::put('news/{id}', '[email protected]');

And here is my controller:

  // Index
  public function index() {
    $news = News::latest()->get();
    return view('news.index', ['articles' => $news]);
  }

  // Show
  public function show(News $id) {
    return view('news.show', compact('id'));
  }

Any idea why this is not working and what I need to do to get this to work?

Thanks.

Please sign in or create an account to participate in this conversation.