我收到错误
方法orderBy在我的视图中不存在。
这是我的观点:
@foreach($post->comments->orderBy('created_at', 'desc') as $comment)
{{ $comment->comments }}
@endforeach
@stop
这是我的控制器:
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');
}
仍然出现错误。
您试图在Collection
对象中使用orderBy()
,而不是在查询中。
要使这项工作与你正在做的完全一样,你必须做:
@foreach($post->comments()->orderBy('created_at', 'desc')->get() as $comment)
{{ $comment->comments }}
@endforeach
但是,这种方式并不是最好的方式
为了使代码变得清晰,您应该将其添加到comments()
方法中,或者创建另一个在模型中对查询进行排序的方法。