Skip to content
Advertisement

How can I chain Laravel requests properly for a search?

I have a search form where I take several parameters and I return the results narrowed down. However, I don’t get how I can chain the requests properly.

Like, I can’t put Candidate::all() to have all the values and narrow them down since it’s a collection. How can I make sure that my request will follow from the past request?

Here’s is my request (only the first parameter).

So, how can I chain them properly?

    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index(Request $request)
    {
        $candidates = Candidate::all();
        $data = [];
        $data['availabilities'] = Availability::all();
        $data['job_types'] = JobType::all();
        $data['fields_of_work'] = FieldOfWork::all();
        $data['interests'] = Interest::all();
        $data['salary'] = Salary::all();
        $data['trainings'] = Training::all();
        if($request->availaibilities && $request->availabilities !== -1) {
            $candidates = Candidate::whereHas('availabilities', function ($query) use ($request) {
                $query->where('availabilities.id', $request->field);
            });
        }
        return view('admin.candidates.index')->with('candidates', $candidates->get())->with('data', $data)->with('request', $request);
    }

Advertisement

Answer

You can add conditions on the query builder instance from Candidate::query()

/**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index(Request $request)
    {
        $candidates = Candidate::query();
        $data = [];
        $data['availabilities'] = Availability::all();
        $data['job_types'] = JobType::all();
        $data['fields_of_work'] = FieldOfWork::all();
        $data['interests'] = Interest::all();
        $data['salary'] = Salary::all();
        $data['trainings'] = Training::all();
        if ($request->availaibilities && $request->availabilities !== -1 && $request->field) {
            $candidates->whereHas('availabilities', function ($query) use ($request) {
                $query->where('availabilities.id', $request->field);
            });
        }
        if ($request->secondParameter) {
            $candidates->where('secondParameter', $request->secondParameter);
        }
        // and so on
        return view('admin.candidates.index')->with('candidates', $candidates->get())->with('data', $data)->with('request', $request);
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement