Forked from technoknol/Laravel eloquent where-group-and-whereor-sorting-orderby-search.php
Created
January 9, 2018 07:04
-
-
Save baorv/c3c1026b6de2ead3fbed41769376aef6 to your computer and use it in GitHub Desktop.
Full pagination, searching, orderby and sorting in laravel eloquent model
This file contains hidden or 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
👍