Home > Blockchain >  Method Illuminate\Database\Eloquent\Collection::orderby does not exist
Method Illuminate\Database\Eloquent\Collection::orderby does not exist

Time:05-06

 $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. "

CodePudding user response:

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

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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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')); 
  • Related