Skip to content

Instantly share code, notes, and snippets.

@nellytadi
Last active December 4, 2024 08:13
Show Gist options
  • Select an option

  • Save nellytadi/55d3e7fdde472ba60850f554352c1825 to your computer and use it in GitHub Desktop.

Select an option

Save nellytadi/55d3e7fdde472ba60850f554352c1825 to your computer and use it in GitHub Desktop.
Manual Paginate In Laravel
<?php
namespace App\Http\Controllers\Api;
use App\Model;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
class TestController extends Controller
{
public function test(Request $request){
$array = Model::select('id','organisation_name','company_status','created_at','updated_at')->where('publish', 1)->limit(15)->get();
$total=count($array);
$per_page = 5;
$current_page = $request->input("page") ?? 1;
$starting_point = ($current_page * $per_page) - $per_page;
$array = array_slice($array, $starting_point, $per_page, true);
$array = $array->toArray();
$array = array_slice($array, $starting_point, $per_page, true);
$array = new Paginator($array, $total, $per_page, $current_page, [
'path' => $request->url(),
'query' => $request->query(),
]);
dd($array);
}
}
@RicardoRL

RicardoRL commented Apr 29, 2020 •

Copy link
Copy Markdown

Hi, I'm trying to implement a paginator, but I don't know where do you get "page" here:

$current_page = $request->input("page") ?? 1;

Could you help me whit that? I'm a bit confused

@nellytadi

nellytadi commented Apr 29, 2020 •

Copy link
Copy Markdown
Author

$request->input("page")

Should come from your request. You need to keep track of what page you're on from your view.
So always pass the value of that page in the request maybe through the URL assuming it is a get request.
eg
<a href="{{ url ("/your/url?page=".$array->current_page + 1 ) }}" > next </a>

@nellytadi

nellytadi commented Apr 29, 2020 •

Copy link
Copy Markdown
Author

$request->input("page")

Should come from your request. You need to keep track of what page you're on from your view.
So always pass the value of that page in the request maybe through the URL assuming it is a get request.
eg
<a href="{{ url ("/your/url?page=".$array->current_page + 1 ) }}" > next </a>

Remember to ensure you add if statements to check if you're on the first page and if you're on the last page. You don't want the next or previous respectively to be clickable on those pages.

@RicardoRL

Copy link
Copy Markdown

Oh right, excellent, thank you so much!!

@nellytadi

Copy link
Copy Markdown
Author

Oh right, excellent, thank you so much!!

Glad i could help :)

@manihs

manihs commented Jun 24, 2020

Copy link
Copy Markdown

short and simple = awesome 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment