PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

[FIXED] What will the best solution for this multiple optional filter?

 April 18, 2022     laravel, laravel-5, mysql, php     No comments   

Issue

These are all optional fields, so will I have to write multiple queries with conditions or is there any way to handle this using Laravel? What will be the query looks like?

Thanks

enter image description here


Solution

It depends a bit on how the filters are submitted, but you can do one of the following two things (and probably a gazillion more...):

public function listCars(Request $request)
{
    $cars = Car::when($request->get('make'), function ($query, $make) {
            $query->where('make', $make);
        })
        ->when($request->get('model'), function ($query, $model) {
            $query->where('model', $model);
        })
        ->...
        ->get();

    // do what you have to do
}

So you are basically wrapping your query builder calls in when($value, $callback), which will only execute $callback if $value evaluates to true. When you retrieve a not set parameter with $request->get('parameter'), it will return null and the callback is not executed. But be careful, if $value is 0 it will also not execute the callback. So be sure you don't have this as an index.

As alternative to this, you can also do the same thing but with a bit less eloquent expressions...

public function listCars(Request $request)
{
    $query = Car::query();

    if($request->filled('make')) {
        $query->where('make', $request->get('make'));
    }
    if($request->filled('model')) {
        $query->where('model', $request->get('model'));
    }

    // some more filtering, sorting, ... here

    $cars = $query->get();

    // do what you have to do
}


Answered By - Namoshek
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing