In my laravel application I have a simple form with a dropdown.
Dropdown options are getting filled with DB data.
I want to populate my dropdown with user previously selected option on the edit.
Following is what I have done so far..
Blade
<select name="company_id" class="form-control">
@foreach($companies as $company)
@if (old('company_id') == $employee->company_id)
<option value="{{ $company->id }}" selected>{{ $company->name }}</option>
@else
<option value="{{ $company->id }}">{{ $company->name }}</option>
@endif
@endforeach
</select>
Controller.
public function edit(Employee $employee)
{
$companies = Company::all(['id','name']);
return view('employees.edit', compact('employee','companies'));
}
Employee Model
{
use HasFactory, Notifiable;
protected $fillable = [
'first_name', 'last_name', 'email', 'phone', 'company_id'
];
public function company()
{
return $this->belongsTo(Company::class);
}
}
My company table structure
Employee table structure
When I tried with these, it kept showing me the values in the dropdown on the edit but not setting the old value properly…..
3
Answers
In Laravel 9 you don’t have to use
if-else
to check the value just use the@selected()
blade function/directive.Also, we have the
@checked()
function as well:Try this as your loop:
The reason could be
typecasting
.This will never be true. You see
old
holds string values and you’re comparing it against an id which is of typeint
.So, this will work for you:
Also, there is a new directive you can use instead of conventional if-else statements
checked
: