Get enum options values in PHP Laravel eloquent – onlinecode

Get enum options values in PHP Laravel eloquent – onlinecode

In this post we will give you information about Get enum options values in PHP Laravel eloquent – onlinecode. Hear we will give you detail about Get enum options values in PHP Laravel eloquent – onlinecodeAnd how to use it also give you demo for it if it is necessary.

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 staticfunctiongetEnumValues($table,$column){
  4. $type= DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[]->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. }
<?php
class General {
    public static function getEnumValues($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 = array_add($enum, $v, $v);
      }
      return $enum;
    }
}

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

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

You can also use information_schema but i think this is the best solution for me to get enum values of a table column.

Hope this code and post will helped you for implement Get enum options values in PHP Laravel eloquent – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

5  +  5  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US