#How to Dynamically Access a Relationship in Laravel?

1 messages · Page 1 of 1 (latest)

alpine veldt
#

I'm working on a Laravel project where a Stay can either reference a Vehicle or store vehicle information directly. This avoids creating a Vehicle for one-time stays, as most vehicles won't return.

My structure example

Stay:
  vehicle_id: id foreign nullable # null if other_fields
  vehicle_plate: string nullable # null if vehicle_id
  vehicle_type_id: id foreign nullable # null if vehicle_id

Vehicle:
  plate: string unique
  vehicle_type_id: id foreign

VehicleType:
  name: string unique

I want a way to access $stay->vehicleType from a Stay, whether it's from the associated Vehicle or directly from the Stay information (only one of them will be available, I cannot have Stay with both vehicle_type_id and vehicle_id). When I create a Stay, I'll fill vehicle_id leaving the other fiels null and vice-versa.

molten edge
#

Create a mutator for that

alpine veldt
#

Do I have to create it with a different name? other than "vehicleType"

molten edge
#

You can name it however you want tbh

#

You can use it both for changing the way it set the property and get the attribute

alpine veldt
#

Yeah, I can not define it with the same name of the relationship belongsTo declaration, so I did this:

protected function getVehicleVariantAttribute(): ?VehicleVariant
{
  return $this->vehicleVariant ?? $this->vehicle?->vehicleVariant;
}

I don't like that solution very much because is the "old" way to define an accessor, and the automatically typing (in vscode) does not type it correctly... But i think is fine, thank you very much

molten edge
#

Get*

#

If dislike the magic way