Rafał Walczak
Rafał Walczak

Reputation: 543

Filtering results by model in Laravel Eloquent ORM

I'm building simple forum with Laravel 4. I need to count posts written by current user on given topic.

What I have so far:

$topic = Topic::find(1);
$user = Auth::user();
echo $user->posts()->whereTopicId($topic->id);

This works fine, but I'm not satisfied with working on ID directly. Is it possible to do it in neat way using relations?

I'm looking for something like this:

echo $user->posts()->whereTopic($topic);

Which doesn't work.

Upvotes: 1

Views: 1119

Answers (1)

Simon Wicki
Simon Wicki

Reputation: 4059

you could achieve $user->posts()->whereTopic($topic) by using scopes in your Post Model

public function scopeTopic($query, $topic)
{
    return $query->where('topic_id', '=', $topic->id);
}

Upvotes: 1

Related Questions