首页 > 解决方案 > 如何在控制器上的 html 标记中设置 if else 条件

问题描述

大家好,我想在我的控制器上使用 html 标签中的 foreach 设置我的选项

这是我的控制器:

$category = Subcategory::where('category_code', $request->category_code)->get();
$selected = 'selected';
foreach ($category as $item) {
    $html .= '<option value="'.$city->code.'" '.if($request->subcategory_code==$city->code) { echo $selected; }.' >'.$city->name.'</option>';
}

标签: htmllaravelif-statementforeach

解决方案


您可以使用三元运算符

$category = Subcategory::where('category_code', $request->category_code)->get();
foreach ($category as $item) {
    $html .= '<option value="' . $city->code . '"' . ($request->subcategory_code==$city->code ? ' selected' : '') . '>'.$city->name.'</option>';
}

推荐阅读