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

Saturday, February 12, 2022

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

 February 12, 2022     activerecord, cakephp, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

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