Sometimes we need to know from which device user is logged in to out application and show different content to user based on their device. So in this tutorial we are going to learn how to detect user device is Mobile, Dekstop or Tablet and show the result based on the device. For this tutorial we are going to use a package called jenssegers/agent
Setting up the Project
First you need to create a new laravel project by running below command in your terminal
use Illuminate\Http\Request; use Jenssegers\Agent\Agent;
class DeviceController extends Controller { /* return view based on device*/ public function detectDevice() { $agent = new Agent();
$mobileDevice = $agent->isMobile(); if ($mobileDevice) { return view('mobile'); }
$tabletDevice = $agent->isTablet(); if ($tabletDevice) { return view('tablet'); }
$desktopDevice = $agent->isDesktop(); if ($desktopDevice) { return view('welcome'); } }
/* return result based on device*/ public function detectDevices() { $agent = new Agent();
$mobileDevice = $agent->isMobile(); if ($mobileDevice) { $result = 'This is Mobile'; }
$tabletDevice = $agent->isTablet(); if ($tabletDevice) { $result = 'This is Tablet'; }
$desktopDevice = $agent->isDesktop(); if ($desktopDevice) { $result = 'This is Dekstop'; }
return view('devices',compact('result'));
} }
Create View
Inside resources -> views folder create, four files called dekstop.blade.php, tablet.blade.php, mobile.blade.php & devices.blade.php. Then navigate to dekstop.blade.php and paste below code:
In this tutorial, we learned how show result based on the the user's device in Laravel. If you have any issue regarding this tutorial, mention your issue in the comment section or reach me through my E-mail. You can obtain complete source code for this tutorial from this GitHub repository.