Laravel 8 Get Column Names from Select Query

Viewed 944

I want to get column names from a select query example:

$data = RoomModel::from('rooms as a')
    ->where('a.id', 1)
    ->where('a.isdelete', 0)
    ->join('roomclass as b', 'a.roomclass_id', 'b.id')
    ->join('nursestation as c', 'a.nursestation_id', 'c.id')
    ->select('a.id as ID', 'a.description as Description', 'b.customdesc as Room Class', 'c.customdesc as Nurse Station', 'a.isactive as Status');

Which will have a result of

array('ID','Description','Room Class', 'Nurse Station', 'Status')

This can be achieved using code igniter by using field_list:

$sql = "
    SELECT
    id as `ID`, 
    description as `Description`, 
    customdesc as `Nurse Station`,
    isactive as `Status`
    FROM mytable";

$query = $this->db->query($sql);
print_r($query->field_list());

which I can't find in Laravel.

Thanks in advance!!

2 Answers
    $data = RoomModel::from('rooms as a')
                            ->where('a.id', 1)
                            ->where('a.isdelete', 0)
                            ->join('roomclass as b', 'a.roomclass_id', 'b.id')
                            ->join('nursestation as c', 'a.nursestation_id', 'c.id')
                            ->limit(1)->get('a.id as ID', 'a.description as Description', 'b.customdesc as Room Class', 'c.customdesc as Nurse Station', 'a.isactive as Status');

$attr = array_keys($data->getAttributes());

When using the model class to create a new query you will get an instance of Illuminate\Database\Eloquent\Builder (or a class derived from it).

To get the columns used in the select you need the query from within the builder:

$data = RoomModel::from('rooms as a')
    ...
    ->select('a.id as ID', 'a.description as Description', 'b.customdesc as Room Class', 'c.customdesc as Nurse Station', 'a.isactive as Status');

$columns = $data->getQuery()->columns;

If you are not using Eloquent, and have an instance of Illuminate\Database\Query\Builder you can get the columns property without the getQuery() call:

$data = DB::table('rooms as a')
    ...
$columns = $data->columns;

which will result in $columns being set to the array:

[
  "a.id as ID",
  "a.description as Description",
  "b.customdesc as Room Class",
  "c.customdesc as Nurse Station",
  "a.isactive as Status",
]

Unfortunately the alias are not resolved for you, even if you execute the query.

Related