Inertia - append custom attribute only on demand - without $appends, with implicit model binding in laravel

22 Views Asked by At

I need appending custom attribute only when I want this. I want to optimize sending data, not always I want this custom attribute. In other words I need this eloquent-serialization#appending-at-run-time but in model directly.

In model I have:

protected function qrCode(): Attribute
{
    return new Attribute(
        get: fn () => $this->generateQrCode($this->code),
    );
}

In controller implicit model binding:

public function show(Code $code)
{
    $code->append('qr_code');
    $code->load('offer','user:name');
    return Inertia::render...
}

But It Doesn't work.

With: $code->append('qr_code')->toArray() It will but later I need relations and pass it to inertia, so I want to stick with Model type.

Temporary solution: for now only option is to make custom function in Model but maybe there is other?

public function appendCustom($column) {
    return $this[$column] = $this->{$column};
}
0

There are 0 best solutions below