Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Retrieve instances of superclass with Eloquent

Here are my (simplified) models:

abstract class Animal extends Illuminate\Database\Eloquent\Model
{
    protected $name;
}

class Cat extends Animal
{
}

class Dog extends Animal
{
}

Cats and dogs have several other attributes. I've made animal abstract as each animal will be a cat or a dog, so there will be no actual instances of animal.

Now, I want to be able to list:

  • Cat::all() should retrieve all cats.
  • Dog::all() should retrieve all cats.
  • Animal::all() should retrieve all cats and dogs.

Is this generally possible with eloquent? If, yes: Should I use Polymorphic Relations for that purpose?

like image 440
Barret Wallace Avatar asked Nov 28 '25 04:11

Barret Wallace


1 Answers

There's no support for that in Eloquent.

If Cat and Dog have similar properties, a single animals table is probably the best solution. You can use scopes to only get one species:

class Animal extends Illuminate\Database\Eloquent\Model
{
    public function scopeCats($query)
    {
        return $query->where('species', 'cat');
    }
}

$cats = Animal::cats()->get();
like image 140
Jonas Staudenmeir Avatar answered Nov 30 '25 17:11

Jonas Staudenmeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!