Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

459
Vistas
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 Respuestas
Responde la pregunta

0

You can use the following query

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

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda