Sfortunatamente, Laravel non offre una soluzione per questo. Dovrai farlo da solo. Ho fatto qualche ricerca e ho trovato this answer
È possibile utilizzare questa funzione e di trasformarlo in un metodo nella classe del modello ...
class Page extends Eloquent {
public static function getPossibleStatuses(){
$type = DB::select(DB::raw('SHOW COLUMNS FROM pages WHERE Field = "type"'))[0]->Type;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$values = array();
foreach(explode(',', $matches[1]) as $value){
$values[] = trim($value, "'");
}
return $values;
}
}
e si utilizza in questo modo
$options = Page::getPossibleStatuses();
Se vuoi che tu possa renderlo un po 'più universalmente accessibile e generico.
Innanzitutto, creare un BaseModel
. Tutti i modelli dovrebbero quindi estendere da questa classe
class BaseModel extends Eloquent {}
Dopo di che, mettere questa funzione in là
public static function getPossibleEnumValues($name){
$instance = new static; // create an instance of the model to be able to get the table name
$type = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$name.'"'))[0]->Type;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$enum = array();
foreach(explode(',', $matches[1]) as $value){
$v = trim($value, "'");
$enum[] = $v;
}
return $enum;
}
Si chiama questo genere
$options = Page::getPossibleEnumValues('status');
Perché non utilizzare un tratto dedicato per questo? – ozanmuyes
Certo, puoi usare un tratto se vuoi che – lukasgeiter
Laravel lo aggiunga ad ogni Classe Eloquent come Tratto –