Skip to content

Instantly share code, notes, and snippets.

@tsmsogn
Last active June 2, 2021 10:11
Show Gist options
  • Save tsmsogn/e6d8af0ad182b40ac512eaf1aa4d58fb to your computer and use it in GitHub Desktop.
Save tsmsogn/e6d8af0ad182b40ac512eaf1aa4d58fb to your computer and use it in GitHub Desktop.
Laravel: Create array for select
<?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;
}
}
}
@tsmsogn
Copy link
Author

tsmsogn commented Dec 6, 2019

Model

<?php

namespace App;

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

class User extends Model
{
    use Selectable;

    public $displayField = 'name';
}

Get array for select

User::toSelectArray();

@wvandeweyer
Copy link

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