Answer the question
In order to leave comments, you need to log in
Is there a scope analog for Laravel collections?
After spending some time googling for answers, I never found an answer to the following question.
Is there a scope analog for Laravel collections?
Among the answers I read, it was stated that you can use scope for models (not collections). For example: I need to get all active (with status 1) and inactive (status 0) comments. How it's done, options:
$active_comments = $post->comments->where('status', 1);
$incative_comments = $post->comments->where('status', 0)
Answer the question
In order to leave comments, you need to log in
class Post {
public function scopeCommentsWithStatus($query, $status)
{
return $this->comments->where('status', $status);
}
public function getActiveCommentsAttribute()
{
return $this->comments->where('status', 1);
}
}
$post = Post::with(['comments'])->first();
$post->commentsWithStatus(1);
$post->commentsWithStatus(0);
$post->active_comments;
If you really want to crutch
Collection::macro('inactive', function () {
return $this->where('status', 1);
});
It is not worth being afraid of queries, the database was created for this) If there is a lot of data, the query will be faster than filtering the collection (checked). In general, it is better to think like this - there are no ospreys, which means they should not be. With various kinds of innovative ideas without experience, you can then run into a sickly refactoring (checked). I would do so
// В модели Post
public function activeComments()
{
return $this->commnets()->ofActive();
}
public function inactiveComments()
{
return $this->commnets()->ofInactive();
}
// в контроллере/классе
$relations = ['activeComments', 'inactiveComments'];
Post::with($relations)
->withCount($relations)
->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question