Beusebiu
Beusebiu

Reputation: 1523

Create function with query in model, Laravel

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;
}

Upvotes: 1

Views: 400

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

The problem is that you defined the method to the model but you try to call it on an eloquent query. What you need to do is to use another variable for the query:

public function index(Request $request, Question $question)
{
   $query = $question->newQuery();
   $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');

   $question->count_filter($query, $request)

   return response()->json($query->paginate($request->per_page));
}

Upvotes: 1

Related Questions