我正在创建一个laravel待办事项应用程序。在我的控制器中有不同的方法,但其中的所有代码几乎相同。在notCompleted方法和完成的方法中,还有1个不同的where子句。除了所有的代码是相同的。我该如何避免代码重复?如何避免这里的PHP代码重复
public function all()
{
$user_id = $this->user_id;
$todos = $this->todos
->where('user_id', $user_id)
->orderBy('id', 'DESC')->paginate(15);
return view('todos.index', compact('todos'));
}
public function notCompleted()
{
$user_id = $this->user_id;
$todos = $this->todos
->where('user_id', $user_id)
->where('completed', false)
->orderBy('id', 'DESC')->paginate(15);
return view('todos.index', compact('todos'));
}
public function completed()
{
$user_id = $this->user_id;
$todos = $this->todos
->where('user_id', $user_id)
->where('completed', true)
->orderBy('id', 'DESC')->paginate(15);
return view('todos.index', compact('todos'));
}
我可以这样做,但我需要三个途径三种不同的方法。感谢您的回应 –