Skip to content
Advertisement

Laravel Query with Implode

i have an array with values

Array
(
    [0] => Python
    [1] => PHP
    [2] => MySQL
)

So i want search these three items from tables using like query

$employees = DB::table('audit_employee_basics')
                    ->select('audit_employee_basics.id as empid', 'emp_name', 'emp_code', 'designation_name', 'emp_company_email_id', 'emp_contact_number', 'emp_gender', 'emp_location'
                            , 'department_name', 'emp_joining_date', 'fk_emp_previous_exp', 'image')
                    ->join('audit_department', 'audit_employee_basics.emp_fk_dep', '=', 'audit_department.id')
                    ->join('audit_employee_skillset', 'audit_employee_skillset.fk_emp_id', '=', 'audit_employee_basics.id')
                    ->join('audit_designation', 'audit_designation.id', '=', 'audit_employee_basics.emp_fk_des_id')
                    ->where('primary_skill ', 'like', '%' .  implode("' OR primary_skill LIKE '%", $skill_name) .'%')
                    ->distinct()
                    ->get();

I tried where('primary_skill ', 'like', '%' . implode("' OR primary_skill LIKE '%", $skill_name) .'%') which is not working for me.Any help would be highly appreciated.

Advertisement

Answer

->where(‘primary_skill ‘, ‘like’, ‘%’ . implode(“‘ OR primary_skill LIKE ‘%”, $skill_name) .’%’)

Above line is incorrect since you can’t inject multiple where inside a single where condition. QueryBuilder will just take that as a string for comparison.

You can use regexp to match each value with a regular expression created from your $skill_name array as

->where('primary_skill ', 'regexp', '(' .  implode("|", $skill_name) .')')

This would get compiled as

 where primary_skill regexp '(Python|PHP|MySQL)'
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement