简体   繁体   中英

Object of class Illuminate\Database\Query\Builder could not be converted to string in Laravel

I'm trying to add orwhere using the below syntax for searching:

->where(function($query) {
    $query->where(DB::raw("g.title"), 'LIKE', "%{$query}%");
    $query->orWhere(DB::raw("s.step"), 'LIKE', "%{$query}%");
})

but I'm receiving the below error

Object of class Illuminate\Database\Query\Builder could not be converted to string

It is working fine if I used the normal syntax as below:

->where(DB::raw("g.title"), 'LIKE', "%{$query}%")
->orwhere(DB::raw("s.step"), 'LIKE', "%{$query}%")

But I will add another where condition, so I have to use the first syntax.

You are defining $query twice. Both in your where() Closure and as a value. Also when you use closures and what to access values from outside the scope you have to use the use() statement. This code is not included but i assume it looks something similar to this and will work like that.

// replace this with whatever $query is in your code, from outside the closure scope
$search = $request->get('query');

Model::query()
    ->where(function($query) use ($search) {
        $query->where(DB::raw("g.title"), 'LIKE', "%{$search}%");
        $query->orWhere(DB::raw("s.step"), 'LIKE', "%{$search}%");
    })
    ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM