Method Illuminate\Database\Eloquent\Collection::orderby does not exist

1.8k Views Asked by At
 $posts = Post::all()->orderby('created_at','desc')->where('usr_id','=',session('LoggedUser'))->get();

    return view('admin.profile',compact('userInfo' , 'posts'));

i am making a custom auth for a journal activity but i cant sort the content i shows this error

"Method Illuminate\Database\Eloquent\Collection::orderby does not exist. "

5

There are 5 best solutions below

0
On

Change the orderby to orderBy. This could be the reason you are getting the error.

$posts = Post::all()->orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->get();

return view('admin.profile',compact('userInfo' , 'posts')); 

Or...

If you want to get specific number of posts you can do it this way to avoid using the Post::all

$posts = Post::orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->paginate(5);

return view('admin.profile',compact('userInfo' , 'posts')); 
0
On

I believe this might be because you typed orderby instead of orderBy (notice the uppercase). See laravel orderBy documentation if needed.

Plus, as mentionned by other, don't use all() if you need to do other thing (where clause, order by, etc) in you query.

0
On
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();

True query like that. When you take all() already query done.

0
On

Change it to:

$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();

you cant use all() and orderBy because all() does not allow the modification of the query.

0
On

Yeah this is pretty confusing and just got me as well.

The actual problem isn't the capitilization typo (orderby versus orderBy) but rather the fact that you're using ->all() instead of just Model::orderBy()->...

The moment you use ->all() the object is transformed to another type of collection object and the normal methods one would expect do not exist.

In this case you should rather use sortBy().

See here.