https://twill.io logo
how should I overwrite the order function?
# ❓questions
n
how should I overwrite the order function?
i
Here's an example:
Copy code
protected $indexColumns = [
        'title' => [
            'title' => 'Title',
            'field' => 'title',
            'sort' => true,
        ],
        'eventType' => [
            'title' => 'Type',
            'relationship' => 'eventType',
            'field' => 'title',
            'sort' => true,
        ],
    ];
Copy code
public function order($query, array $orders = [])
    {
        if (array_key_exists('eventTypeTitle', $orders)) {
            $direction = $orders['eventTypeTitle'];

            unset($orders['eventTypeTitle']);

            $query->orderByEventType($direction);
        }

        return parent::order($query, $orders);
    }
Copy code
public function scopeOrderByEventType($query, $direction = 'asc')
    {
        return $query
            ->select('events.*')
            ->leftJoin(
                'event_types',
                'events.event_type_id',
                '=',
                'event_types.id'
            )
            ->leftJoin(
                'event_type_translations',
                'event_types.id',
                '=',
                'event_type_translations.event_type_id'
            )
            ->where('event_type_translations.locale', locale())
            ->orderBy('event_type_translations.title', $direction);
    }
You won't need that complexity because your fields are not translatable but hopefully that gives you some inspiration
you don't need a scope either if you don't want to
Could be
Copy code
public function order($query, array $orders = [])
    {
        if (array_key_exists('userName', $orders)) {
            $direction = $orders['userName'];

            unset($orders['userName']);

            $query->with('user')->orderBy('user.name');
        }

        return parent::order($query, $orders);
    }