Retain selected value of select box in Laravel

Created at 06-Jul-2022 , By samar

Retain selected value of select box in Laravel

In this session, we’ll try our hand at solving the "Retain selected value of select box in Laravel" puzzle by using the computer language.

How can I retain the selected value of the select option while editing the form data in case of Laravel validation failure. I want to the selected option to be selected if validation fails while submitting a form.
  • Retain selected value of select box while editing the form in Laravel

    //Controller's method code (in controller)
    $user = User::findOrFail($id);
    $companies = Company::all();
    //Blade file (in blade) 
    <select class="form-control" name="company">
    @foreach($companies as $company)
        <option value="{{ $company->id }}" @if(old('company') == $company->id || $company->id == $user->company_id) selected @endif>{{ $company->name }}</option>

    You can display the selected option of select box by using the old helper function.

    Here we have two models User and Company. User model is used to store the user details in users table with 
    company id in company_id column which is a foreign key belongs to companies table. 
    Company model is used to store company name with company id which is primary key of the companies table.

  • Select option to be selected while creating a record in Laravel using old helper method

    <option value="{{ $company->id }}" @if(old('company') == $company->id) selected @endif>
    	{{ $company->name }}

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.