SpookyCode
SpookyCode

Reputation: 39

Route uses Slug, but id needed for function

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.

Upvotes: 0

Views: 47

Answers (2)

nakov
nakov

Reputation: 14298

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'));
}

Upvotes: 1

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9703

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.

Upvotes: 1

Related Questions