Skip to content

Instantly share code, notes, and snippets.

@grandmanitou
Created June 10, 2020 10:59
Show Gist options
  • Save grandmanitou/5795d2048b186fd2baf8c1ebffefd329 to your computer and use it in GitHub Desktop.
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
<?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