samedi 19 août 2017

Dynamically order related eloquent records in Laravel

In Laravel 5.4 I have Job model where it which it belongsTo Product and Machine models. I'm using pagination in the index action of JobController and I manage sorting records like the following:

public function index()
    {

       $allowedSort = ['id','title','created_at','completed','started','product_id','machine_id'];
       if (in_array(request('sortBy','id'),$allowedSort)){
           $sortBy = request('sortBy','id');
       }
       else{
           $sortBy = 'id';
       }
       if (request('dir','desc') == 'desc' || request('dir','desc') == 'asc'){
           $dir = request('dir','desc');
       }
       else {
            $dir = 'desc';    
       }
        $jobs = Job::orderBy($sortBy,$dir)->paginate(config('fox.pagingPerPage'));

        return view('job.index', compact('jobs'));
    }

Currently, I'm able only to order the related models using their ids using product_id and machine_id. However, I need to keep the order dynamically as above and also to be able to order using another property of the related model such as machine.title or product.price.

I have tried supplying orderBy() with machine.title as a field name by adding it to $allowedSort array like [...,'machine.title']. However, it generates SQL error Unknown column 'machine.title'...

Is there any way to keep dynamically listed index and allow sorting according to both model's attributes and its related models attributes in the same process?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2wcSyJX
via IFTTT

Aucun commentaire:

Enregistrer un commentaire