26.9 C
Pakistan
Monday, July 15, 2024

PHP User Agent Parser for Desktop and Mobile

Based on MobileDetect, the jenssegers-agent package is a desktop/mobile user agent parser that supports Laravel. This package gives you a service facade that can be used in any PHP application. It also comes with a Laravel service provider.

use Jenssegers\Agent\Facades\Agent;
Agent::is(‘Firefox’);
Agent::is(‘iPhone’);
// Magic methods
Agent::isFirefox();
Agent::isIPhone();
// Device type
Agent::isDesktop();
Agent::isMobile();
Agent::isTablet();
Agent::isPhone();

 

 

The Agent service offers more than just user agent helps; it also offers a language helper, platform, device name method, and more. For instance, you could use the following technique to obtain the supported browser languages:

 

Agent::languages(); // [‘en-us’, ‘en’]

 

 

You might set the locale in a middleware during a request by using the languages method. Here is a little example, simply to give you an idea, that comes to mind:

 

public function handle(Request $request, Closure $next): Response
{
$supported_locales = [‘en’, ‘es’];
$user_locales = Agent::languages();
foreach ($user_locales as $locale) {
if (in_array($locale, $supported_locales)) {
app()->setLocale($locale);
}
}
return $next($request);
}

The locale will be defined by the config(‘app.fallback_locale’) parameter if you do not support the localization. In middleware, you can also use the languages() method to reroute a locale-specific route prefix /{locale}/ according to the language supported by the user agent.

Route::prefix(‘/{locale}’)->group(function () {
// …
})->whereIn(‘locale’, [‘en’, ‘es’]);

The Agent service can also determine if the current user agent is a bot and what type of bot:

// Is the user a bot?
Agent::isRobot(); // bool
// get the robot name
Agent::robot();

Finally, you can utilize the appropriately designated methods on the façade to obtain the device name, platform, and browser:

Agent::device(); // “Macintosh”
Agent::platform(); // “OS X”
Agent::browser(); // “Safari”

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles