1

I would like to retrieve data matching the search string, provided, it must not belongs to current user.

if($str_search && $str_search != '' )
{
  $mandate_list = Mandate::select(array('umrn','mandate_status', 'payment_type','currency','fixed_amount','max_amount','user_id','id','debtor_bank','creditor_bank','refusal_reason'))
                        ->orWhere('id', 'LIKE', '%'.$str_search.'%')
                        ->orWhere('umrn','LIKE','%'.$str_search.'%')
                        ->orWhere('mandate_status','LIKE','%'.$str_search.'%')
                        ->orWhere('mandate_date','LIKE','%'.$str_search.'%')
                        ->orWhere('payment_type','LIKE','%'.$str_search.'%')
                        ->orWhere('currency','LIKE','%'.$str_search.'%')
                        ->orWhere('fixed_amount','LIKE','%'.$str_search.'%')
                        ->orWhere('mandate_date','LIKE','%'.$str_search.'%')   
                        ->where('user_id', '<>', $current_user) 
                        ->orderBy('updated_at', 'desc')                            
                        ->get();

}

But this query displays all records (even belongs to current user). How can i solve this. Thanks for your suggestions.

1 Answer 1

3

Group all your orWheres in a closure:

Mandate::select([.....])->where(function($query) use ($str_search)
{
    $columns = ['id', 'umrn', 'mandate_status', ...];

    foreach ($columns as $column)
    {
        $query->orWhere($column, 'LIKE', '%'.$str_search.'%');
    }
})
->where('user_id', '<>', $current_user) 
->orderBy('updated_at', 'desc')                            
->get();
Sign up to request clarification or add additional context in comments.

3 Comments

When I implement this code I am getting {"error":{"type":"ErrorException","message":"Undefined variable: str_search","file" in foreach .
You can pass the $str_search variable to the function callback using use: [....]->where(function($query) use ($str_search) {[.....]});
@NithilGeorge - updated the answer to use your $str_search variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.