0

I made a searchScope in one model. This is working perfectly. But i need to make this search field for multiple models. When i search a string it must scan other tables. What i have done so far:

public function scopeSearch(Builder $query, $search)
{
    $query->whereHas('translations', function ($q) use ($search) {
        $q->where('value', 'like', '%' . $search . '%');
    })
        ->orWhere('title', 'LIKE', '%' . $search . '%')
        ->orWhere('sub_body', 'like', '%' . $search . '%')
        ->orWhere('body', 'like', '%' . $search . '%');
}

Translation table has all other model's translated values. Thats good. Because i just want to add 2-3 extra models in this query. How can i do that? Thanks in advance.

1 Answer 1

1

One way of doing it is that you can start your search with parent table and then go along. like if you want to search in posts, comments and their replies at the same time then you can start from the parent table i.e posts.

public function scopeSearchGlobal($query, $search){
   $query->where('body', 'LIKE', '%' . $search . '%');
   $query->with(['comments', function($comment) use ($search){
       $comment->where('comment', 'LIKE', '%' . $search . '%');
       $comment->with(['replies' => function($reply) use ($search){
           $reply->where('reply', 'LIKE', '%' . $search . '%');
       }]);
   }]);
}

Remember that this search is for tables that are co related. This is a general idea to search for multiple tables. But if you have translations table and it has all other models translated values then you can just search just the translations table and call every relation in with.

public function scopeSearch($query, $search)
{
   $query->whereHas('translations', function ($q) use ($search) {
    $q->where('value', 'like', '%' . $search . '%');
   })->with('posts', 'blogs', 'comments', 'replies'); 
   // define relations that are associated with translations model and call 
      them here. So it will search just the translations table and brings all 
      associated results
}

Hope this helps :)

Sign up to request clarification or add additional context in comments.

Comments

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.