Rakesh
Rakesh

Reputation: 51

How to set old value for SELECT tag in Laravel

create.blade.php

<select  id="category" class="form-control" name="category"  required>
<option selected disabled>- Select -</option>
<option {{ old('category') == $key ? "selected" : "" }} value="{{ $value }}">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>

Error : Undefined variable: key (View: C:\xampp\htdocs\LaravelCrud_x\resources\views\create.blade.php)

Upvotes: -1

Views: 685

Answers (4)

Pjman Yucifee
Pjman Yucifee

Reputation: 121

It would be better if use @selected directive in Laravel Blade

<select name="category">
    <option>Select a category</option>
    <option value="catX" @selected( old('category') == 'catX' )> Category_X </option>
    <option value="catY" @selected( old('category') == 'catY' )> Category_Y </option>
    <option value="catZ" @selected( old('category') == 'catZ' )> Category_Z </option>
</select>

Upvotes: 1

Hector jones
Hector jones

Reputation: 11

<select name="category">
  <option value="">Select a category</option>
  <option value="1" {{ old('category', $post->category_id) == '1' ? 'selected' : '' }}>Category 1</option>
  <option value="2" {{ old('category', $post->category_id) == '2' ? 'selected' : '' }}>Category 2</option>
  <option value="3" {{ old('category', $post->category_id) == '3' ? 'selected' : '' }}>Category 3</option>
</select>

Upvotes: 1

Akbor
Akbor

Reputation: 1358

Your ans almost right only need to remove $key from this code or send this from controller

<select  id="category" class="form-control" name="category"  required>
    <option selected disabled>- Select -</option>
    <option {{ old('category') == "A"? "selected" : "" }} value="A">
    <option {{ old('category') == "B"? "selected" : "" }} value="B">
    <option {{ old('category') == "C"? "selected" : "" }} value="C">
</select>

If you use array key value this code will be different

Upvotes: 0

nakov
nakov

Reputation: 14298

I don't know where do your variables come from, but the error is pretty obvious, you don't have those variables defined anywhere in order to use them.. old value works the way you use it, but it should be with real data, for example for your other fields you can do this:

<option value="A" @if(old('category') === 'A') selected @endif>A</option>
<option value="B" @if(old('category') === 'B') selected @endif>B</option>
<option value="C" @if(old('category') === 'C') selected @endif>C</option>

Upvotes: 2

Related Questions