<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

trait HasOrderByRequest
{
    public function orderByRequest(&$builder, Request $request)
    {
        foreach ($request->keys() as $keyRequest) {
            // Order by
            if (str_contains($keyRequest, 'order_by')) {
                $column = str_replace('order_by_', '', $keyRequest);
                if ($request->get($keyRequest) === 'desc') {
                    $builder = $builder->orderBy($column, 'desc');
                } else {
                    $builder = $builder->orderBy($column, 'asc');
                }
            }
        }
        return $builder;
    }
}
