I'm using slugs to navigate in my site, but I need the id connected to the slug for a function.
Function:
public function categories(Request $request, $slug)
{
$categories = Category::where('slug', $slug)->get();
$announcements = Announcement::where('category_id', $request->id)->paginate(5);
$category_lists = Category::all();
return view('announcements.index', compact('announcements', 'categories', 'category_lists'));
}
This is the function where I need to get the ID. $request->id isn't working since my $request->id returns 'null'. Is there any way to get the id that's connected to the slug/DB row?
If any more information is needed please tell me.
I've tried getting it with
$announcements = Announcement::where('category_id', Category::get(id))->paginate(5);
and things alike, nothing worked.
I suppose you override the getRouteKeyName
in your Category
model:
public function getRouteKeyName()
{
return 'slug';
}
Then you can get the Category
like this with the route model binding:
public function categories(Request $request, Category $category)
{
$announcements = Announcement::where('category_id', $category->id)->paginate(5);
$category_lists = Category::all();
return view('announcements.index', compact('announcements', 'category', 'category_lists'));
}