skip to Main Content

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 class="mb-2">
            <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');

3

Answers


  1. Chosen as BEST ANSWER

    As @SazzadHussain suggested adding this block of code inside my model class solved the issue.

      public static function getPossibleEnumValues($table, $column) {
          $type = DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[0]->Type ;
          preg_match('/^enum((.*))$/', $type, $matches);
          $enum = array();
          foreach( explode(',', $matches[1]) as $value )
          {
            $v = trim( $value, "'" );
            $enum = Arr::add($enum, $v, $v);
          }
          return $enum;
        }
    

    After that getting it from my Controller like that:

    $enumoption = Competition::getPossibleEnumValues('competitions','status');
    

  2. 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');

    Login or Signup to reply.
  3. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search