I am using rtconner/laravel-tagging package to get tags functionality to my app.
I can count attached tags by $o->tags->count()
I can loop the tags by a foreach: @foreach($o->tags as $t)
.
print attached tags by
Now I want to get a collection of random 10 Quotation with no tags attached.
While I can print a random 10 pieces with a given attribute:
$object = Quotation::where('deepness', null)->get()->random(10);
(Note: I have a random scope defined in the model, irrelevant for my issue)
... but this code, cloned from another model doesn't work:
$object = Quotation::whereHas('tags','>',0)->get()->random(10);
It produces this error message:
FatalThrowableError in Builder.php line 880:
Type error: Argument 2 passed to Illuminate\Database\Eloquent\Builder::whereHas() must be an instance of Closure, string given
I have also tried to execute this query
$object = Quotation::has('tags')->get()->random(10);
but I got this: ``` BadMethodCallException in Builder.php line 2431: Call to undefined method Illuminate\Database\Query\Builder::tags()
```
Note 2: In the source model (the one I cloned from) the relation was counting a hasMany
relation.
Please help me to create the collection of Quotations with no tags assigned
Had the same problem and solved it this way:
$objects = Quotation::all();
$objects = $objects->filter(
function ($object, $key) {
return $object->tags->count() > 0;
}
)->random(10);
Hope issues still relevant :)