Last active
April 9, 2022 17:19
-
-
Save Muetze42/542e12cbe581b11a153a38ee9c6f5c48 to your computer and use it in GitHub Desktop.
Laravel Nova (4) Resource with Optional sorting and filter options
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 | |
namespace App\Nova; | |
use Illuminate\Database\Eloquent\Builder; | |
use Laravel\Nova\Http\Requests\NovaRequest; | |
use Laravel\Nova\Resource as NovaResource; | |
use Laravel\Scout\Builder as ScoutBuilder; | |
abstract class Resource extends NovaResource | |
{ | |
/** | |
* The column by which to sort as default | |
* | |
* @var string | |
*/ | |
public static string $defaultSort = ''; | |
/** | |
* Sort ascending or descending as default | |
* | |
* @var string | |
*/ | |
public static string $defaultOrder = 'asc'; | |
/** | |
* Build an "index" query filter for the given resource. | |
* | |
* @param NovaRequest $request | |
* @param $query | |
* @return Builder | |
*/ | |
public static function indexFilter(NovaRequest $request, $query): Builder | |
{ | |
return $query; | |
} | |
/** | |
* Build an "index" query for the given resource. | |
* | |
* @param NovaRequest $request | |
* @param Builder $query | |
* @return Builder | |
*/ | |
public static function indexQuery(NovaRequest $request, $query): Builder | |
{ | |
$query = static::indexFilter($request, $query); | |
if (static::$defaultSort && empty($request->get('orderBy'))) { | |
$query->getQuery()->orders = []; | |
return $query->orderBy(static::$defaultSort, static::$defaultOrder); | |
} | |
return $query; | |
} |
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 | |
class User extends Resource | |
{ | |
/** | |
* The column by which to sort as default | |
* | |
* @var string | |
*/ | |
public static string $defaultSort = 'name'; | |
/** | |
* Sort ascending or descending as default | |
* | |
* @var string | |
*/ | |
public static string $defaultOrder = 'desc'; | |
/** | |
* Build an "index" query filter for the given resource. | |
* | |
* @param NovaRequest $request | |
* @param $query | |
* @return Builder | |
*/ | |
public static function indexFilter(NovaRequest $request, $query): Builder | |
{ | |
return $query->where('id', $request->user()->id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment