How to split multiple models in Laravel

I have a search method that searches for multiple models. For simplicity, I have added two models that I am looking for.

I would like to combine the two models to break down their results.

This is what I am doing right now.

public function search(Request $request) { $query = $request->get('q'); $threads = Thread::where('title', 'LIKE', "%{$query}%")->get(); $posts = Post::where('body', 'LIKE', "%{$query}%")->get(); $results = array_merge($threads->toArray(), $posts->toArray()); $results = new Paginator($results, 10); return view('pages.search', compact('query', 'results')); } 

It works, but I feel that it is really inefficient and can be improved. Is there a better way to do this?

+6
source share
2 answers

Try this controller,

 <?php namespace App\Http\Controllers; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; class SearchController extends Controller { public function search(Request $request){ $query = $request->get('q'); $threads = Thread::where('title', 'LIKE', "%{$query}%")->get(); $posts = Post::where('body', 'LIKE', "%{$query}%")->get(); $searchResults = array_merge($threads->toArray(), $posts->toArray()); //Get current page form url eg &page=6 $currentPage = LengthAwarePaginator::resolveCurrentPage(); //Create a new Laravel collection from the array data $collection = new Collection($searchResults); //Define how many items we want to be visible in each page $perPage = 10; //Slice the collection to get the items to display in current page $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all(); //Create our paginator and pass it to the view $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage); return view('pages.search', compact('query', '$searchResults')); } } 

In your opinion, search.blade.php

 <?php echo $query->render(); ?> 

Link

+6
source

You can check the 'DataTables' to easily find the data from the front page of the page. https://datatables.net/

-one
source

All Articles