Converting a Laravel Collection to an Array

Database Eloquent Forms

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at January 25, 2016 4:22 pm

This tip shows you how to convert a Laravel collection into an array

It's sometimes convenient to selectively use a Laravel collection within a drop-down list, but Form::select requires an array. While you could use the lists() method to retrieve just the desired array elements, this method only allows you to retrieve a maximum of two elements:

$books = Book:lists('name', 'id');

What if you wanted to use for instance three fields from the books table within your view? You'd need to instead retrieve a collection like so:

$books = Book::select('name', 'id', 'publisher')->get();

Withing your view, you can convert that collection to an array containing just the name and id fields like so:

$books->lists('name', 'id')->toArray()

<div class="form-group">
    {!! Form::label('Book') !!}<br />
{!! Form::select('book_id', $books->lists('name', 'id')->toArray(), 
        ['id' => 'book_id', 'class' => 'form-control']
    ) !!}

This is a clear case of having your cake and eating it too thanks to Laravel's flexible syntax!