outl1ne / nova-sortable

This Laravel Nova package allows you to reorder models in a Nova resource's index view using drag & drop.
MIT License
282 stars 120 forks source link

How to sort all by desc in a resource? #94

Closed dprhmk closed 3 years ago

dprhmk commented 3 years ago

After creation, object is display at the end.

I can't use indexQuery() "NB! This overrides the indexQuery() method."

Maybe, i can use some default method to sort?

How to sort all by desc in a resource, and after creation object will be first?

Tarpsvo commented 3 years ago

Heya! The restriction comes from spatie/laravel-sortable which doesn't allow specifying the direction of the sort. However - there's one quick-fix which I've used and recommend to others as well:

1) Create an Observer for your model 2) Call $model->moveToStart() in the created() callback

Example of this:

public function __construct()
{
  static::created(function($model) {
    $model->moveToStart();
  });
}
lisotton commented 3 years ago

Hi,

I also would like to have the sort of my resources to have the newests on top. I tried to override the indexQuery changing the direction of my order_column but then this package does not work properly.

It would be great to have a configuration in the package to indicate if the order_column should be desc or asc. I see in the trait, by default it always order by asc.

You mentioned that spatie/laravel-sortable does not support the direction, but I think in the Controller when persisting the data in the database, it could just invert the order when persisting if it is configured to be desc.

What do you think?

If everyone thinks that this is good, I can try to propose a PR.

Tarpsvo commented 3 years ago

@lisotton Hey! Thanks for your feedback.

I don't think it's that easy to tap into Nova's own CreateController - the easiest way is to observe the observable model and when a new one is created, move it to the first position. The models creation isn't handled by a controller inside this package.

What kind of a solution were you thinking of?

lisotton commented 3 years ago

Hi @Tarpsvo

I get your point for creation, but my main point is to have the resources in the table ordered by desc (newest first). The change of the order for existing resources (when dragging and dropping) in the index is handled by the controller inside of this package, so I think could be an option to invert the order of the array received in the post or something more elaborated, so the order of the resources in the index table could be either ways.

What do you think?