Thursday, February 3, 2022

[FIXED] Cakephp 3 : How to detect mobile in controller by requestHandler?

Issue

I need detect mobile in controller for a condition. I have tried below code in my controller.

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

Then I have written below code in index method

if ($this->RequestHandler->is('mobile')) 
{     
  //condition 1 
}else {
 //condition 2 
}

Here I get the error

Error: Call to undefined method Cake\Controller\Component\RequestHandlerComponent::is() 

How can mobile detect in controller ?


Solution

The request handler isn't necessary for that since all the request handler does is proxy the request object:

public function isMobile()
{
    $request = $this->request;
    return $request->is('mobile') || $this->accepts('wap');
}

The controller also has direct access to the request object, so the code in the question can be rewritten as:

/* Not necessary
public function initialize()
{
    parent::initialize();
} 
*/    

public function example()
{
    if ($this->request->is('mobile')) {
        ...
    } else {
        ...
    }
}


Answered By - AD7six

No comments:

Post a Comment

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