Get enum options values in laravel eloquent

Get enum options values in laravel eloquent

In this post, i will tell you how to get enum values of a column in a table using Laravel.

Unfortunately, Laravel does not have short method to get enum values so i use here laravel query builder to get enum values manually by writing our own custom methods.

First, define a static method within a model class so that you can easily access anywhere within application by model class name.

I suggest you to create a helper class and put this method within helper class.

Click here to know : how to create helper class in Laravel

I have created a General helper class with the help of above link and paste this method into General class.

  1. <?php
  2. class General {
  3. public static function getEnumValues($table, $column) {
  4. $type = DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[0]->Type ;
  5. preg_match('/^enum\((.*)\)$/', $type, $matches);
  6. $enum = array();
  7. foreach( explode(',', $matches[1]) as $value )
  8. {
  9. $v = trim( $value, "'" );
  10. $enum = array_add($enum, $v, $v);
  11. }
  12. return $enum;
  13. }
  14. }

Now i can get enum values of a table by calling getEnumValues method.

    $enumoption = General::getEnumValues('table_name','column_name') ;

Phone: (+91) 8800417876
Noida, 201301