Laravel 5.3 select pluck method

michal picture michal · Jan 26, 2017 · Viewed 9.8k times · Source

Controller method:

public function edit($id){

    $match2 = Match::pluck('team_a_id', 'id');
    return view('admin.accept.edit', compact('match2'));

}

And view file:

{{ Form::select('matches_id', $match2, null, ['class' => 'form-control']) }}

And my table:

Table from model Match (table name: matches):

enter image description here

Table from model Team (table name: teams):

enter image description here

Table teams is connected (references) with table matches( team_a_id and team_b_id is connected with table teams). The select method with view returned me only ID with tables:

enter image description here

I need have team_name with table teams not id. When I change method pluck:

$match2 = Match::pluck('id', 'id');

And view:

 {{ Form::select('matches_id', Team::find($match2)->team_a_id." vs. ".Team::find($match2)->team_b_id, null, ['class' => 'form-control']) }}

Laravel returned error:

Invalid argument supplied for foreach() (View: C:\xampp\htdocs\football\football\resources\views\admin\accept\edit.blade.php)

This is metohd edit so I must have highlighted record that was previously selected.

Answer

michal picture michal · Jan 26, 2017

Ok I repair this. I write method:

public function edit($id){

    $match = Match::select()->orderBy('updated_at', 'asc')->get();
    $selectedMatch = DB::table('usermatches')->find($id)->matches_id;

    return view('admin.accept.edit', compact('match', 'selectedMatch'));

}

And view:

  <select name="matches_id" id="matches_id" class="form-control selectpicker" data-live-search="true" data-size="5">
    <option value=0>Wybierz wydarzenie</option>
      @foreach($match as $role)
          <option value="{{ $role->id }}" {{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}>
            {{ Team::find($role->team_a_id)->team_name }} vs. {{ Team::find($role->team_b_id)->team_name }} ({{$role->date}}; <?php echo date('G:i',strtotime($role->time)); ?> | Liga {{ League::find($role->league_id)->name }} | {{ Sport::find($role->sport_id)->name }}) 
          </option>  
      @endforeach
  </select>

In model view I compare id with two tables and it working ;)

{{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}