A
A
Alex2021-02-25 05:28:58
Laravel
Alex, 2021-02-25 05:28:58

Is it possible to change the order of models in Laravel?

Is it possible in Laravel to change the order of models to bring them to the front-end order?
In my case, these are dragbble blocks with notes that the user can drag around by changing their order. And you need the ability to maintain this order with each change of order.

ps is used by Laravel 8

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kuznetsov, 2021-02-25
@dima9595

"Order of models" is a wrong concept. There is no such.
At you these elements change by means of JS and are stored in any object. So what's the problem with storing this object in some field of the table?

Z
zorca, 2021-02-25
@zorca

Google "Laravel Sortable"

K
Konstantin B., 2021-02-25
@Kostik_1993

If you are concerned about the number of requests, you can do something similar, but only more elegantly.

if($request->photo !== null){

                /**
                 * Городим конструкцию, которая позволит нам избежать n+1 запросов при прикреплении фотографий к записи
                 * Стандартная реализация связей нам не подходит потому что у нас помимо указания ID поста
                 * необходимо добавить порядкове номера для сортировки фотографий
                 * Аналогичная функция используется и для перетаскивая
                 */
                $table = with(new Photo)->getTable();
                $imageable_type = Advert::class;
                $imageable_id = $advert->id;
                $cases = [];
                $ids = [];
                $params = [];

                foreach ($request->photo as $value => $id) {
                    $id = (int) $id;
                    $cases[] = "WHEN {$id} then ?";
                    $params[] = $value;
                    $ids[] = $id;
                }

                $ids = implode(',', $ids);
                $cases = implode(' ', $cases);
                $params[] = $imageable_type;
                $params[] = $imageable_id;

                $this->db->update("UPDATE `{$table}` SET `position` = CASE `id` {$cases} END, `imageable_type` = ?, `imageable_id` = ? WHERE `id` in ({$ids})", $params);
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question