Question

I'm currently trying to do a custom forum software for a client, and I'm using the laravel framework. The "board" contains "discussions" that haveMany "comments". Each discussion belongsTo a "category".

What I'm trying to do now, is creating an overview by category. Categories are predefined (like "news", "internal", "project" ...) and discussions can be assigned to them (the category is nullable).

The controller method to get the discussions by category, searching by the url-slug looks as follows:

return View::make('pages.board.overview', [
    'discussions', DiscussionCategory::where('slug', $slug)->discussions()->paginate(25)
]);

Except, that it doesn't work. I would like to retrieve all discussions (with their author, normally I would have used ::with('author'), but where do add that in this case?) that have the specified category, paginated by 25 items.

How do I build a query that does that? Is it even possible to do it in one query?

Was it helpful?

Solution

This will work:

DiscussionCategory::where('slug', $slug)->with('discussions.author')->paginate(25)

Set foreign key on the relation:

// Discussion model, the same applies to the Category model
public function category()
{
    return $this->belongsTo('Umc\Models\DiscussionCategory', 'category_id');
}

Paginating discussions:

$category = DiscussionCategory::where('slug', $slug)->first();
$discussions = $category->discussions()->paginate(25);
$discussions->load('author'); // eager load authors on the collection
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top