How to use "enum" values in select option in laravel?

by edmond_brakus , in category: PHP Frameworks , 5 months ago

How to use "enum" values in select option in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 5 months ago

@edmond_brakus 

To use "enum" values in a select option in Laravel, follow these steps:

  1. Define an enum type in your Laravel model. For example, if you have an 'User' model with a status field that is an enum type, you can define the enum type like this:
1
2
3
4
5
6
class User extends Model
{
    use HasFactory;

    public $enumStatus = ['active', 'inactive'];
}


  1. In your form view, use the enum values in the select options. You can do this by looping through the enum values in the controller and passing them to the view:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// In your controller
$user = User::find($id);
$enumStatus = User::$enumStatus;

return view('edit', compact('user', 'enumStatus'));

// In your view
<select name="status">
    @foreach($enumStatus as $status)
        <option value="{{ $status }}" {{ $user->status == $status ? 'selected' : '' }}>{{ $status }}</option>
    @endforeach
</select>


  1. After submitting the form, you can save the selected enum value back to the database in your controller:
1
2
3
// In your controller
$user->status = $request->status;
$user->save();


By following these steps, you can use enum values in select options in Laravel and make it easier to manage and update your data.