Skip to content

Instantly share code, notes, and snippets.

@tsmsogn tsmsogn/Selectable.php
Last active Dec 9, 2019

What would you like to do?
Laravel: Create array for select
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;

This comment has been minimized.

Copy link
Owner Author

tsmsogn commented Dec 6, 2019



namespace App;

use App\Traits;
use Illuminate\Database\Eloquent\Model;

class User extends Model
    use Selectable;

    public $displayField = 'name';

Get array for select

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.