I want to display all products on my page. Each product has x number of images. Some products have images which are set to be cover images. Now I need to get all products with the cover images, and if a particular product doesn't have a cover image set, then I need to get a random image.
+----+--------------+
| id | product_name |
+----+--------------+
| 1 | Ferrari |
| 2 | Audi |
| 3 | BMW |
+----+--------------+
+----+--------------+------------+-------------+--+
| id | image_name | product_id | cover_image |
+----+--------------+------------+-------------+
| 1 | audi.jpg | 2 | 1 |
| 2 | Audis.jpeg | 2 | |
| 3 | bemms.jpg | 3 | 1 |
| 4 | ferrari.jpeg | 1 | |
| 5 | ferr.jpg | 1 | |
+----+--------------+------------+-------------+
So far I've tryed this code but it doesn't solve my problem because I only get pictures with the cover image set.
public static function get_all_products() {
return \DB::table('products')
->leftjoin('product_pictures', 'products.id', '=', 'product_pictures.product_id')
->select('products.name', 'product_pictures.images_name')
->where('product_pictures.cover_image', '=', 1)
->get();
}
Any help is welcome!