I'm trying to put a foreach loop inside my datatable but it wont work, P.S. if I remove the foreach everything works fine already, attached here is my code
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) {
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
'.foreach ($colors as $color){.'
<option value="test">test</option>'.}.'
</select>
</div>';
return $return;
});
That won't work, you're attaching a foreach
into a string
What you may do is perform the foreach
first to prepare the items you want to attach in that string.
E.g.,
<option>something</option>
<option>something more</option>
Before setting the $return
do the foreach
:
->addColumn('add_color', function($row) {
$options = ''
// here we prepare the options
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="'.$row->id.'">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>' . $options . '</select>
</div>';
return $return;
})
You need to perform foreach outside your return. and then you also need no use
or import the $color
variable inside your data table. something like this ..
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) use ($colors) {
$options = '';
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
</select>
</div>';
return $return;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With