Yajra 数据表中的 Foreach Laravel

Foreach in Yajra DataTable Laravel

我试图在我的数据表中放置一个 foreach 循环,但它不起作用, P.S。如果我删除 foreach 一切正常, 附件是我的代码

$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;

});

那行不通,您要将 foreach 附加到 string

您可以先执行 foreach 以准备要附加到该字符串中的项目。

例如,

<option>something</option>
<option>something more</option>

在设置 $return 之前执行 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;

})

您需要在 return 之外执行 foreach。然后您也不需要 use 或在数据 table 中导入 $color 变量。像这样的..

$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;

});