ZUK88 ZUK88 - 30 days ago 9
MySQL Question

Laravel Referencing Foreign Key Data

Noob question incoming..


$data = DB::table('fquotes')->orderBy('created_at', 'DESC')->get();


I have this query which is pulling all data from fquotes. Each item has a cid which is linked to a customer id in another table. How do I include a column (name) from the customers table matching each row pulled?

I want to display the data:

customer name from customers row - fquotes row

Answer Source

Before you call get() which will execute the query, call the join() method and it will join your table on the other table by the specified column.

$data = DB::table('fquotes')
    ->select('customers.id as customer_id', 'fquotes.id as fquotes_id', DB::raw('*'))
    ->orderBy('created_at', 'DESC')
    ->join('customers', 'fquotes.cid', '=', 'customers.id')
    ->get();