Ad

Eloquent Where Condition AND ( Condition OR Condition OR Condition )

- 1 answer

Can somebody tell me what am I doing wrong? I want to get all projects with status 0 and if any of data matches in eloquent. My code is like this

public function search(Request $request){
        if($request->has('q')){
            
            $search_query = $request->input('q');

            $projects = Project::where(['status' => '0'])->get();

            $projects = $projects->where(function($query) use ($search_query) {
                $query->where('title','LIKE','%'.$search_query.'%')
                      ->orWhere('shortDescription','LIKE','%'.$search_query.'%')
                      ->orWhere('longDescription','LIKE','%'.$search_query.'%')
                      ->orWhere('tags','LIKE','%'.$search_query.'%')
                      ->orWhere('projectLink','LIKE','%'.$search_query.'%');
            });
            $projects->get();

            dd($projects);
         }
}

And I am getting this error

ErrorException
explode() expects parameter 2 to be string, object given

Ad

Answer

I solved the problem but changed the code a little bit... If you like, take it! I tested and it's working.

if($request->has('q')){

        // Your $request->q Value
        $term = $request->q;

        $projects = DB::table('tbl_projects')->where('status', '=', 0) 
                    ->where(function ($query) use ($term) {
                        $query->where('title', 'LIKE', '%'.$term.'%')
                        ->orWhere('shortDescription', 'LIKE', '%'.$term.'%')
                        ->orWhere('longDescription', 'LIKE', '%'.$term.'%')
                        ->orWhere('tags', 'LIKE', '%'.$term.'%')
                        ->orWhere('projectLink', 'LIKE', '%'.$term.'%');
                   })
                   ->get();

        //dd($projects);
    }

Raw query is:

select * from `tbl_projects` where `status` = 0 and (`title` LIKE %bla bla% or `shortDescription` LIKE %bla bla% or `longDescription` LIKE %bla bla% or `tags` LIKE %bla bla% or `projectLink` LIKE %bla bla%))

Regards!

Ad
source: stackoverflow.com
Ad