Join operations let you combine data from two or more database tables into one result. This helps you see related information together easily.
Join operations in Laravel
DB::table('table1') ->join('table2', 'table1.column', '=', 'table2.column') ->select('table1.*', 'table2.column') ->get();
The join method combines rows where the columns match.
You can use leftJoin to include all rows from the first table even if no match in the second.
DB::table('users') ->join('posts', 'users.id', '=', 'posts.user_id') ->select('users.name', 'posts.title') ->get();
DB::table('orders') ->leftJoin('customers', 'orders.customer_id', '=', 'customers.id') ->select('orders.id', 'customers.name') ->get();
DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.id') ->select('products.name', 'categories.name as category') ->get();
This code gets all posts with the user names who wrote them. It prints each user and their post title on a new line.
<?php use Illuminate\Support\Facades\DB; $results = DB::table('users') ->join('posts', 'users.id', '=', 'posts.user_id') ->select('users.name', 'posts.title') ->get(); foreach ($results as $row) { echo "User: {$row->name}, Post: {$row->title}\n"; }
Always specify the columns to avoid confusion when tables have columns with the same name.
Use leftJoin if you want to keep all rows from the first table even if no matching row in the second.
Joins can slow down queries if tables are large, so use indexes on join columns for better speed.
Join operations combine rows from two tables based on matching columns.
Use join for inner joins and leftJoin to keep all rows from the first table.
Always select needed columns and be mindful of performance.