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

tbkinc's avatar

Adding a Function to a Model / Relationship method must return an object of type Relation

I am trying to add a function to my model that is not a relationship, scope, or mutator. Is this possible/advised?

I have:

class OrderLineItem extends Model
{
public function fill_backorder() {
        Log::debug('Fill backorder.');

        $self = $this;
        $qty_to_fill = $self->QuantityNeeded;

        if($self->SkuDetails->QOH >= $qty_to_fill) {
            DB::transaction(function() use($self, $qty_to_fill) {
                Log::debug('We have Inventory.', ['$this' => $self]);

                $self->SkuDetails->QOH -= $qty_to_fill;
                $self->SkuDetails->save();

                $self->QuantityNeeded -= $qty_to_fill;
                $self->QuantityShipped += $qty_to_fill;
                $self->save();

                if ($self->Parent > 0) $self->fill_parent;
            });
        }
    }
}

When I call it, all works exactly as I want it to, but then I get an error after it finishes:

ERROR: exception 'LogicException' with message 'Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation' in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:2691

0 likes
1 reply
tbkinc's avatar
tbkinc
OP
Best Answer
Level 2

I found my issue. I forgot the parenthesis when I was calling my second function. So I needed to update to: if ($self->Parent > 0) $self->fill_parent();

Please or to participate in this conversation.