Laravel replace variable on Model

Viewed 40

I would like to be able to override a variable on the model, so that a normal field is instead replaced by a relationship's field, i.e.

Where product.image might normally be a field, I want to run a function which will go through all of the resulting products from a query and replace the image field with something like the following --

(Product.php) Model

...

public function variantImages(){
    return $this->image = $this->variants()->first()->pluck('image_url');
}

...

So the default product image field is replaced by the "first product variant's image". I don't want to do this in a collection once I have already got the data, the problem here is being able to do this at a Model level.

Is there a way to do this within a scope?

1 Answers

You can create an accessor instead of a normal function:

// Singular because it only gets one
public function getVariantImageAttribute(){
    return $this->image = $this->variants()->first()->pluck('image_url');
}

This will make it available under $product->variant_image

Then you can ensure it is always appended to your model (if you want) by adding it to the appends e.g.:

$appends = [ 'variant_image' ];

Since this is not the best idea since it will force load the relationship every time you get a product (even if you didn't request it) you can conditionally control when to append it via e.g.:

return response()->json($product->append('variant_image'));

Note that the append method also works for collecitions of eloquent models.

Related