Search code examples
phplaravellaravelcollective

Laravel collective form and foreach loop


I want to connect my dropdown select form with database, currentli I have sth like this:

                 @foreach( $clients as $client)
                    {!! Form::select('connected_with',
                     ['name' => $client->name . $client->surname
                      ]) !!}
                    @endforeach

And this is my controller:

        $clients = Client::all();

        return view('report_create')->with('clients', $clients);

and i get much fields. I want only one with items from db. How to do it?


Solution

  • If you want to create select list of clients, use pluck():

    $clients = Client::pluck('full_name', 'id');
    return view('report_create')->with('clients', $clients);
    

    To make it work, you'll also need to define an accessor in the Client model:

    public function getFullNameAttribute()
    {
        return $this->name.' '.$this->surname;
    }
    

    Then just create the list:

    {!! Form::select('connected_with', $clients) !!}