Loading more eloquent hasMany relation queries through ajax in Laravel? Loading more eloquent hasMany relation queries through ajax in Laravel? ajax ajax

Loading more eloquent hasMany relation queries through ajax in Laravel?


Do you need to load the first page of replies server-side? I guess since you are willing to load subsequent pages with AJAX you could just handle all client-side and just have an AJAX endpoint that provides the data.

Just make ajax calls to your endpoint passing the status id and page number.

// AjaxControllerpublic function replies(){    $status = Status::findOrFail(request('id'));    return $status->replies()->paginate(3);}

(The page number will be resolved automatically.)

This will return a JSON representation of the paginator, which has the urls for previous and next pages, and the data for the current page. Then just render the data client-side.


What I ended up doing was simply creating a new function in my controller for the request itself, and then sending the ID of the status along with it, along with a skip count (that increases based on how many replies are already loaded) to skip the loaded replies.

public function getReplies($statusID, $skip, Request $request) {    $status = Status::findOrFail($statusID);    $replies = $status->replies()->orderBy('created_at', 'desc')->skip($skip)->take(10)->get();    if($request->ajax()) {        return [            'replies' => view('templates.partials.replies')->with('replies', $replies)->render(),        ];    }   }