Laravel Join with two coloums

 <?php


namespace App\Http\Controllers;


use App\Models\User;

use Illuminate\Support\Facades\DB;


class UserController extends Controller

{

    public function getUserOrders()

    {

        // Using Eloquent with inner join (default)

        $usersWithOrders = User::join('orders', function ($join) {

            $join->on('users.id', '=', 'orders.user_id');

            $join->on('users.email', '=', 'orders.email'); // Additional join condition

        })->get();


        // Using DB facade with a more complex join (optional)

        $complexJoin = DB::table('users')

            ->select('users.id', 'users.name', 'orders.id as order_id', 'orders.product_id', 'orders.created_at')

            ->join('orders', function ($join) {

                $join->on('users.id', '=', 'orders.user_id');

                $join->on('users.email', '=', 'orders.email'); // Additional join condition

            })

            ->where('orders.created_at', '>', now()->subMonth()) // Filter orders from the last month

            ->get();


        return view('users.orders', compact('usersWithOrders', 'complexJoin')); // Pass data to the view

    }

}


Comments

Popular posts from this blog

Add Css And Js Files on Specific Page In laravel

Xpendy Pending