user7290594
user7290594

Reputation: 23

How to build MySQL query with Laravel

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%')

Upvotes: 1

Views: 66

Answers (3)

AmalJo
AmalJo

Reputation: 106

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

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

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9853

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);

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

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

function ($query) use($keyword) {

Upvotes: 4

Related Questions