Home » Php » php – How can I build a condition based query in Laravel 6.x?

php – How can I build a condition based query in Laravel 6.x?

Posted by: admin February 25, 2020 Leave a comment

Questions:
public function test(Request $request){
    $apartments = DB::table('apartments');
    if ($request->filled('bathrooms')) {
        $apartments->where('bathrooms', '=' ,$request->input('bathrooms'));
    }
    if ($request->filled('rooms_number')) {
        $apartments->where('rooms_number', '=', $request->input('rooms_number'));
    }
    $apartments->get();
    return view('pages.test2' , compact('apartments'));
}

How can this code be translated so that it works in Laravel?

How to&Answers:

You can use when as a conditional clause:

public function test (Request $request)
{
    $apartments = DB::table('apartments')
        ->when($request->filled('bathrooms'), function ($query) use ($request) {
            return $query->where('bathrooms', '=', $request->input('bathrooms'));
        })
        ->when($request->filled('rooms_number'), function ($query) use ($request) {
            return $query->where('rooms_number', '=', $request->input('rooms_number'));
        })
        ->get();

    return view('pages.test2' , compact('apartments'));
}