'Method Illuminate\Database\Eloquent\Collection::orderby does not exist
$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. "
Solution 1:[1]
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
True query like that. When you take all() already query done.
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
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'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Deniz Gölbaş |
Solution 2 | geertjanknapen |
Solution 3 | |
Solution 4 | Brian Mweu |