0

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?

1 Answer 1

1

You can create a custom attribute instead of a relation function:

    public function getCurrentOwnerAttribute()
    {
        return $this->owners()->where('active', true)->first();
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I'm using the same line in my currentOwner() function. :)
@flow3r your function is different. by using "public function currentOwner()" you set a relation, "public function getCurrentOwnerAttribute()" creates a custom attribute. that you can call by using $car->currentOwner. laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
I'm sorry, I didn't know the difference between our function declarations, I'm new to Laravel. But your solution works, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.