Laravel 7 Join Example Tutorial

Laravel 7 Join Example Tutorial

Laravel 7 eloquent join example. In this tutorial, you will learn how many types of joins and subquery joins in laravel and as well as how to use this joins with queries.

Sometime, you may want to get data more than two or n-tables. At that time you can use laravel join and subquery joins clauses.

Laravel Joins

Laravel provides the following types of eloquent joins:

  • Inner Join Clause
  • Left Join / Right Join Clause
  • Cross Join Clause
  • Advanced Join Clauses
  • Sub-Query Joins

Inner Join Clause

Laravel Inner Join clause selects records if the given column values matching in both tables.

When joining two tables in Laravel, you should be specific about what you are choosing.

Let’s say you have two tables, users and posts. Both have ID columns, and there is a user_id in the post, which is a foreign key for the users’ table.

$user = User::join('posts', 'posts.user_id', '=', '')

Left Join / Right Join Clause

Left Join Clause

The Laravel LEFT JOIN clause returns all rows from the left table, even if there are no matches in the right table, The result is NULL from the right side.

 User::leftJoin('posts', 'posts.user_id', '=', '')

Right Join Clause

The Laravel Right JOIN clause returns all rows from the right table, even if there are no matches in the left table, The result is NULL from the left side.

 User::rightJoin('posts', 'posts.user_id', '=', '')

Cross Join Clause

The CROSS JOIN joined every row from the first table (T1) with every row from the second table (T2).


Advanced Join Clauses

If you would like to use a “where” style clause on your joins, you may use the where and orWhere methods on a join. Instead of comparing two columns, these methods will compare the column against a value:

        ->join('contacts', function ($join) {
            $join->on('', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);

Sub-Query Joins

Consider the following example of sub query joins:

->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)->groupBy('user_id');


Laravel join tutorial, you have learned following laravel joins, inner join, left join, right join, advanced join, cross join and sub-query join.

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

Leave a Reply

Your email address will not be published. Required fields are marked *