Dave Wize's avatar

Weird error on a Model Attribute!

I have a donation model and a campaign model.

I need to fetch the donation receipt template and, if none, fetch the campaign template, which depends on the donation amount. here is my two methods

On the Donation Model

    protected function receiptTemplate(): Attribute
    {
        return new Attribute(
            get: fn () => $this->template ?? $this->campaignTemplate() ?? $this->organization?->template ?? Template::first() ?? null,
        );
    }

    public function campaignTemplate()
    {
        return $this->campaign->template($this->amount);
    }

On the Campaign Model


    public function templates(): BelongsToMany
    {
        return $this->belongsToMany(Template::class)
            ->withPivot('from_amount', 'to_amount')
            ->withTimestamps();
    }


    public function template(?int $amount): ?Template
    {
        return $this->templates()->wherePivot('from_amount', '>=', $amount)
            ->wherePivot('to_amount', '<=', $amount)
            ->first();
    }

Now when it runs, I'm getting this error

Too few arguments to function App\Models\Campaign::template(), 0 passed in /home/forge/rms.hardonsoft.com/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 577 and exactly 1 expected {"exception":"[object] (ArgumentCountError(code: 0): Too few arguments to function App\Models\Campaign::template(), 0 passed in /home/forge/rms.hardonsoft.com/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 577 and exactly 1 expected at /home/forge/rms.hardonsoft.com/app/Models/Campaign.php:70)

Any help?

0 likes
1 reply
s4muel's avatar
public function template(?int $amount): ?Template
    {
        return $this->templates()->wherePivot('from_amount', '>=', $amount)
            ->wherePivot('to_amount', '<=', $amount)
            ->first();
    }

by the ?int $amount definition, the $amount is nullable, but mandatory. add the default value or review your code and if the amount is mandatory, pass it in

public function template(?int $amount = null): ?Template
    {
		//but somehow handle the null value
        if(!$amount) {
            return null;
        }
        return $this->templates()->wherePivot('from_amount', '>=', $amount)
            ->wherePivot('to_amount', '<=', $amount)
            ->first();
    }

Please or to participate in this conversation.