How to pass a variable in join query in laravel?

Member

by domenico , in category: PHP Frameworks , 3 months ago

How to pass a variable in join query in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 3 months ago

@domenico 

In Laravel, you can pass a variable in a join query by using the DB facade to manually write the SQL query. Here's an example of how to pass a variable in a join query:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use IlluminateSupportFacadesDB;

$userId = 1;

$result = DB::table('posts')
            ->join('users', function($join) use ($userId) {
                $join->on('posts.user_id', '=', 'users.id')
                     ->where('users.id', '=', $userId);
            })
            ->select('posts.*', 'users.name')
            ->get();


In this example, we are joining the posts table with the users table on the user_id and id columns, and we are using the $userId variable to filter the users. You can pass any variable to the join query using the use ($variable) syntax within the closure function.


Alternatively, you can also use Eloquent relationships to achieve the same result:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

$userId = 1;

$posts = Post::with('user')->whereHas('user', function($query) use ($userId) {
                $query->where('id', $userId);
            })->get();


This will eager load the user related to each post and filter the posts based on the user's id.