Home > front end >  Enum field filtration in Laravel
Enum field filtration in Laravel

Time:01-13

I need to add a drop-down menu that filtrates with enum values from the table. Instead of that it gets the values from the rows. Any and all help gratefully received.

This is what I have managed to get so far.

View:

<div>
    <span>
        <select >
            <option value="Status" disabled selected>Status</option>
                @foreach ($status_filter as $key => $status)
                   <option value="{{ $key }}">
                    {{$status}}
                   </option>
                @endforeach
        </select>
    </span>
</div>

Controller:

 $status_filter = Competition::pluck('status');
        $request->flash();
        return view('competition.index', compact('competitions', 'status_filter'));

This is what I need to get from the migration:

$table->enum('status',['inactive','to_push','active'])->default('inactive');

CodePudding user response:

If i got it right you want to make a filter for status like listing all active ou inactive. I think the easiest way to do this is add a query on your variable $status_filter on the controller. Something like: $status_filter = Competition::where('status', 'active')->pluck('status');

CodePudding user response:

You can grab those enum values from the table. But there is no direct way. You have to use laravel query builder using raw.

$statusValues = DB::select(DB::raw("SHOW COLUMNS FROM competitions WHERE Field = 'status' "))[0]->Type;
$matches = array();
preg_match('/^enum\((.*)\)$/', $statusValues, $matches);
$enumValues = array();
foreach( explode(',', $matches[1]) as $value )
{
  $v = trim( $value, "'" );
  $enumValues = $v;
}

print_r($enumValues)
  • Related