Last active
June 2, 2021 10:11
-
-
Save tsmsogn/e6d8af0ad182b40ac512eaf1aa4d58fb to your computer and use it in GitHub Desktop.
Laravel: Create array for select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Database\Eloquent\Model; | |
trait Selectable | |
{ | |
public static function toSelectArray() | |
{ | |
$instance = new static; | |
$key = $instance->getKeyName(); | |
$value = $instance->getDisplayFieldName(); | |
/** @var Model $this */ | |
return static::all([$key, $value]) | |
->pluck($value, $key)->toArray(); | |
} | |
public function getDisplayFieldName() | |
{ | |
if (property_exists($this, 'displayField')) { | |
return $this->displayField; | |
} | |
} | |
} |
Nice, exactly what I was looking for!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Model
Get array for select
User::toSelectArray();