• 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is a beforeFind on a Model a bad idea?

#5
I never found a consistent use for a beforeFind event, honestly If people feel it's useful then feel free to submit a PR.

For things like searching and filtering for an index page you can always chain methods together. Something like:

In controller:
PHP Code:
$users $userModel->filter($this->request->getPost())->paginate(20); 

and the new method in the model might be something like:

PHP Code:
public function filter($params
{
    if(isset(
$params['search'] && ! empty($params['search'])) {
        
$this->like('name'$params['search'].'%');
    }
    if(isset(
$params['city_id'] && ! empty($params['city_id'])) {
        
$this->like('city_id'$params['city_id'].'%');
    }

    
// Sorting
    
$sortBy = isset($params['sort']) && trim($params['sort'] !== '')
        ? 
$params['sort']
        : 
'first_name';
    
$sortDir = isset($params['sort_dir']) && in_array($params['sort_dir'], ['asc''desc'])
        ? 
$params['sort_dir']
        : 
'asc';
    
$this->orderBy($sortBy$sortDir);

    return 
$this;

Reply


Messages In This Thread
Is a beforeFind on a Model a bad idea? - by tgix - 06-29-2020, 10:29 PM
RE: Is a beforeFind on a Model a bad idea? - by kilishan - 06-30-2020, 12:02 PM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.