วิธีการเช็ค Detect Browser ผู้ใช้จาก Laravel
11 กุมภาพันธ์ 2565
บางครั้งในโปรแกรมที่เราเขียนขึ้น เราต้องการทราบว่าผู้ใช้ที่เข้ามาใช้งาน Web Application ของเราใช้งานมาจากอุปกรณ์ใด Browser ไหน หรือ OS อะไร เราสามารถใช้ package phattarachai/laravel-mobile-detect เพื่อตรวจสอบ client ที่ผู้ใช้เรียกใช้เข้ามาได้
โดยแพคเกจนี้ ใช้พื้นฐานมาจาก Mobile Detect โดยเพิ่มการรองรับ Desktop มีการเชื่อม Laravel integration ให้สามารถเรียกใช้งานได้ง่ายขึ้น
การติดตั้ง
สามารถติดตั้งได้โดย run คำสั่ง composer
composer require phattarachai/laravel-mobile-detect
Laravel (optional)
เพิ่ม service provider ใน config/app.php
:
Phattarachai\LaravelMobileDetect\AgentServiceProvider::class,
เพิ่ม alias ใน config/app.php
:
'Agent' => Phattarachai\LaravelMobileDetect\Facades\Agent::class,
การใช้งานพื้นฐาน
เริ่มจากสร้างตัวแปร Agent หรือเรียกใช้ผ่าน Laravel Facade
use Phattarachai\LaravelMobileDetect\Agent;
$agent = new Agent();
ถ้าหากเราต้องการ แปร User Agent ที่ไม่ได้มาจาก request โดยตรง เช่น ทดสอบเรียกใช้จาก Artisan command หรือ factory เราสามารถใช้เมธอด setUserAgent
และ setHttpHeaders
ได้
$agent->setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2');
$agent->setHttpHeaders($headers);
นอกจากนี้ เรายังสามารถเรียกเมธอดอื่น ๆ ใน Mobile Detect ได้ตามปกติ โดยเราสามารถดูตัวอย่างการใช้งานได้ที่ https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples
เมธอด is
ใช้เช็คว่ามีคำที่ระบุอยู่ใน User Agent
$agent->is('Windows');
$agent->is('Firefox');
$agent->is('iPhone');
$agent->is('OS X');
Mobile detection ตรวจสอบว่ามาจาก Mobile ใช่หรือไม่
$agent->isMobile();
$agent->isTablet();
ชื่ออุปกรณ์ที่ใช้ Device name
ดึงชื่ออุปกรณ์ที่ใช้ถ้ามาจาก (iPhone, Nexus, Samsung,...)
$device = $agent->device();
ชื่อ Operating system
ดึงชื่อ Operating System (Ubuntu, Windows, OS X, ...)
$platform = $agent->platform();
ชื่อ Browser
ดึงชื่อ browser (Chrome, IE, Safari, Firefox, ...)
$browser = $agent->browser();
ตรวจเช็ค Desktop
เช็คว่า ผู้ใช้มาจาก Desktop
$agent->isDesktop();
ดูรายละเอียด package เพิ่มเติมได้ที่ Github phattarachai/laravel-mobile-detect