this my mysql query:
$tmp=almacen::select('nombre_empresa','oferta')->join('users','users.id','=','almacen.emp_id')->where('almacen.event_id','5')->get();
this returns several objects like these:
...
App\almacen {#1948
nombre_empresa: "Aux1",
oferta: "Serv_1234",
},
App\almacen {#1947
nombre_empresa: "Aux2",
oferta: "Serv 12345678",
},
...
i need to convert "nombre_empresa" in a key, for example
$tmp['Aux2']
this return:
"Serv 12345678"
Is it possible to do this in Laravel? or should I do it in another way?
Sure Laravel can handle that, check out the available collections methods. mapWithKeys
is probably what you're looking for:
$mapped = $results->mapWithKeys(function ($item) {
return [$item['nombre_empresa'] => $item['oferta']];
});
Edit: mapWithKeys
rather than map
You can use keyBy:
$tmp->keyBy('nombre_empresa');
You can chain it directly at the end of your query, after the get method.
But on this case you are only getting 2 fields from the database you can use pluck
directly on the query builder
:
$tmp=almacen::select('nombre_empresa','oferta')
->join('users','users.id','=','almacen.emp_id')
->where('almacen.event_id','5')
->pluck('oferta','nombre_empresa');
The second argument of pluck will be use for the key. If none is given it will just use numeric keys: 0, 1,...
Of course, all solutions are valid, but the way I would do it which I think is also considered to be best practice in Laravel is by using pluck()
Documentation
Example:
$tmp=almacen::select('nombre_empresa','oferta')
->join('users','users.id','=','almacen.emp_id')
->where('almacen.event_id','5')
->get()
->pluck('oferta', 'nombre_empresa')
->toArray();
Do notice that pluck()
is a new method introduced in version 5.2 to replace the before used lists()