Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 818
Satu Sultana Avatar asked Dec 15 '22 11:12

Satu Sultana


1 Answers

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 {
        ...
    }
}
like image 137
AD7six Avatar answered Feb 15 '23 23:02

AD7six