简体   繁体   中英

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?

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

There's absolutely no point in trying to do it this way, because this entire approach is antiquated. Sure, you could pass the $(window).width() from the client in javascript back to the server in PHP, but then what happens if the user resizes their window?

This is why, today, what is encouraged, instead, is responsive design . Even Google Adsense has responsive ad units for this.

Responsive design doesn't require the back-end to know anything about the client in order to properly render things on the page. Instead, the client makes no assumptions whatsoever about how content is rendered on the client UA, and allows advanced CSS and JS to deal with the rendering directly and responsively. Meaning, that your content is never different regardless of the screen size.

Bootstrap is one such front-end framework that makes use of responsive design. There's also the Material design , which has many implementations that are also responsive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM