skip to Main Content

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?

2

Answers


  1. 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 and orWhereRaw 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

    Login or Signup to reply.
  2. 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').'%');
       })
       ..// ;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search