Search code examples
phplaraveldynamicwhere-clauseclause

Laravel 5.4 where clauses if $request->jobTitle !null?


I built small search form helps me search in jobsTable from db

jobs Table has jobTitle, jobCompany, jobGovernorate, jobLocation and created_at column

And posted data from search form:

{"jobTitle":"designer","jobCompany":null,"jobGovernorate":null,"jobLocation":null,"postingDate":"ad"}

I mean some input may be null, so how to write dynamic where clause for inputs have value, i want search engine able to search by JobTitle, JobCompany or All inputs if have value.

Hint: fields name and table columns name are same

if there's a way to retrieve jobs from my db like

DB::table('jobs')->where($request->all())

Sorry for poor english, I don't know how to explain my question


Solution

  • I prefer to define all search fields.

    $searchFields = ['jobTitle','jobCompany','jobGovernorate','jobLocation','postingDate'];
    $jobQuery = DB::table('jobs');
    foreach ($searchFields as $field) {
        if ($request->has($field)) {
            $jobQuery->where($field, $request->input($field));
        }
    }
    $results = $jobQuery->get();