Created
June 10, 2020 10:59
-
-
Save grandmanitou/5795d2048b186fd2baf8c1ebffefd329 to your computer and use it in GitHub Desktop.
Laravel Phone Number Accessor : format phone number to local phone number or international phone number for other regions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
use libphonenumber\PhoneNumberUtil; | |
use libphonenumber\NumberParseException; | |
use libphonenumber\PhoneNumberFormat; | |
class Contact extends Model | |
{ | |
protected $guarded = []; | |
public function getLocalMobilePhoneAttribute() | |
{ | |
return $this->LocalPhoneNumberFormat($this->mobile_phone); | |
} | |
public function getLocalFixedPhoneAttribute() | |
{ | |
return $this->LocalPhoneNumberFormat($this->fixed_phone); | |
} | |
private function LocalPhoneNumberFormat($string) | |
{ | |
if (!empty($string)) { | |
$phoneNumberUtil = PhoneNumberUtil::getInstance(); | |
try { | |
$phone = $phoneNumberUtil->parse($string); | |
$region = $phoneNumberUtil->getRegionCodeForNumber($phone); | |
} catch (NumberParseException $e) { | |
return false; | |
} | |
if (strtolower($region) == strtolower(config('app.locale'))) { | |
return $phoneNumberUtil->format($phone, PhoneNumberFormat::NATIONAL); | |
} else { | |
return $phoneNumberUtil->format($phone, PhoneNumberFormat::INTERNATIONAL); | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment