I'm working with Laravel 5.8 and I have this method:
public function getCourseDefinition()
{
$course_definition = DB::table('getCourseDefinition');
if (request()->has('cod_title') && request('cod_title'))
$course_definition = $course_definition->whereRaw("cod_title = ?", [request('cod_title')]);
}
So it basically checks if the request contains cod_title
, then searches for that particular request('cod_title')
.
But now I need to add LIKE
for returning similar results based on the entered input.
So I tried this instead:
$course_definition = $course_definition->whereRaw("cod_title = ?", 'LIKE', [request('cod_title')]);
But got this error:
Array to string conversion
So whats going wrong here?
How can I add LIKE
to this search query?
CodePudding user response:
whereRaw
only takes two arguments.
Define like this
$course_definition = $course_definition->whereRaw("cod_title LIKE ?", ['%' . request('cod_title') . '%']);
From the Laravel Docs
The
whereRaw
andorWhereRaw
methods can be used to inject a raw "where" clause into your query. These methods accept an optional array of bindings as their second argument
CodePudding user response:
You can also use where
eloquent method like so:
public function getCourseDefinition()
{
$course_definition = DB::table('getCourseDefinition')
->when(request()->has('cod_title') && request('cod_title'), function($query){
$query->where('cod_title', 'like', '%'.request('cod_title').'%');
})
..// ;
}