All Projects → ofcold → Nova Sortable

ofcold / Nova Sortable

Licence: mit
Adds sorting functionality to Laravel Nova's index resource

Labels

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].