We can paginate Laravel items in several ways. The most simple is to use the
paginate method on an Eloquent query or the query builder. This method automatically takes care of the setting of the query’s ‘offset’ and ‘limit’ based on the current page that is in user’s view. Let’s see how we can use the where clause with paginate for multiple tables.
The current page is detected by default, using the value of the page query string argument on the HTTP request. Laravel automatically detects this value. It also automatically inserts into links that are generated by the paginator.
Paginate using where clause
To paginate Eloquent queries. We can use the
App\Models\User model and indicate that we plan to display 10 records per page. The syntax is nearly identical to paginating query builder result.
use App\Models\User; $users = User::paginate(10);
You may now call the
paginate method after setting the
where clauses constraint on the query.
$users = User::where('votes', '>', 100)->paginate(10);
Paginate results from multiple tables
To paginate results from multiple tables, we can use the union function. As shown below.
$address= Address::where('location','LIKE','%'.$key.'%'); $users= User::where('votes', '>', 100) ->union($address) ->paginate(10);
The above query shows combines results from two tables. It illustrates how we can use the where clause with paginate for multiple tables. The two tables here are ‘address’ and ‘user’ tables. The user table will merge with addresses using ‘union’ and results from both pass to and paginate method.