Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Form-Model Binding multi select default values

I'm trying to bind a default value to a select tag. (in a "edit view").

I know this should be easy, but I think I'm missing something.

I have:

User.php (my user model)

...
    public function groups() 
{
    return $this->belongsToMany('App\Group');
}

public function getGroupListAttribute()
{
    return $this->groups->lists('id');
}
...

UserController.php (my controller)

...
public function edit(User $user)
{
    $groups = Group::lists('name', 'id');

    return view('users.admin.edit', compact('user', 'groups'));
}
...

edit.blade.php (the view)

...
{!! Form::model($user, ['method' => 'PATCH', 'action' => ['UserController@update', $user->id]]) !!}
...

...
// the form should be binded by the attribute 'group_list' created
// at the second block of 'User.php'
// performing a $user->group_list gets me the correct values
{!! Form::select('group_list[]', $groups, null, [
                                'class' => 'form-control',
                                'id'    => 'grouplist',
                                'multiple' => true
                                ]) !!}
...

I did a dummy test in my blade, and have gotten the correct results:

@foreach ($user->group_list as $item)
     {{ $item }}
@endforeach

This lists the values that should be selected by default..

I also tried to put $user->group_list as third parameter from the Form::select, but this didnt work ether...

I have no clue what i'm doing wrong.. any hints on this one?

edit

when I do:

public function getGroupListAttribute()
{
    //return $this->groups->lists('id');
    return [1,5];
}

The item are correctly selected,

now i know i have to grab an array from the collection.. digging deeper.. :)

found it

User.php:

...
public function getGroupListAttribute()
{
    return $this->groups->lists('id')->toArray();
}
...

could it be easier?

Nice regards,

Kristof

like image 815
krstfvndm Avatar asked Jun 21 '15 22:06

krstfvndm


1 Answers

You shouldn't put null in the selected defaults (3rd) argument.

{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!}

{!! Form::select(
        'group_list[]',
        $groups,
        $user->group_list,
        ['multiple' => true]
    )
!!}
like image 130
ryanwinchester Avatar answered Nov 02 '22 17:11

ryanwinchester