My select box isn´t working. Trying to display on the select option the names of the table (departments) in a view. The error I get it is :
Undefined variable: department (View: C:\xampp\htdocs\project\resources\views\users\form.blade.php)
This is my controller
public function edit($userID)
{
$usuario = User::query()->findOrFail($userID);
$roles = Role::pluck('display_name','id');
$departments = Department::all();
return view('users.edit',compact('usuario','roles','departments'));
}
and my view
<select name="department_id" id="department_id" class="form-select">
{{--@foreach($departments as $department)--}}
<option value="{{$department->id}}">{{$department->name}}</option>
{{--@endforeach--}}
</select>
CodePudding user response:
<select name="department_id" id="department_id" class="form-select">
@foreach ($departments as $department)
<option value="{{$department->id}}">{{$department->name}}
@endforeach
</option>
Looping on the blade is look like this
CodePudding user response:
In Laravel Blade the syntax {{--
means that the following is commented out. In your case you commented out the iteration of your departments collection. And that the reason why $department is undefined.
Instead of {{--@foreach($departments as $department)--}}
you have to use @foreach($departments as $department)
... @endforeach
CodePudding user response:
I solve it changing the controller and without the comments
public function edit($userID)
{
$usuario = User::query()->findOrFail($userID);
$roles = Role::pluck('display_name','id');
$departments = Department::all(['id','name']);
//dd($departments);
return view('users.edit',compact('usuario','roles','departments'));
}
<select name="department_id" id="department_id" class="form-select">
@foreach ($departments as $department)
<option value="{{$department->id}}">{{$department->name}}</option>
@endforeach