Skip to content
Advertisement

How to fetch product name from orders table which contain product_id in laravel?

I am unable to fetch the product name according to matching id but i am getting same name in table as shown below this is the ordered list of products

Please check table for reference ill be showing below (order_list table)

order_list table

Table products

products table

My Controller

public function details($id)
{
    $orders = Order_model::find($id);        

    $Order_lists = Order_list::orderBy('id', 'asc')->where('user_id', '=', Auth::user()->id)->where('order_id', '=', $id)->get();

    foreach($Order_lists as $order_list)
    {
        $prod_name = DB::table("products")->where('id', $order_list->product_id)->value('name');

    }
    $address = DB::table("delivery_address")->where('user_id', '=', Auth::user()->id)->get();

    if(Auth::user()->role == 'customer')
    {
        return view('customer.orders.details',['Order_lists' => $Order_lists, 'orders' => $orders, 'address' => $address, 'prod_name' => $prod_name]);
    }

}

please Help me out as i am at learning stage and any help would be glad to hear thanks.

Advertisement

Answer

the problem is $prod_name is a single variable and you running it in loop. so it only replace every iteration and just get last iteration name. so if you want get every product name with $order_list , you can easily create Model for products table. then create one to one Order_list. eg:

https://laravel.com/docs/7.x/eloquent-relationships#one-to-one

class Order_list extends Model
{
   
    public function products()
    {
        return $this->hasOne('AppProducts',"product_id");  //your model name and path
    }
}

then you can get all order list data with product like this:

$Order_lists = Order_list::orderBy('id', 'asc')->where('user_id', '=', Auth::user()->id)->where('order_id', '=', $id)->with('products')->get();

product details should in $Order_lists[0]->products->name

edit: to run this in blade file

@foreach($Order_lists as $Order_list)
////other <td>s

    <td>{{$Order_list->products->name}}</td>


@endforeach

if above method is complex you can create separate array to name

 $prod_name =[];
 foreach($Order_lists as $order_list)
    {
        $prod_name[$order_list->product_id] = DB::table("products")->where('id',  $order_list->product_id)->value('name');

    }

then read it on blade file like this:

{{$prod_name[$order_list->product_id]}}

edit: to print elements in second method you can use blade syntax. first send veriables to .blade file eg: view(‘your.blade.php,compact(‘Order_lists’,’prod_name’));

//then print in .blade file 

 @foreach($Order_lists as $Order_list)
        ////other <td>s
        
            <td>{{$prod_name[$order_list->product_id]}}</td>
        
        
  @endforeach
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement