Distinct values with pluck

Arlind Hajdari picture Arlind Hajdari · Feb 24, 2017 · Viewed 28.4k times · Source

I'm trying to retrieve data from database and bind them to a html select tag, and to bind them i need to use pluck so i get the field i want to show in a array(key => value), because of FORM::select. The normal pluck gets all the results, while i want to use distinct. My model is Room and it looks like:

    class Room extends Eloquent
{
    public $timestamps = false;

    protected $casts = [
        'price' => 'float',
        'floor' => 'int',
        'size' => 'float'
    ];

    protected $fillable = [
        'capacity',
        'description',
        'price',
        'floor',
        'size',
        'type',
        'photo_name'
    ];
}

While my function I'm using in the controller look like:

public function getRooms()
    {
        $roomType = Room::pluck('type','type');
        $roomFloor = Room::pluck('floor','floor');

        return view('roomgrid')->with('type',$roomType)->with('floor',$roomFloor);
    }

And my view contains this piece of code to get floors:

{{FORM::select('floor', $floor, null,['class'=>'basic'])}}

Like this i get duplicated floors, that i don't want. Is there any way so i can get distinct floors and pluck them? Thanks in advance.

Answer

Buglinjo picture Buglinjo · Feb 24, 2017

Why not use groupBy()?

$roomType = Room::groupBy('type')->pluck('type','type');