mardi 5 mars 2019

Showing default image in a Relation table

I guys, i have a products table and a products_images.

In my Product model i have a method that gets the image related with the product, and than in the product_images Model i have another method (mutator) that checks if the images exists and in case that exists show the image, if not show a default image.

But i notice that im doing it wrong, because case the product image doesnt exists in the table product_images, the method will never get fired, so all the logic should be in the product Model.

This is how i did:

Product model:

 public function image()
    {
      return $this->hasOne(ProductImage::class);          
    }

ProductImage model:

protected $fillable = [
        'product_id', 'path', 'is_main_image'
    ];
    public function getPathAttribute($value)
    {

        if($value){

            $image = url('storage/media/products/thumbs/'.$value);
        }else{
            $image = 'https://via.placeholder.com/206';
        }
        return $image;
    }

So looking what i did how can i add the last logic of the method ProductImage to the Product Model metho image, what is the best way of doing without creating conditionals on blade to check if image exists or not.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire