How to sort records in alphabetical order in Larav

2020-03-22 06:28发布

How to sort records in alphabetical order in laravel?

public function index()
{
    $comproducts = Comproduct::paginate(3);

    $items = Item::orderBy('name')->all();        

    return view('computer', compact(['comproducts', 'items']));

}

This is not working correctly. This shows

Call to undefined method Illuminate\Database\Query\Builder::all()

this error. How can i fix this?

3条回答
▲ chillily
2楼-- · 2020-03-22 07:09

I use get() instead , you can't modify query with method all() and also it is static function

  $items = Item::orderBy('name')->get(); 
查看更多
我命由我不由天
3楼-- · 2020-03-22 07:09

That's how you sort it, orderBy() comes after all():

$items = Item::all()->sortBy('name');    

Reference: https://laravel.com/docs/5.5/collections

查看更多
劫难
4楼-- · 2020-03-22 07:20

Hi Please find an answer based on eloquent query laravel

Table: Users Columns:id,name,class_id

$users = DB::table('users')->whereIn('class_id', [1, 2, 3])->orderBy('name', 'ASC')->paginate(50);
查看更多
登录 后发表回答