How can I get the column field names from a query, the actual column name needs to be returned

How can I get the column names from a query

Im using Eloquent Query builder, need to re-use the column name as header

$userlst = DB::table('users')
                ->leftJoin('address', 'users.id', '=', 'address.userid')
                ->leftJoin('usergroup', 'users.id', '=', 'usergroup.id')
                ->select (
                        'users.id AS online_user_id',
                        'users.email AS online_email_acc',
                        'users.firstname AS online_firstname',
                        'users.lastname AS online_lastname',
                        'address.address1',
                        'address.address2',
                        'address.suburb',
                        'address.citytown',
                        'address.province',
                        'usergroup.firstname',
                        'usergroup.lastname',
                        'usergroup.hoh',
                        'usergroup.cellphone',
                        'usergroup.gender',
                        'usergroup.maritalstatus',
                        'usergroup.occupation',
                        'usergroup.birthdate',
                        'usergroup.baptism',
                        'usergroup.communion',
                        'usergroup.confirmation',
                        'usergroup.holyorders',
                        'usergroup.marriage',
                )
                ->where('users.id', 1)
                ->get()
                ->toArray();

output must be

   online_user_id
   online_email_acc
   online_firstname
   online_lastname
   etc....

To alias the name of a column in Eloquent, you can use the select method on the query builder instance, passing an array of columns and their desired aliases as the argument. For example:

$query->select(
    [
        'column_1' => 'alias_1',
        'column_2' => 'alias_2',
        // etc.
    ]
);

This will select the specified columns, but with the aliases you’ve provided. You can then access these columns using the aliases you’ve defined, rather than the original column names.

1 Like