Created
May 23, 2017 09:26
-
-
Save technoknol/ab9ab0114e4f5b0955d5516295e837c5 to your computer and use it in GitHub Desktop.
Full pagination, searching, orderby and sorting in laravel eloquent model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code will lie in Controller.