jp.palubs
jp.palubs

Reputation: 178

Laravel 5.1 How to sort collection using lists() method

I have two questions/help to fix here:

  1. How to reduce redundancy in this line of code $this->all()->lists('name', 'id')->all()
  2. How to call mutator by using orderBy method.

helper.php

if (! function_exists('withEmpty')) {

    function withEmpty($selectList, $emptyLabel = '')
    {
        return array('' => $emptyLabel) + $selectList;
    }
}

Agent.php (model)

public function getNameAttribute($value){
    return $this->lname.', '.$this->fname.' '.$this->mname;
  }

public function listAgents($emptyLabel = '--Select Agent--'){

    return withEmpty($this->all()->lists('name', 'id')->all(), $emptyLabel);


  }

Upvotes: 3

Views: 562

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

1. Change this:

$this->all()->lists('name', 'id')->all()

To:

$this->all()->lists('name', id)

2. You can't do that. Use sortBy() and sortByDesc() collection methods with a closure instead:

->sortBy(function($i) {
    return $i->name;
});

Upvotes: 4

Carlos Palomino
Carlos Palomino

Reputation: 11

You can use the pluck and sortBy method and then apply a closure

$this->pluck('name', 'id')->sortBy(function($el) {
    return $el->name;
});

Upvotes: 1

Related Questions