Search code examples
javascriptphplaravelgoogle-dfp

Laravel - include file only if screen size > 768px


I have a tricky situation where I need to move my Google Ads around on Mobile. I figured out that the best way to do this is to call them using @include but only if certain screen size conditions are met.

I am thinking that the following would work

@if($screensize < 768px)
  @include('partials.my-advert')
@endif

So my question is how do I get the screen size into PHP? I can get the screen size via JS using $(window).width(); but then how do I use this value in the Laravel if statement?


Solution

  • You can't detect the screen size with PHP, but alternatively, you can detect the agents. There is a package, which detects the agents easily where it lets you detect whether the request is coming from desktop/tablet/mobile.

    To install it via composer, you can run the command below.

    $ composer require jenssegers/agent
    

    Then add dd the service provider to providers key within the file config/app.php.

    Jenssegers\Agent\AgentServiceProvider::class
    

    Furthermore, add the Agent alias to the aliases key,

    'Agent' => Jenssegers\Agent\Facades\Agent::class
    

    Finally, pass the agent variable from your controller to view.

    $agent = new Agent();
    return view('some.view', compact('agent'));
    

    Then within your view, you can check whether the agent belongs to some mobile phone or not.

    @if($agent->isMobile())
      @include('partials.my-advert')
    @endif