Abdallah Sakre
Abdallah Sakre

Reputation: 915

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.

Upvotes: 0

Views: 304

Answers (1)

mrhn
mrhn

Reputation: 18916

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

Upvotes: 1

Related Questions