1

I created this new Laravel component, how can I use a custom foreach using {{ $name }} blade variable?

View -> Components

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();
    }

}

resources -> components

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

-> Views

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

Thanks :)

edit: I solved this even though I would like to have a better solution

<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>
shaedrich
  • 5,457
  • 3
  • 26
  • 42
cloude
  • 338
  • 5
  • 18
  • 1
    Just a tip: There's an easier way to make a slug out of your `$name` value. You can use Laravel's Str helper. Instead of `{{ strtolower(str_replace(" ", "_", $name)) }}` try `{{ Str::snake($name) }}`. – dhnwebpro Jul 10 '20 at 20:36
  • Thank you very much :) – cloude Jul 15 '20 at 19:32

0 Answers0