How to Paginate Multiple Models in Laravel

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

In Your view, search.blade.php

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

Reference

Tags:

Php

Laravel