Laravel 6 join clause example tutorial
In this article, We will explain to you how to use join clause in laravel 6. normally there are four types of join. 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 Clause
1 2 3 4 | $products = Product::join('categories', 'products.category_id', '=', 'categories.id') ->select('products.*') ->get(); dd($products); |
Left Join Clause
1 2 3 4 | $products = Product::leftJoin('categories', 'products.category_id', '=', 'categories.id') ->select('products.*') ->get(); dd($products); |
Right Join Clause
1 2 3 4 | $products = Product::rightJoin('categories', 'products.category_id', '=', 'categories.id') ->select('products.*') ->get(); dd($products); |
Cross Join Clause
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); |
Please follow and like us: