Home > Software engineering >  Old value not setting properly on laravel 9 blade dropdown
Old value not setting properly on laravel 9 blade dropdown

Time:10-17

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" >
                            @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.....

CodePudding user response:

Try this as your loop:

@foreach ($companies as $company)
    <option value="{{ $company->id }}" {{ $company->id == old('company_id') ? 'selected' : '' }}>
         {{ $company->name_en }}</option>
@endforeach

CodePudding user response:

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 )

CodePudding user response:

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" >
    @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)) />
  • Related