Install the Bundle Add the package via Composer:
composer require fontai/browscap-bundle
Register the bundle in config/bundles.php (if not auto-discovered):
return [
// ...
Fontai\BrowscapBundle\FontaiBrowscapBundle::class => ['all' => true],
];
Publish Configuration Publish the default config (if needed):
php artisan vendor:publish --tag=browscap-bundle-config
This creates config/browscap.php. Key settings include:
browscap_path: Path to your Browscap file (e.g., vendor/crossjoin/browscap/browscap.ini).cache_enabled: Enable caching for performance (default: true).cache_ttl: Cache TTL in seconds (default: 86400 for 24h).First Use Case: Detect Browser Capabilities
Inject the Browscap service into a controller or service:
use Fontai\BrowscapBundle\Service\Browscap;
class UserAgentController extends Controller
{
public function __construct(private Browscap $browscap) {}
public function showCapabilities(Request $request)
{
$userAgent = $request->userAgent();
$browser = $this->browscap->getBrowser($userAgent);
return response()->json($browser->toArray());
}
}
getBrowser(string $userAgent): Returns a Browser object with parsed capabilities.isMobile(string $userAgent): Quick check for mobile devices.isBot(string $userAgent): Detects bots/spiders.Dynamic Feature Detection Use the parsed data to conditionally load assets or apply CSS/JS:
if ($browser->isMobile()) {
return view('mobile')->with('features', $browser->getFeatures());
}
isIE(), isChrome(), getMajorVersion(), supportsFlash().Bot/Spider Handling Block or redirect bots early in middleware:
public function handle(Request $request, Closure $next)
{
if ($this->browscap->isBot($request->userAgent())) {
abort(403, 'Bots not allowed.');
}
return $next($request);
}
Cache Integration Leverage Laravel’s cache for performance:
$this->browscap->setCache(new RedisCache()); // Replace with your cache driver
browscap_<md5(userAgent)>.Event-Driven Logic Dispatch events when specific browsers are detected:
if ($browser->isIE() && $browser->getMajorVersion() < 11) {
event(new LegacyBrowserDetected($browser));
}
Extend the Browser Class
Add custom methods to the Browser object (e.g., for analytics):
// In a service provider
$this->app->extend('browscap.browser', function ($browser, $app) {
$browser->setCustomProperty('isEnterprise', $browser->isIE() && $browser->getCompanyName() === 'Microsoft');
return $browser;
});
Override Default Config
Modify config/browscap.php to point to a custom Browscap file:
'browscap_path' => storage_path('app/browscap.ini'),
Browscap File Updates
crossjoin/browscap package requires manual updates to the Browscap file (e.g., via composer require crossjoin/browscap:dev-main).composer require crossjoin/browscap:dev-main --no-update && composer update crossjoin/browscap --with-all-dependencies
Cache Invalidation
php artisan cache:clear
php artisan browscap:clear-cache if the bundle provides a command.User-Agent Spoofing
if (strpos($userAgent, 'Mozilla/') === false) {
// Likely spoofed or bot
}
Browser object to debug:
\Log::debug('Browser data:', $browser->toArray());
getBrowser() returns null, verify:
config('browscap.browscap_path').Mozilla/5.0 (Windows NT 10.0; ...)).Custom Browser Rules
Extend the Browser class to add domain-specific logic:
namespace App\Services;
use Fontai\BrowscapBundle\Entity\Browser as BaseBrowser;
class CustomBrowser extends BaseBrowser
{
public function isLegacy()
{
return $this->getMajorVersion() < 10 || $this->isIE();
}
}
Bind it in a service provider:
$this->app->bind('browscap.browser', function ($app) {
return new CustomBrowser($app['browscap.browser']->getData());
});
Database Storage Store parsed browser data in a database for analytics:
$browserData = $browser->toArray();
UserAgentLog::create([
'user_agent' => $request->userAgent(),
'browser' => json_encode($browserData),
'ip' => $request->ip(),
]);
Performance Optimization
'cache_enabled' => env('APP_ENV') !== 'local',
browscap_lite.ini) if full features aren’t needed.How can I help you explore Laravel packages today?