Ned
Ned

Reputation: 4141

Using Eloquent relationships gives 'Call to undefined method'

In Laravel's docs there is example that shows how one can chain relationships between Models.

// one to many relationship
$comments = Post::find(1)->comments;

So this is how you can retrieve all the comments, for post with id 1.

But why I can't use relationships chained with where, I keep getting

Call to undefined method Illuminate\Database\Query\Builder::classifieds()

Here's my code:

$classifieds = ClassifiedCategory::where('slug', 'like', $slug)
                                ->classifieds()
                                ->where('is_approved', 'true')
                                ->get();

And here's the related code from ClassifiedCategory model:

public function classifieds() {
 return $this->hasMany('Classified');
}

Upvotes: 0

Views: 2664

Answers (2)

JofryHS
JofryHS

Reputation: 5874

You can try using whereHas:

$classifieds = Classified::where('is_approved', 'true')
                        ->whereHas('classifiedCategory', function($q) use($slug) {
                            $q->where('slug', 'like', $slug);
                        })
                        ->get();

Assuming you have the inverse relationship also defined.

public function classifiedCategory() {
    return $this->belongsTo('Classified');
}

Upvotes: 1

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

whereHas can be used, but here's why your code doesn't work and how to make it work:

$classifieds = ClassifiedCategory::where('slug', 'like', $slug)
    // here you are trying to call relation before you fetched the model
    ->classifieds() 
    ->where('is_approved', 'true')
    ->get();

So you need:

$classifieds = ClassifiedCategory::where('slug', 'like', $slug)
    ->first() // fetch the category
    ->classifieds()  // now query the relation
    ->where('is_approved', 'true')
    ->get();

Upvotes: 1

Related Questions