0

I want to keyword search from a table and its all related table using Elequent in Laravel5. My controller is

 $clients = Client::with('contacts', 'paymentTerm', 'addressInfo');
    if ($q = Request::input("q")) {
        $clients->where("clients.name", 'LIKE', "%$q%");
        $clients->where("address_info.email", 'LIKE', "%$q%");//This is not working,I want to search from both client and client address_info
    }
    return $clients->paginate(10);

Client Model ,

 public function addressInfo() {
    return $this->hasOne('App\Model\ClientAddressInfo');
}

Client Address info,

public function client() {
        return $this->belongsTo('App\Model\Client');
    }

how can I apply keyword search here?

1 Answer 1

2

You can use whereHas to filter by a related model:

$clients->whereHas('addressInfo', function($query) use ($q){
    $query->where("email", 'LIKE', "%$q%");
});
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for answer and it is working,but the problem is two conditions are joining here with "and", how it make "or" ?
Simply use orWhereHas instead of whereHas (it works the same as with two "normal" wheres)
How can i sort from related model $clients->orderBy('addressInfo.email');?
Unfortunately that's just possible if you use a join. See this
So I need to change Elequent method to db method ?
|

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.