2016-07-01 24 views
6

Ho un metodo di ricerca che ricerca più modelli. Per semplicità ho aggiunto due modelli che sto cercando.Come impaginare più modelli in Laravel

Vorrei unire i due modelli per impaginare i risultati.

Ecco cosa sto facendo attualmente.

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')); 
} 

Questo funziona, ma ritengo che questo sia davvero inefficiente e potrebbe essere migliorato. C'è un modo migliore per farlo?

risposta

6

Prova questo 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 e.g. &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')); 
} 
} 

Secondo lei, search.blade.php

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

Reference

+0

C'è un bug nel codice. Dovrebbe essere slice (($ currentPage-1) * $ perPage). Altrimenti non otterrai mai i primi risultati. –

-1

È possibile selezionare "DataTables" per impaginare facilmente i dati dal lato front-end. https://datatables.net/

+0

Questo è niente a che fare con la fine del carattere. Per favore leggi di nuovo la domanda. – Enijar