Sid Heart
Sid Heart

Reputation: 743

Method orderBy does not exist on view

I am getting error

method orderBy does not exist on my view.

This is my view:

@foreach($post->comments->orderBy('created_at', 'desc') as $comment)
    {{ $comment->comments }}
@endforeach
@stop

This is my controller:

public function store(Request $request)
{
    $post = new post;

    $post->title = $request->title;
    $post->save();

    return redirect()->route('rules');
}

public function show($title)
{
    $post = post::where('title', $title)->first();

    return view('post.show', compact('post'));
}


public function storecomment(request $request)
{
    $comment = new comment;

    $comment->post_id = Crypt::decrypt(Input::get('post_id'));
    $comment->comments = $request->comments;
    $comment->save();

    return redirect()->route('rules');
}

still getting an error.

Upvotes: 0

Views: 3246

Answers (1)

Laerte
Laerte

Reputation: 7083

You are trying to use orderBy() in a Collection object, not in a query.

To make this work exactly as you are doing, you have to do:

@foreach($post->comments()->orderBy('created_at', 'desc')->get() as $comment)
   {{ $comment->comments }}
@endforeach

But, this way is not the best way to do it.

To make the code clear, you should add this to comments() method or create another method that orders the query inside the model.

Upvotes: 2

Related Questions