Saturday, February 12, 2022

[FIXED] CakePHP 3 - check variable from controller in model

Issue

I'm newbie in CakePHP, and I need help with this now.

In app I have this variable which is accessiable from controllers.

$this->Auth->user('is_admin')

I need apply filter for all Finds in Model. So in ContactsTable.php I have this

public function beforeFind($event, $query, $options) {  
  $alias = $event->subject()->alias();
  $query->where([$alias.'.deleted is null']);
  return $query;
}

Now, I need aplly this "where" only for no admins users. So my question is how I can read $this->Auth->user('is_admin') in this model?

Thank you


Solution

1) You can pass the auth cariable as param to finder:

//controller 
$result = $this
    ->Users
    ->find('myCustomFinder' , [
        'is_admin' => $this->Auth->user('is_admin')
    ]);

2) Or You can access session variables directly in model, but this not a good practice and this is a little bit harder to test.

// model
public function beforeFind($event, $query, $options) 
{  
    $is_admin = \Cake\Routing\Router::getRequest()
        ->session()
        ->read('Auth.User.is_admin');

    // edit: 
    if($is_admin) {
       return $query->withAdminStuff();
    }

    return $query->nonAdminStuff();
}


Answered By - Dariusz Majchrzak

No comments:

Post a Comment

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