ronon's avatar
Level 9

hydrateRaw/fromQuery with pagination?

I currently found out that you can hydrate an Raw sql query.

I have following query:

DB::table(DB::raw('(SELECT *, Y(location) AS longitude, X(location) AS latitude FROM meetings WHERE MBRCONTAINS(@quadrat, location)) AS sub'))
            ->select(DB::raw('(FLOOR(SQRT(POW((@ibk_breite - sub.latitude) * 111, 2) + POW((@ibk_laenge - sub.longitude) * 111 * ABS(COS(RADIANS(@ibk_breite))),2)))) AS distance, sub.*, latitude, longitude'));

which I hydrate as following

$meetings = Meeting::fromQuery($query->toSql());

Now I need the pagination. Normally you would do sth. like $meetings = $query->paginate(5); and $meetings->withPath('home');

But I receive an Method withPath does not exist. exception. What am I doing wrong?

0 likes
2 replies
spekkionu's avatar
Level 48

The withPath is on the paginator instance.

You might need to manually create an instance of the paginator. This would mean would need to calculate the total number of records as well as add the limit and offsets to the query to pull only the current page of data.

$mettings = new \Illuminate\Pagination\LengthAwarePaginator($meetings, $total, $per_page);

Alternatively you could use the paginate method on the query before hydrating the model, then pulling the items from the paginator and hydrating those.

$paginator = (YOUR QUERY)->paginate(X);
$items = Meeting::hydrate($paginator->items());
2 likes

Please or to participate in this conversation.