Laravel-nova 增加拖動排序

Olivia-outshine發表於2019-04-21

Laravel Nova的索引資源新增排序功能

REP (Github)[https://github.com/ofcold/nova-sortable]

(Novapackages)[https://novapackages.com/packages/ofcold/nova-sortable]

安裝

composer require ofcold/nova-sortable

使用

  • 新增排序欄位到你的 database migrations file.

Example

$table->unsignedInteger('sort_order')->nullable();
  • 在Model中use

use Ofcold\NovaSortable\SortableTrait;

class Entry extends Model
{
    use SortableTrait;
}
  • 指定是否需要對資源進行排序。
class Example extends Resource
{
    /**
     * Build an "index" query for the given resource.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function indexQuery(NovaRequest $request, $query)
    {
        $query->when(empty($request->get('orderBy')), function (Builder $q) {
            $q->getQuery()->orders = [];
            return $q->orderBy(static::$model::orderColumnName());
        });

        return $query;
    }

    /**
     * Prepare the resource for JSON serialization.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Support\Collection  $fields
     *
     * @return array
     */
    public function serializeForIndex(NovaRequest $request, $fields = null)
    {
        return array_merge(parent::serializeForIndex($request, $fields), [
            'sortable'  => true
        ]);
    }
}

更改排序欄位名稱。

您只需要在Model中更改方法'orderColumnName'。

/*
 * Determine the column name of the order column.
 */
public static function orderColumnName(): string
{
    return 'your sort order column name';
}

Demos

demos.gif?sanitize=true

Bill

相關文章