I used this old code, and start refactor it with use of laravel/scout
.
This code is a simply search function thet search in posts and pages too, and show result mixed paginate.
Old code:
public function search($term) {
$post = Post::where('title', 'LIKE', $term);
$page = Page::where('content', 'LIKE', $term);
$result = $page->union($post)->orderBy('created_at')->paginate();
return $result;
}
New Code not working:
public function search($term) {
$post = Post::search($term);
$page = Page::search($term);
$result = $page->union($post)->orderBy('created_at')->paginate();
return $result;
}
get error: Method Laravel\Scout\Builder::union does not exist.
What is the best syntax for this problem?
My Answer:
To search with multiple models using Laravel Scout, you can use the `searchable` trait in your models and then use the `search` method to perform the search. However, the `union` method is not available in the Scout builder.
One way to achieve the desired result is to perform separate searches for each model and then merge the results manually. Here's an example of how you can do this:
php
use Illuminate\Support\Collection;
public function search($term) {
$postResults = Post::search($term)->get();
$pageResults = Page::search($term)->get();
$mergedResults = $postResults->merge($pageResults)->sortBy('created_at')->paginate();
return $mergedResults;
}
In this code snippet, we first perform separate searches for posts and pages using the `search` method. Then, we use the `merge` method from the `Collection` class to merge the results into a single collection. Finally, we use the `sortBy` method to sort the merged results by the `created_at` attribute and then paginate the results.
This should help you achieve the desired functionality of searching with multiple models using Laravel Scout.
Rate this post
5 of 5 based on 5217 votesComments