mstdmstdd Posted April 18, 2017 Share Posted April 18, 2017 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 ! Quote Link to comment https://forums.phpfreaks.com/topic/303735-in-laravel-54-retrieving-with-several-criteria/ Share on other sites More sharing options...
NigelRel3 Posted April 18, 2017 Share Posted April 18, 2017 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. Quote Link to comment https://forums.phpfreaks.com/topic/303735-in-laravel-54-retrieving-with-several-criteria/#findComment-1545568 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.