skip to Main Content

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

enter image description here

Employee table structure

enter image description here

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


  1. In Laravel 9 you don’t have to use if-else to check the value just use the @selected() blade function/directive.

    <select name="company_id" class="form-control">
        @foreach($companies as $company)
            <option value="{{ $company->id }}" @selected(old('company_id') == $company->id)>{{ $company->name }}</option>
        @endforeach
    </select>
    

    Also, we have the @checked() function as well:

    <input type="checkbox" name="active" value="active" @checked(old('active', $user->active)) />
    
    Login or Signup to reply.
  2. Try this as your loop:

    @foreach ($companies as $company)
        <option value="{{ $company->id }}" {{ $company->id == old('company_id') ? 'selected' : '' }}>
             {{ $company->name_en }}</option>
    @endforeach
    
    Login or Signup to reply.
  3. The reason could be typecasting.

    @if (old('company_id') === $employee->company_id)
    

    This will never be true. You see old holds string values and you’re comparing it against an id which is of type int.
    So, this will work for you:

    @if ( (int)old('company_id') === $employee->company_id )
    

    Also, there is a new directive you can use instead of conventional if-else statements checked :

    @checked( old('key', $employee->key) )
    @selected( old('key') === $employee->key )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search