Santhosh Shet
Santhosh Shet

Reputation: 107

Laravel column alias

I am a newbie to Laravel.

I have written a controller which will join 3 table and return the rows and then on the model they will shown as table using pagination

On the model, I need to get the id of a particular table.

The problem is the id field is a common name in all tables. When i do $rec->id its is not fetching the id which i am expecting.

I tried googling on how to create an alias name for my column but it is not working and usually get some sql errors.

Can someone please suggest a solution.

-Updated code

$enquiries = DB::table('enquiries');
$enquiries = $enquiries->join('user_masters', 'enquiries.user_master_id', '=', 'user_masters.id');
$enquiries = $enquiries->join('items', 'enquiries.items_id', '=', 'items.id');

return view('enquiry', 'enquiries' => $enquiries)

I am able to get all other column values. All i want is on the model to fetch the enquiry id. But as i said, ID is present on all 3 tables. Thanks.

Solution
Since i was using paginate, i added it as below
->select(array('enquiries.id as enquiries_id','enquiries.* ','table2.* ','table3.*'));

Upvotes: 1

Views: 4119

Answers (1)

Hilmi Erdem KEREN
Hilmi Erdem KEREN

Reputation: 1999

You can use select.

<?php

$query = \DB::table('enquiries')
    ->join('user_masters', 'enquiries.user_master_id', '=', 'user_masters.id')
    ->join('items', 'enquiries.items_id', '=', 'items.id')
    ->select('enquiries.id as enquiries_id'); // and so on.

$enquiries = $query->get();

...

Upvotes: 3

Related Questions