I have a working function in my controller, but I want to place a part of the code in model, is repeatable and I want to use it in multiple controllers. but witch my current code is not working (no errors).
Controller
public function index(Request $request)
{
$query = new Question;
$query->select(
['questions.id',
'questions.free_text',
'questions.title',
'questions.created_at',
'lkp_answers.name as bestMatch',
]);
$query->with(['answer_history']);
$query->join('lkp_answers', 'lkp_answers.id', '=', 'questions.best_match');
$query->count_filter($query, $request); //here I try to use it
return response()->json($query->paginate($request->per_page));
}
Model
public function count_filter($query, $request){
if($request->sort_by){
$direction = ($request->sort_direction === 'false') ? 'asc' : 'desc';
if($request->sort_by === 'best_match'){
$query->orderBy('lkp_answers.name', $direction);
}else if ($request->sort_by === 'noneOfTheAbove') {
$query->withCount(['answer_history AS none' => function ($q) {
$q->where('answer_type', 'none');
return $q;
}])->orderBy('none', $direction);
} else if ($request->sort_by === 'skipped') {
$query->withCount(['answer_history AS skipped' => function ($q) {
$q->where('answer_type', 'skipped');
return $q;
}])->orderBy('skipped', $direction);
} else if ($request->sort_by === 'totalVotes') {
$query->withCount(['answer_history AS totalVotes' => function ($q) {
$q->where('answer_type', '!=','skipped');
return $q;
}])->orderBy('totalVotes', $direction);
}
else {
$query->orderBy($request->sort_by,$direction);
}
}
return $query;
}
$query = $query->count_filter($query, $request);$query = Helper::count_filter($query, $request);and make static function on helper file. and call like that.