eddy1992's avatar

search columns using % like %

Hi guys I have a question , If I had to search multiple columns using eloquent query scope how will I do it . The below elquent query giving me less results when searching. Is this correct to search a string in columns in a table. Please assist.

/**
     * query scope for search string
     * @param  $query
     * @param  String $searchString 
     * @return 
     */
    public function scopeSearchString($query, $searchString)
    {   
        if(!empty($searchString)){
            return $query->where('product_name', 'like', '%'.$searchString.'%')
                    ->orWhere('product_Description', 'like', '%'.$searchString.'%')
                    ->orWhere('users_user_id', 'like', '%'.$searchString.'%')
                    ->orWhere('productNameArabic', 'like', '%'.$searchString.'%')
                    ->orWhere('productNameEnglish', 'like', '%'.$searchString.'%')
                    ->orWhere('productDescriptionArabic', 'like', '%'.$searchString.'%')
                    ->orWhere('productDescriptionEnglish', 'like', '%'.$searchString.'%');
        }
        return $query;
    }

0 likes
3 replies
JoaoPedroAS51's avatar

Try this:

$query->where(function ($q) use ($searchString)
{
    return $q->where('product_name', 'like', '%'.searchString .'%')
            ->orWhere('product_Description', 'like', '%'.$searchString.'%')
            ->orWhere('users_user_id', 'like', '%'.$searchString.'%')
            ->orWhere('productNameArabic', 'like', '%'.$searchString.'%')
            ->orWhere('productNameEnglish', 'like', '%'.$searchString.'%')
            ->orWhere('productDescriptionArabic', 'like', '%'.$searchString.'%')
            ->orWhere('productDescriptionEnglish', 'like', '%'.$searchString.'%');
});
Snapey's avatar
Snapey
Best Answer
Level 122

Looks ok, but camel case in scope names and relationships seem to trip me up sometimes. You might need to use;

public function scopeSearch_string($query, $searchString)

but otherwise it looks ok.

Are you actually getting an issue?

You probably don't need to search user_id ?

Please or to participate in this conversation.