Jump to content

In laravel 5.4 retrieving with several criteria


Go to solution Solved by NigelRel3,

Recommended Posts

 Hello,
in laravel 5.4 I have a form with several criteria and several of them can be selected or none selected at all :

So in function for data retrieving I want to set any sql criteria under condition if parameter is set, something like this :

 

$quoteModel = Client::where( 'client_id', '>', 0 ); // I DO NOT LIKE THIS LINE
if ( !empty( $filtersArray['is_active'] ) ) {
  $quoteModel->where( 'is_active', $filtersArray['is_active'] );
}
if ( !empty( $filtersArray['department_id'] ) ) {
  $quoteModel->where( 'department_id', $filtersArray['department_id'] );
}
if ( !empty( $filtersArray['name'] ) ) {
  $quoteModel->where( 'name', 'like', '%' . $filtersArray['name'] . '%' );
}

return $quoteModel->get();
It works ok for me, except first line: without this fake condition if all 3 parameters(is_active, department_id, name) are not set I would get error that $quoteModel is not set!

 

 

In this case I do not like  query in 1 line, like :
$clients = Client::select( 'client_id', 'name', 'login', 'active_till_date' )->onlyActive()->orderBy( $order_by, $order_direction )->get()

 

 

There could be some more parameters in all possible combinations and this seems very difficult to support.

 

 

Maybe I could write in any conditional
if ( !empty( $filtersArray['is_active'] ) ) {
  if ( !empty($quoteModel) ) {
    $quoteModel->where( 'is_active', $filtersArray['is_active'] );
  } else {
    $quoteModel = where( 'is_active', $filtersArray['is_active'] );
  }
}

 

But is there is a better way?

 

Thanks ! 

Link to post
Share on other sites
  • Solution

You could build an array of conditions, where can take something like...

$binT = \App\BinType::where([['binTypeID', '>', 1], ['sizeX', '<', 10]])->get();

So if you get to the end of all the possible conditions, you can make a choice of including the where only when you know there are criteria to use.

Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.