Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save technoknol/ab9ab0114e4f5b0955d5516295e837c5 to your computer and use it in GitHub Desktop.
Save technoknol/ab9ab0114e4f5b0955d5516295e837c5 to your computer and use it in GitHub Desktop.
Full pagination, searching, orderby and sorting in laravel eloquent model
<?php
// You may need to use this classes
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\Paginator;
// Searching in segments Model, with pagination, ordering, sorting and searching.
$segments = Segment::where('segmentProviderName', $provider); // first where condition
$segmentStatuses = config('constants.segment.status');
// Searching in segments
if (Input::has('query')) { // check for query parameter in Input
$query = urldecode(Input::get('query'));
$segments = $segments->where(function($segments) use ($query) { // this will create condition like 'and (`segmentName` LIKE ? or `segmentJson` LIKE ?)'
$segments->where('segmentName', 'LIKE', '%' . $query . '%');
$segments->orWhere('segmentJson', 'LIKE', '%' . $query . '%');
});
}
// Status
if (Input::has('status')) {
// Pending segments
if (Input::get('status') == "Pending") {
$segments = $segments->whereNotNull('segmentProviderId'); // where conditions with AND
$segments = $segments->where('segmentProviderStatus', '!=', 'Published');
}
if (Input::get('status') == $segmentStatuses['draft']) {
$segments = $segments->where('segmentProviderStatus', $segmentStatuses['draft']);
}
if (Input::get('status') == $segmentStatuses['published']) {
$segments = $segments->where('segmentProviderStatus', $segmentStatuses['published']);
}
}
// Order By
$sort = 'desc';
if (Input::has('sort') && in_array(Input::get('sort'), ['asc', 'desc'])) {
$sort = Input::get('sort'); // sorting
}
if (Input::has('orderby')) { // Ordering
$segments = $segments->orderBy(Input::get('orderby'), $sort);
} else {
$segments = $segments->orderBy('updated_at', $sort);
}
// Get current page from Input and add in query e.g. url http://host.domain/?page=2
Paginator::currentPageResolver(function () {
return Input::get('page');
});
$segments = $segments->with('user')
// ->toSql(); // to get resulting query.
->paginate();
return $segments;
@technoknol
Copy link
Author

This code will lie in Controller.

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