Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

twg_'s avatar
Level 6

Query data from through pivot table based on slug

Hi Everyone,

I have a route setup that uses /books/category/{slug} to get books based off a slug but I'm having an issue getting the data to return quickly.

Tables

/**
 * Books
 */
UUID
Name
ISBN
....


/**
 *  Categories
 */
UUID
Name
Slug
...


/**
 *  Book_Category
 */
UUID
Book_id (foreign)
Category_id (foreign)
...

I'm using the following in my controller to get the data but nothing is coming back.

public function getBooksByCategory($slug)
{
	$books = Book::with('related')
		->whereHas('categories', function ($query) use ($slug) {
			$query->where('category.slug', $slug);
		});
}

0 likes
2 replies
ollie_123's avatar

Hi @twg_

You need to add ->get() to your method and a return.

public function getBooksByCategory($slug)
{
	$books = Book::with('related')
	->whereHas('categories', function ($query) use ($slug) {
	$query->where('category.slug', $slug)->get();
		});
	return $books;
}
alanholmes's avatar

Hi @twg_

The issue is likely, $query->where('category.slug', $slug);.

There is no table category its categories (from your description.

However, what I would do, is use route model binding to get the category (https://laravel.com/docs/8.x/routing#implicit-binding - see Customising the key).

then in your controller it would be: $category->books to get the books for that category.

Please or to participate in this conversation.