简体   繁体   中英

Display the Name of Table using the ID of another table in Laravel Eloquent

Please, I have a function in my controller. I want to query the stock table to select the list of product_id and after select , it should go to product table to display the NAME of product to the user instead of product_id .

public function getStockList()
{
    $stock = DB::table("stocks")->pluck("product_id","product_id")->all();
    $products = DB::table("products")->pluck("name")->where('id', $stock);
    return view('shop.shop')->with(['stocks' => $stocks, 
    'stock' => $stock, 'products' => $products]);
}

My PHP blade has

{!! Form::select
(
    'stock',
    ['' => 'Select'] +$stock,'',
    array(
        'class'=>'form-control',
        'id'=>'country',
        'style'=>'width:350px;'
        )
)!!}

{!! Form::select
(
    'product_id',
    [''=>'Select Supplier'] + $products, null, 
    ['class'=>'form-control']
)!!}

Basically, I don't want product_id to be displayed to the user but the product name.

Try this

public function getStockList()
{
    $stock = DB::table("stocks")->pluck("product_id");
    $products = DB::table("products")->whereIn('id', $stock)->pluck("name","id");
    return view('shop.shop')->with([
        'stocks'   => $stocks,
        'stock'    => $stock,
        'products' => $products
    ]);
}

Replace your product list select box with the following

{!! Form::select('product_id',$products,null, ['class'=>'form-control','placeholder'=>'Select Products'])!!}

you need array to pass in form

/* $product_array = ['1' => 'product 1',  '2' => 'product 2', '3' => 'product 3']; */

so in your controller

$product_array = []
  foreach($products as $product){
    $product_array[$product->id] = $product->name;
  }

return view('shop.shop')->with(['stocks' => $stocks, 
'stock' => $stock, 'products' => $products , 'product_array'=>$product_array]);

And in your view

{{!! Form::select('product_id', $product_array , null, ['class'=>'form-control'])!! }}

hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM