hjcoder18
hjcoder18

Reputation: 479

Laravel inner join saying variable undefined

I am doing a search to filter through users that are displayed on my screen. The display of the users is working without the search. However when I type in the search a name, and go to display it, I get an undefined variable for search.

    $Search = $request->search_code; //print_r($Search);die(); // this works
    // this next line was used for testing and it works as well
    //$findTrainers = DB::table('users')->where('users.name', 'like', "%$Search%")->get();

    // This is what we want to work, but the search variable is now undefined
     $findTrainers = DB::table('users')
            ->join('bios', function ($findTrainers) {
                $findTrainers->on('users.id', '=', 'bios.user_id')
                ->where('users.name', 'like', "%$Search%");
            })
            ->get();

Upvotes: 2

Views: 624

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50798

This is due to how closures and scoping work. Closures don't know about variables defined outside of their scope, so you must tell a closure to use that variable when you want to access it within the scope of the closure, like this:

$findTrainers = DB::table('users')
    ->join('bios', function ($findTrainers) use ($Search){
        $findTrainers->on('users.id', '=', 'bios.user_id')
            ->where('users.name', 'like', "%$Search%");
    })
    ->get();

Upvotes: 3

Related Questions