How to Redirect Users According to Device Type With Laravel

Let’s say we have an app and it has some platform-specific versions that can be installed on desktop computers and mobile (Android/iOS) devices. So, we can provide a download link like example.com/download
for users. Then they need to select the related download link for their device type. The main problem with this approach is, always we cannot assume that all the users are tech-savvy enough to understand these technical things. Sometimes, all they need is just a page with a download button.
So, instead of letting users to decide the download link, we can detect the device type and automatically redirect them to the related page. For example, when a user visits example.com/download
with an Android device, it will be redirected to example.com/download/android
URL. Likewise, if the user visits the same example.com/download
URL from any other device like iOS or PC, it will be redirected to the related page. Let’s see how to do this with Laravel.
First, we need to create a Laravel middleware with the following command. It will create a middleware called DeviceRedirect
in the /app/Http/Middleware
directory.
php artisan make:middleware DeviceRedirect
Add the following code to the DeviceRedirect
middleware.
public function handle(Request $request, Closure $next)
{
$userAgent = $request->header('user-agent');
$userAgentString = strtolower($userAgent);
$androidKeywords = ['android'];
$iosKeywords = ['iphone', 'ipad'];
$isAndroidDevice = \Illuminate\Support\Str::contains($userAgentString, $androidKeywords);
$isIosDevice = \Illuminate\Support\Str::contains($userAgentString, $iosKeywords);
if ($isAndroidDevice) {
return redirect(route('android'));
} elseif ($isIosDevice) {
return redirect(route('ios'));
} else {
return redirect(route('pc'));
}
return $next($request);
}
First, it will get the user agent from the visitors’ browsers. Then it will convert the user agent into a lower case string. After that, we use the
Str::contains() helper method to check whether the user agent string has any of the words in $androidKeywords
or $iosKeywords
arrays. If matched, it will be redirected to the related mobile device route or otherwise, it will be redirected to the default route.
Add the DeviceRedirect
middleware to the $routeMiddleware
array of the Kernel.php
file in the /app/Http
directory.
protected $routeMiddleware = [
...
'device-redirect' => \App\Http\Middleware\DeviceRedirect::class,
];
Finally, open the web.php
file in the /routes
directory and add the following routes.
Route::middleware(['device-redirect'])->get('/download', function () {});
Route::get('/download/pc', function () {
return "PC";
})->name('pc');
Route::get('/download/android', function () {
return "Android";
})->name('android');
Route::get('/download/ios', function () {
return "iOS";
})->name('ios');
Now visit http://localhost/download from your desktop and mobile devices, it will be redirected to the related route.