D. Look
D. Look

Reputation: 111

Laravel 5: Sending/saving data from multiple select option

I'm having trouble to get all data (options) selected in multiple select dropdown. Here is the blade code:

<div class="form-group">
    <select name="roles[]" class="form-control select2 select2-hidden-accessible" multiple="" data-placeholder="User roles" style="width: 100%;" tabindex="-1" aria-hidden="true">
        @foreach ($roles as $role)
            <option value="{{$role->name}}">{{$role->display_name}}</option>
        @endforeach
    </select>
</div>

That's how I get all "roles" listed, I have like seven of them in database and one should be able to select as much as one wants.

Here is the part in the controller:

$input = Input::all();
$roles[] = $input["roles"];
foreach ($roles as $role) {
    echo $role; //this is just for testing purposes
}

But, only last one in that array is being showed. So if I select "admin, moderator, subscriber" it will only show "subscriber". Please help me, it's obvious I'm missing some small detail.

Upvotes: 0

Views: 2584

Answers (2)

D. Look
D. Look

Reputation: 111

So the problem was double array I had both name of the select tag and var in the controller with "[]" indicating they are array, removing "[]" from $roles[] in controller solved it.

In case anyone needs this:

$input = Input::all();
$roles = $input["roles"]; // removed brackets
foreach ($roles as $role) {
    echo $role; // this is just for testing purposes
}

Upvotes: 0

Hedegare
Hedegare

Reputation: 2047

I'm sorry I can't test this answer right now. Try:

$roles = Input::get('roles');
foreach ($roles as $role) {
    echo $role; //this is just for testing purposes
}

Upvotes: 1

Related Questions