I have the following table named mytable
:
id SERIAL PK
namae VARCHAR
And using laravel 5.7 I need to retrieve the data using the following code (tested in a tinker session):
$yakuzaNames = DB::select('SELECT id from mytable where name like 'omaewa%');
dump($yakuzaNames);
The problem is that once data retrieved in variable $yakuzaNames
is in the following format:
[ { id: 1},{id:2},...]
From the results I need to retrieve an array containing integers with the id, therefore I need to manipulate it via array_map
:
$yakuzaNames = DB::select('SELECT id from mytable where name like 'omaewa%');
$yakuzaNames = array_map(function($item){ return $item->id },$yakuzaNames);
Or use a foreach loop:
$yakuzaNames = DB::select('SELECT id from mytable where name like 'omaewa%');
$names = [];
foreach($yakuzaNames as $yakuzaName){
$names[] = $yakuzaName->id;
}
But using a loop seems kinda a waste also using some sort of iteration seems waste as well. Is there a way for laravel's database layer be able to return directly the data in the format I want to?
Use pluck method for collection. https://laravel.com/docs/8.x/collections#method-pluck