Laurenswuyts
Laurenswuyts

Reputation: 2142

Variable not recognized in function, laravel

This is my code:

public function userprofile($id)
{
    $users = DB::table('users')->where('username', $id)->get();

    $myposts = DB::table('posts')->where('maker', $id)->get();

    $user_id = $id;

    $postsvotes = DB::table('posts')
    ->join('upvotes', function($join)
    {
        $join->on('post_id', '=', 'upvotes.post_id')
             ->where('upvotes.user_id', $user_id);
    })
    ->get();

    return View::make('users.profile')->with('users', $users)->with('myposts', $myposts)->with('myvotes', $postsvotes);
}

I'm working with a join and as you can see in the where I have this variable $user_id and this should be the $id you get as an argument from the function userprofile($id) but I can't seem to get that argument into that where clause.

Regards,

Upvotes: 0

Views: 114

Answers (1)

Mikk
Mikk

Reputation: 2229

Go ahead and try (notice the use ($user_id) part):

->join('upvotes', function($join) use ($user_id)
{
    $join->on('post_id', '=', 'upvotes.post_id')
         ->where('upvotes.user_id', $user_id);
})

This probably is a variable scoping problem. See Example #3 Closures and scoping from http://php.net/manual/en/functions.anonymous.php

Upvotes: 2

Related Questions