phplaraveldistinctlaravelcollectivepluck

Distinct values with pluck


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?


Solution

  • Why not use groupBy()?

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