Laravel eloquent search query for two foreign tables

i have a question about the code above , i want to search with criteria from 2 extra tables
I want ‘charge’ from charges table , ‘name’ from user table and also ‘name’ from customer table
all has binds the above query runs but the doesnt fetch data from customers->name any idea how to make it work?

public function scopeSearch($query, $val){
    return $query->has('customer')
        ->whereHas('user', function($query) use ($val) {
            $query->where('tasks','like','%'.$val.'%')  
                ->Orwhere('name','like','%'.$val.'%');      
       })
       ->with('user')
       ->with('customer');
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can follow the documentation about adding stuff to your relation query (whereHas).

So, you should have this:

public function scopeSearch($query, $val){
    return $query->with(['user', 'customer'])
        ->whereHas('user', function($query) use ($val) {
            $query->where('tasks','like','%'.$val.'%')  
                ->Orwhere('name','like','%'.$val.'%');      
       })
       ->whereHas('customer', function($query) use ($val) {
           $query->where('name','like','%'.$val.'%');
       });
}

See that you had only used whereHas for users but not customers

Method 2

Finally worked! after some research i found that the problem was my using of or statement
the code above works for me:

  public function scopeSearch($query, $val){
    return $query->whereHas('user', function($query) use ($val) {
        $query->where('tasks','like','%'.$val.'%')
                ->orWhere('name','like','%'.$val.'%');
    })
        ->orWhereHas('customer', function($query) use ($val) {
            $query->where('name', 'LIKE', '%'.$val.'%');
        })
        ->with('user', 'customer');
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x