4

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 ?

Satu Sultana
  • 527
  • 1
  • 11
  • 23

3 Answers3

8

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 {
        ...
    }
}
AD7six
  • 63,116
  • 12
  • 91
  • 123
4

I think that will be

$this->RequestHandler->isMobile()
Alimon Karim
  • 4,354
  • 10
  • 43
  • 68
1

CakePHP 3 uses mobiledetect/mobiledetectlib lib

In bootstrap.php added 2 types of detection 'mobile', 'tablet'

You can use it:

    if ($this->request->is('mobile')) {
       // ...
    }
    elseif ($this->request->is('tablet')) {
       // ...
    }
    else {
       // ...
    }