Sebastian De Deyne
Designer & developer at Spatie

Tim MacDonald on HasOne relationships in Laravel

timacdonald.me

I’ve used HasOne relationships for 1:1 relationships, but those are rare. I haven’t considered using them to scope down relationships, like having one default payment method in a set of n methods.

<?php

class User extends Model
{
    public function paymentMethods(): HasMany
    {
        return $this->hasMany(PaymentMethod::class);
    }

    public function defaultPaymentMethod(): ?HasOne
    {
        return $this->hasOne(PaymentMethod::class)
            ->whereDefault();
    }
}

$user->defaultPaymentMethod;

After reading Tim’s post, I have a feeling there are some places where I needed this but didn’t think of it at the time…

If you enjoyed this post, you might be interested in my newsletter. I occasionally send a dispatch with personal stories, things I’ve been working on in the past month, and other interesting tidbits I come across online.