Hello everyone and welcome to this new article on Laravel. Today I want to show you an interesting way to deal with any third-party services or external API you need to integrate in your Laravel projects.

namespace App\DataTransferObjects; class Geolocation { private $ip; private $city; private $country; private $timezone; private $internetProvider; public function __construct($ip, $city, $country, $timezone, $internetProvider) { $this->ip = $ip; $this->city = $city; $this->country = $country; $this->timezone = $timezone; $this->internetProvider = $internetProvider; } public function ip() { return $this->ip; } public function city() { return $this->city; } public function country() { return $this->country; } public function timezone() { return $this->timezone; } public function internetProvider() { return $this->internetProvider; }} #implement-ipinfo-as-a-geolocator Implement IpInfo as a Geolocator

Create a folder "app/Services/Geolocator", and add a new "IpInfo.php" file within it: namespace App\Services\Geolocator; use App\Contracts\Geolocator; use App\DataTransferObjects\Geolocation; use ipinfo\ipinfo\IPinfo as BaseIpInfo; class IpInfo implements Geolocator { public function locate(string $ip): Geolocation { $ipInfo = new BaseIpInfo(config("ipinfo.access_token")); $details = $ipInfo->getDetails($ip); return new Geolocation($ip, $details->city, $details->country, $details->timezone, $details->org); }} #tell-laravel-what-is-our-current-geolocator Tell Laravel what is our current Geolocator

namespace App\DataTransferObjects; readonly class Geolocation { public function __construct( public string $ip, public string $city, public string $country, public string $timezone, public string $internetProvider, ) {}}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners