Use Browser detection in Laravel
stableIn a Laravel environment, you can use the Browser facade to identify device types, operating systems, and browser vendors. This works in both controllers and Blade templates.
In PHP code
Use the Browser facade to perform checks:
use Browser;
// Device type checks
$isMobile = Browser::isMobile();
Browser::isTablet();
Browser::isDesktop();
// Bot detection
if (Browser::isBot()) {
// Logic for bots
}
// Browser vendor checks
if (Browser::isFirefox() || Browser::isOpera()) {
// Logic for specific browsers
}
// OS checks
if (Browser::isAndroid()) {
// Logic for Android
} elseif (Browser::isMac() && Browser::isMobile()) {
// Logic for iOS
}In Blade templates
The package provides custom Blade directives for easy conditional rendering:
@mobile
<p>This is the MOBILE template!</p>
@endmobile
@tablet
<p>This is the TABLEK template!</p>
@endtablet
@desktop
<p>This is the DESKTOP template!</p>
@enddesktop
{{-- You can also use any result key via the @browser directive --}}
@browser('isBot')
<p>Bots are identified too :)</p>
@endbrowseruse Browser;
// Determine the user's device type is simple as this:
$isMobile = Browser::isMobile();
Browser::isTablet();
Browser::isDesktop();
if (Browser::isMobile()) {
// Redirect to the mobile version of the site.
}
// Every wondered if it is a bot who loading Your page?
if (Browser::isBot()) {
echo 'No need to wonder anymore!';
}
// Check for common vendors.
if (Browser::isFirefox() || Browser::isOpera()) {
$response .= '<script src="firefox-fix.js"></script>';
}
// Sometimes You may want to serve different content based on the OS.
if (Browser::isAndroid()) {
$response .= '<a>Install our Android App!</a>';
} elseif (Browser::isMac() && Browser::isMobile()) {
$response .= '<a>Install our iOS App!</a>';
}