I'm trying to send an array of my Model Role
to Blade like this:
public function create()
{
$roles = Role::pluck('name','id');
return view('admin.users.create', compact(['roles']));
}
And on the Blade, I added this:
<div class="form-group">
{!! Form::label('roles', 'Role:') !!}
{!! Form::text('roles[]', $roles, null, ['multiple' => 'multiple', 'class' => 'form-control']) !!}
</div>
Now I get this error:
ErrorException Cannot use a scalar value as an array on create.blade.php
However, when I add {{ dd($roles) }}
, I get this as result:
Illuminate\Support\Collection {#1155 ▼
#items: array:1 [▼
1 => "Manual User"
]
}
So what is going wrong here ? How can I fix this issue ?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
The issue is that you are not supposed to get 2 columns of values using the method ->pluck()
, pluck is used to retrieve a single column of value (https://laravel.com/docs/8.x/queries#retrieving-a-list-of-column-values). If you want to retrieve 2 columns from the model, you could try using the ->select()
method instead:
$roles = Role::select('id', 'name')->get();