0

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.

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
SpookyCode
  • 39
  • 1
  • 7

2 Answers2

1

Change your code to

$category = Category::where('slug', $slug)->first();
$announcements = Announcement::where('category_id', $category->id)->paginate(5);

if one category has one unique slug, just use first(), instead of get() and you can get the category object and use it.

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
1

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'));
}
nakov
  • 13,938
  • 12
  • 60
  • 110