1

我创建了这个新的 Laravel 组件,如何使用 {{ $name }} 刀片变量来使用自定义 foreach?

查看 -> 组件

class SearchDropdownField extends Component
{

    public $name;

    public function __construct($name = 'name text')
    {

        $this->name = $name;

    }

    public function render()
    {

        $status1 = $this->getStatus1();
        $status2 = $this->getStatus2();

        return view('components.search-dropdown-field', ['status1' => $status1, 'status2' => $status2);

    }

    public function getStatus1()
    {
        return Status1::orderBy('title')->get();
    }

    public function getStatus2()
    {
        return Status2::orderBy('title')->get();
    }

}

资源 -> 组件

<select class="form-control" name="{{ strtolower(str_replace(" ", "_", $name)) }}" id="{{ strtolower(str_replace(" ", "_", $name)) }}">
    @foreach($status1 as $item) // <-- How can I use {{ $name }} instead $status1 ?
       <option> {{ $item->nome }}</option>
    @endforeach
</select>

-> 意见

<x-search-dropdown-field :name="'Status1'" />

谢谢 :)

编辑:我解决了这个问题,即使我想有一个更好的解决方案

<select class="form-control" name="{{ strtolower(str_replace(" ", "_", $name)) }}" id="{{ strtolower(str_replace(" ", "_", $name)) }}">

    @if($name == 'Status1')
        @foreach($status1 as $item)
            <option> {{ $item->nome }}</option>
        @endforeach
    @endif

    @if($name == 'Status2')
        @foreach($status2 as $item)
            <option> {{ $item->nome }}</option>
        @endforeach
    @endif
</select>
4

0 回答 0