public function getProductById(Request $request)
{
$response = '';
$product = Product::find($request->productId);
$groups = Group::all();
foreach ($groups as $group) {
if ($group->id == $product->group_id) {
//exclude this record
$response .= "<option value='" . $group->id . "'>";
$response .= $group->group_name;
$response .= "</option>";
}
}
}
This is my function.I'm getting the product record by sending the product id, and from that I'm getting the relevant group record of the product.And I looped through all groups and I want to exclude the record of the group which is the group_id I got from the product table.I'm really stucked here.Apperciate your help thanks.
CodePudding user response:
I think you're looking for this:
public function getProductById(Request $request)
{
$response = '';
$product = Product::find($request->productId);
$groups = Group::all();
foreach ($groups as $group) {
if ($group->id != $product->group_id) {
//exclude this record
$response .= "<option value='" . $group->id . "'>";
$response .= $group->group_name;
$response .= "</option>";
}
}
}
CodePudding user response:
Better to not get the record in the first place
public function getProductById(Request $request)
{
$product = Product::find($request->productId);
$groups = Group::where('id','!=' $product->group_id)->get();
foreach ($groups as $group) {
$response .= "<option value='" . $group->id . "'>";
$response .= $group->group_name;
$response .= "</option>";
}
}
}
and then better to loop over groups in the blade file instead of here
@foreach($groups as $group)
<option value="{{ $group->id }}">{{ $group->name }}</option>
@endforeach