Hotdot Cyber
Hotdot Cyber

Reputation: 393

Displaying multiple images in a view laravel 7

I am trying to display multiple images which works fine in Laravel 7. I have a product and images where a product has many images. I am able to view all images of a single product using a url like this http://localhost:8000/products/5. This only displays all the images of id 5. Now I want to display all the images from the database for all products in a view but grouped by the name of the product. i.e all the images let's of id 1,2,3.. be displayed in a view. This is the code in my controller. How can I adjust this?

  public function getImageData($id)
    {
      $product=Products::find($id);
      $images=$product->images()->get();
     return view('products',['product'=>$product
      ,'images'=>$images

 ]);
           
}

and in web.php

Route::get('/products/{id}', 'ProductsController@getImageData');

Upvotes: 0

Views: 528

Answers (1)

Eric Qvarnström
Eric Qvarnström

Reputation: 1002

What you want to do is create a new function that fetches all images for all products, and then put the images on the index of each product. This could implemented in the following way:

public function getProductImages(){
    // Fetch all the products 
    $products = Products::all();

    // Create an array to hold the data
    $arrayOfImages = [];

    // Make a foreach over the products to fetch the data
    foreach($products as $product){
        $arrayOfImages[$product->id] = $product->images()->get();
    }

    return view('products', ['productImages' => $product]);
]);

After this, you can simply foreach over the specific index to get the images of each product. Forexample

foreach($productImages[0] as $productImages){
    // Do the magic here
}

Upvotes: 1

Related Questions