Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

464
Views
Laravel 8: Can I make Eloquent scope but NOT against query builder but against related model?

I have a model - let's call it Parent.

Each Parent can have many children.

public function children(): HasMany
{
    return $this->hasMany(Child::class, 'parent_id', 'id');
}

I want to make a scope for Parent called "active".

My requirement goes as follows:

Parent is active when it has at least 1 child.

I've done local scopes multiple times and I know that within Parent.php I can do something like:

public function scopeActive($query)
{
    return $query->where(…);
}

But as you see, $query is a \Illuminate\Database\Eloquent\Builder which is not my case. I want to operate on related model somehow, not the DB query.

Can I do this in a clean way without fetching all parents with('child') and within ->filter() forgetting those that have no children? When there will be 1000 parents but only one will have children, it will simply waste DB resources (by fetching 999 redundant parents).

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can use the following query

public function scopeActive($query)
{
    return $query->has('children');
}
over 4 years ago · Santiago Trujillo Report

0

One option is to use whereHas in scope:

public function scopeActive($query){
  return $query->whereHas('children');
}

OR

public function scopeActive(){
  return $this->whereHas('children');
}

And

Parent::active()->with('children')->get();

should give you all Parents who have children and along with respective children

over 4 years ago · Santiago Trujillo Report

0

Can you try something like:

public function getActiveAttribute() {
  return $this->children()->count() > 1;
}

This can be used like,

$parent->active

And the query will only be made when you'll try to access the active property on the Parent model, not when you will be fetching all parents.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!