Home > Enterprise >  How do I use LIKE predicate in asociative array laravel?
How do I use LIKE predicate in asociative array laravel?

Time:08-31

Search Controller

<?php

namespace App\Http\Controllers;

use App\Http\Resources\EmployeeListResource;
use App\Talent\Search\SearchManager;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function __construct(private SearchManager $searchManager)
    {

    }

    public function show(Request $request)
    {
        $input=$request->query();
        $search=$this->searchManager->search($input);
        return $search;
    }
}

Search Manager

<?php
namespace App\Talent\Search;

use App\Talent\Employee\Model\Employee;
use  Illuminate\Database\Eloquent\Collection;

class SearchManager
{
    public function __construct(private Employee $employee)
    {

    }
    public function search(array $input): Collection|array
    {
        return $this->employee->with('employment:employee_id,current_position,work_schedule,team')
        ->whereIn('first_name','LIKE','%'.$input.'%')->orWhereIn('last_name','LIKE','%'.$input.'%')
        ->orWhereIn('email','LIKE','%'.$input.'%')->get(['id','first_name','last_name','email','status','avatar','contact_number']);
    }
}

I am creating a API for search functionality feature where user can be searched from their name or email. Here I am taking values that need to be searched in query parameter. Without using LIKE predicate everything is working fine but I want to search from the characters as well. Here if I hit search route it shows array to string conversion error in postman how can I resolve this. I am pretty new to laravel and I don't know how should I resolve this issue,any help or suggestions will be really appriciated.

CodePudding user response:

whereIn() is used to query multiple possible values like whereIn('id', [1,2,3,4]) and expects second parameter to be an array

To use LIKE query operator, just use the usual where

class SearchManager
{
    public function __construct(private Employee $employee)
    {

    }
    public function search(array $input): Collection|array
    {
        return $this->employee
            ->with('employment:employee_id,current_position,work_schedule,team')
            ->where('first_name','LIKE','%'.$input.'%')
            ->orWhere('last_name','LIKE','%'.$input.'%')
            ->orWhere('email','LIKE','%'.$input.'%')
            ->get(['id','first_name','last_name','email','status','avatar','contact_number']);
    }
}

CodePudding user response:

Not fully sure but this might help you and also this is not the best way to do it as i think but if it solves your issue

->where(function ($query) use($input) {
        foreach($input as $value){
            $query->where('first_name','LIKE','%'.$value.'%')
        }
    })
  • Related