0
0
Laravelframework~5 mins

Join operations in Laravel

Choose your learning style9 modes available
Introduction

Join operations let you combine data from two or more database tables into one result. This helps you see related information together easily.

You want to show a list of orders with customer names.
You need to display posts along with their authors' details.
You want to find products and their categories in one query.
You want to get all users and their roles in a single result.
Syntax
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.

Examples
Get all posts with the name of the user who wrote each post.
Laravel
DB::table('users')
  ->join('posts', 'users.id', '=', 'posts.user_id')
  ->select('users.name', 'posts.title')
  ->get();
Get all orders and customer names. Orders without customers still appear.
Laravel
DB::table('orders')
  ->leftJoin('customers', 'orders.customer_id', '=', 'customers.id')
  ->select('orders.id', 'customers.name')
  ->get();
Show products with their category names.
Laravel
DB::table('products')
  ->join('categories', 'products.category_id', '=', 'categories.id')
  ->select('products.name', 'categories.name as category')
  ->get();
Sample Program

This code gets all posts with the user names who wrote them. It prints each user and their post title on a new line.

Laravel
<?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";
}
OutputSuccess
Important Notes

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.

Summary

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.