how to retrieve image and imagess data using one to many relationship

i’m working on a E-commerce like project where users can upload multiple images of a particular product, i have a one-to-many relation where many images has one description and price. so on the homepage i need to call a single image out of the total uploaded and also fetch the descrition of the image, so when view button is clicked the user can see the rest of the image sliding.

upload Controller

public function store(Request $request)
        'farm_name'=> 'required',
        'images' => 'required',
        'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        //'' => 'image|mimes:jpeg,png,jpg,gif,svg|max:6048',

    $input = new Product;
    $input->farm_name = $request->farm_name;
    //$input->user_id = Auth::user()->id;
    $input->farmer_name = $request->farmer_name;
    $input->tel = Auth::user()->tel;
    $input->farm_adrs = Auth::user()->adrs;
    $input->state = Auth::user()->state;
    $input->email = $request->email;
    $input->qty = $request->qty;
    $input->descr = $request->descr;
    $input->product_package = $request->product_package;
    $input->catr = $request->catr;
    $input->lga = $request->product_name;
    $input->amount = $request->amount;
    //$input->img = $request->images;

    foreach($request->file('images') as $imageFile){
        $image = new Image;
        $imageName = time().rand(1,99).'.'.$imageFile->extension();  
        $imageFile->move(public_path('images'), $imageName);
        $image->images_id = $input->id;
        $image->name = $imageName;

    return back()
            ->with('success','Your Product is succesfully Uploaded.');


//show image this where i have problem

public function index(){
    $products = Product::all();
    foreach($products as $product){
        $product_id = $product->id;
        $images = Image::find($product_id);

        return view('app.index',  compact('products', 'images'));

>Solution :

First of all u re saving product id as image_id on image table. Is this your correct column? if you are using image_id to save related product id, then change the index code to

public function index(){
$products = Product::all();
foreach($products as $product){
    $product_id = $product->id;
    $images[$product_id] = Image::where('image_id',$product_id)->get();

    return view('app.index',  compact('products', 'images'));


it will give you all the images from all product set upped with index of product id.
in a better way you can directly join the table. it will reduce the no. of executing query.

Leave a Reply