I've got 3 tables:
- Car: belongsToMany Owner
- Owner: belongsToMany Car
- CarOwner: pivot table for Car and Owner with an additional column 'active' that indicates who is the current Owner of a Car
So a Car might have multiple or no Owners and vica versa BUT a Car has only 1 current ('active') Owner.
class Car extends Model
{
use HasFactory;
public function owners()
{
return $this->belongsToMany(Owner::class, 'car_owners');
}
public function currentOwner()
{
return $this->owners()->where('active', true)->first();
}
}
My problem is if a Car has no active Owner, Laravel throws the following exception when I want to use $car->currentOwner in a Blade template:
App\Models\Car::currentOwner must return a relationship instance, but "null" was returned. Was the "return" keyword used?
How can I handle if a Car doesn't have any active Owners?