I know that Laravel has a wonderfully useful lists() method that you can use with either Eloquent or Fluent to return an array of values from a database table. Even better, you can use the second argument in that method to pair the values with keys from the table.
The problem is, lists() only lets you return one column from the table. What if you want to return more than one value?
I know you can use select() but that still doesn't populate the array keys with, say, IDs from the table.
So let's assume I have a "heroes" table (this is just a silly made-up example), with columns named id, firstname and lastname (and, of course, created_at and updated_at). I know I can do this:
$heroes = Hero::lists('firstname', 'id');
But how do I include lastname?
Basically what I'd like to end up with is this:
$heroes = array('12' => array('firstname' => 'James', 'lastname' => 'Bond'), '44' => array('firstname' => 'Indiana', 'lastname' => 'Jones'));
So that I can do this kind of thing:
$hero1 = $heroes[12']['firstname'] . ' ' . $heroes[12']['lastname'];
I know you can do this:
$heroes = Hero::whereIn('id', array(12, 44))->orderBy('lastname', 'asc')->get()->toArray();
But the keys in this array are 0 and 1, not 12 and 44.
This seems so simple and yet I seem to be having difficulty. Thanks.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community