laravel eloquent join query example
In this article, We will explain to you how to use the join queries in laravel. normally there are four types of join queries. such as Inner Join, Left Join, Right Join, and Cross Join. but here Advanced Join and Sub-Query Join are possible using the laravel.
Normally we want to need multiple tables data that time we use the join query. so let’s see how to use join query in laravel.
Inner Join query in laravel
The Inner join query method is used to return matching rows data into both tables.
1 2 3 4 | $products = Product::join('categories', 'products.category_id', '=', 'categories.id') ->select('products.*') ->get(); dd($products); |
Left Join query in laravel
The left join query method is used to return all rows data into the left table and return the equal rows of data into the right table.
1 2 3 4 | $products = Product::leftJoin('categories', 'products.category_id', '=', 'categories.id') ->select('products.*') ->get(); dd($products); |
Right Join query in laravel
The right join query method is used to return all rows data into the right table and return the equal rows data into the left table.
1 2 3 4 | $products = Product::rightJoin('categories', 'products.category_id', '=', 'categories.id') ->select('products.*') ->get(); dd($products); |
Cross Join query in laravel
1 2 3 4 | $data = DB::table('sizes') ->crossJoin('colours') ->get(); dd($data); |
Advanced Join Clause
1 2 3 4 5 6 7 | $data = DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5); }) ->get(); dd($data); |
Sub-Query Join Clause
1 2 3 4 | $data = DB::table('posts') ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at')) ->where('is_published', true)->groupBy('user_id'); dd($data); |