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!!
My Answer:
In Laravel, you can achieve this by using the `getColumnListing` method provided by the Schema facade. Here's how you can modify your code to get the column names from the select query:
php
use Illuminate\Support\Facades\Schema;
$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');
// Get the column names from the select query
$columns = collect(Schema::getColumnListing($data->getQuery()->from));
print_r($columns->toArray());
This code snippet will output an array of column names from the select query.
Rate this post
4 of 5 based on 8861 votesComments