How to query from two database tables with a condition in Laravel

Laravel framework offers easy database in application manipulation like creating and using a migration file. It also allows you to join two tables in a query when you need data from two or more tables. For example, let’s say you have tables for users and their orders. If you join these tables, you can generate a useful report for the admin, such as how many orders each user has made. Let’s learn how we can query from two database tables with a condition in Laravel.

Joining tables also allows you to retrieve a result from multiple tables as if they are one. In this shot, we will learn how to use the join() method.

The join() method

The join() method is part of a query builder and is used to carry out the table joining table operation in Laravel.


$users = DB::table('users')
            ->join('contacts', '', '=', 'contacts.user_id')
            ->join('orders', '', '=', 'orders.user_id')
            ->select('users.*', '', 'orders.price')


The join() method receives multiple parameters:

  1. The table to be joined
  2. Optional constraints for the join


$usersDetails = DB::table('users')
            ->join('contacts', '', '=', 'contacts.user_id')// joining the contacts table , where user_id and contact_user_id are same
            ->select('users.*', '')

return $usersDetails;


In the example above, we perform the join from a controller and import the DB class.


We first get users, which is our primary table, i.e., the table that relates to the other tables we want to join. Then, we chain users to the join() method. In this case, the first parameter or table we want to join to the users table is the contacts table. '', '=', and 'contacts.user_id' are constraints and they mean joining the contacts table, where user_id and contact user_id are same. We then use the select method to filter the columns we need for the application. We also chain the get() method, which retrieves the query results for us. Finally, we return the retrieved query from two database tables.

Leave a Comment