Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

folium's avatar

How to return $model->links() From a Controller

I'm trying to return a pagination from the controller using the link function, through ajax but It return an empty value. What could be the problem?

your reply must be appreciated.

Thanks.

$models= Model::paginate(5);
$str= "";
foreach($models as $key => $model){
       $str .= $model->name;
}
return response()->json([
        'rows' => $str,
        'links' => $models->links()
    ], 200);
0 likes
14 replies
Nakov's avatar

Your code does not make sense much..

You are doing this:

foreach($models as model){
       $str .= model['name'];
}

which is not returning even rows, but a single string from all the names. And also this model in the foreach won't work without $. And next, just return the paginator and it will have the links inside, no need to do $models->links() in the controller. So your AJAX returns 500 I guess because of other errors, it is not even getting to the response.

1 like
folium's avatar

@Nakov Oops! it's typing mistake ! actually I am not using any relationship of models I updated it.

how can I just return the paginator I need idea please.

1 like
Elliot_putt's avatar

I think you would be better calling all() instead of paginate on the top part then where you have model->links change too model->paginate()

1 like
folium's avatar

@Snapey Sir! I can see many methods here but I actually need to return html of links created according data how can do that it will really help me if you could send a code sir!

1 like
folium's avatar

@Snapey i have tried all methods from link. but it's not working at all I got all raws and data perfectly but not getting pagination link html. i am getting (Object { }) when i try to return $models->links().

1 like
folium's avatar
folium
OP
Best Answer
Level 3

I have Got The Solution by using following Code Change:

return Response::JSON(array('rows' => $str,'links' => (string) $models->links('pagination::bootstrap-4')));

by applying above return statement I Got The Html Of Paginations Page Links.

Thanks Everyone For Taking Part in This Conversation..

3 likes
gfbdy's avatar

@folium I was looking for this all over... Not able to find the solution for this on the Laravel Documentation on Laravel's official documentation on Pagination made wanna utter bad words... And I've been doing it for 5 hours until I found you. :)

Please or to participate in this conversation.