Conditional model relations (Eloquent)



Also posted this on the Eloquent forum, but it’s on a Userfrosting project, so I am trying my luck here as well…

I have a generic model, let’s call it a Vehicle.

A Vehicle can be one of many types (Bicycle, Bike, Car, Truck, etc…)

The above vehicle types details, are in separate tables, each holding the special properties and technical characteristics for that type of vehicle. So e.g. a Car has engine characteristics, a bicycle has front/back gears etc.

I want to achieve the following scenario.

  1. The controller calls my Vehicle Model to request Vehicle with id = 145.
  2. Vehicle Model, checks vehicles table, and finds entry with id 145, to get the generic vehicle data (vehicle_type_id, name, description etc…)
  3. Then, depending on the vehicle_type_id entry, reaches out to the relevant table (e.g. vehicle_type_id = 3, it’s a Car, go to the cars table).
  4. It looks for the vehicle_id 145 in the cars table, and gets all the car specifications.
  5. The Vehicle model returns the complete vehicle data, including the car specifications.

Makes sense?

Any idea how to approach this in Eloquent (v5.4 since that’s in the latest UF4.1 at the moment)



What you’re looking for is a one to many Polymorphic Relations.