1

I have a Laravel query like this but I got error like this

Undefined variable: keyword

$bookings = DB::table('bookings')
                    ->leftJoin('users', 'bookings.manager_id', '=', 'users.id')
                    ->leftJoin('projects', 'bookings.pr_project_id', '=', 'projects.id')
                    ->leftJoin('resources', 'bookings.pr_resource_id', '=', 'resources.id')
                    ->Where('unavailable','=','0')
                    ->orWhere(function ($query) {
                        $query->Where('users.name', 'LIKE', "%$keyword%")
                            ->Where('projects.project_name', 'LIKE', "%$keyword%")
                           ->Where('resources.r_name', 'LIKE', "%$keyword%");
                    })
                    ->orderBy('bookings.pr_working_date', 'desc')
                    ->paginate($perPage);

Now below query how to convert in Laravel

   select * from bookings left join users on bookings.manager_id=users.id left join projects on bookings.pr_project_id=projects.id left join resources on bookings.pr_resource_id=resources.id where unavailable='0' AND (users.name like '%One Web Series%' or projects.project_name like '%One Web Series%' or resources.r_name like '%One Web Series%')

3 Answers 3

4

You need to add the use() like this to pass the variable into the closure scope:

function ($query) use($keyword) {
Sign up to request clarification or add additional context in comments.

Comments

3

use use()-

$bookings = DB::table('bookings')
                ->leftJoin('users', 'bookings.manager_id', '=', 'users.id')
                ->leftJoin('projects', 'bookings.pr_project_id', '=', 'projects.id')
                ->leftJoin('resources', 'bookings.pr_resource_id', '=', 'resources.id')
                ->Where('unavailable','=','0')
                ->orWhere(function ($query) use($keyword){
                    $query->Where('users.name', 'LIKE', "%$keyword%")
                        ->Where('projects.project_name', 'LIKE', "%$keyword%")
                       ->Where('resources.r_name', 'LIKE', "%$keyword%");
                })
                ->orderBy('bookings.pr_working_date', 'desc')
                ->paginate($perPage);

Comments

1

You can pass the necessary variables from the parent scope into the closure with the use keyword . (i.e)

Where(function ($query) use($keyword)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.