Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

parasume's avatar

How to make custom Eloquent relationship classes

Is there a tutorial out there on how to create custom relationship classes? If not, perhaps @JeffreyWay could include an advanced lesson on that? Or maybe like a "behind-the-scenes" lesson just going through the magic of it all, I totally love your behind-the-scenes lessons!

0 likes
1 reply
Braunson's avatar

Yes you can create custom relationships.

Here's an example for BelongsToEmpty, a very simple example in this case to return a valid empty BelongsTo relation.

<?php

namespace App\Relations;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BelongsToEmpty extends BelongsTo
{
    public function getResults()
    {
        return Collection::make();
    }

    public function get($columns = ['*'])
    {
        return Collection::make();
    }
}

I just placed this in app/Relations/BelongsToEmpty.php composer will autoload it. I can then use it in my models as needed.

For another more complex example, check out this BelongsToMorph relation class here https://gist.github.com/thisdotvoid/3022fee8afa53e45a6b89da3f16b3815

Please or to participate in this conversation.