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