Laravel Community Tools by Tighten
Laravel Nova icon Nova Packages

Readme

Nova sortable

Adds sorting functionality to Laravel Nova's index resource

Installing

composer require ofcold/nova-sortable

Using

  • Add a sort field to your database migrations file.

Example

$table->unsignedInteger('sort_order')->nullable();
  • Trait entry
use Ofcold\NovaSortable\SortableTrait;

class Entry extends Model
{
	use SortableTrait;
}
  • Specify whether the resource needs to be sorted.
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 ($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
		]);
	}
}

Change sort field name

You only need to change the method 'orderColumnName' in your entry.

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

Demos

Back to Top
Added 6 years ago
Last updated 6 Years Ago
Version 1.0.6
Composer
ofcold/nova-sortable
GitHub stars 33
Packagist downloads 236,977

Favorites

24 users favorited

Rating

4.40
(out of 5)
★★★★★
★★★★
★★★
★★
7 ratings

Author

Brought to you by Tighten

Issues/Feature Requests Stats Package Ideas