Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey.
Check out the behavior of this package in the demo.
Run the following command to install the latest applicable version of the package:
composer require propaganistas/laravel-phone
The Service Provider gets discovered automatically by Laravel.
In your languages directory, add an extra translation in every validation.php
language file:
'phone' => 'The :attribute field contains an invalid number.',
To validate a phone number, use the phone
keyword in your validation rules array or use the Phone
rule class to define the rule in an expressive way. The phone validator is able to operate in three ways.
You either specify ISO 3166-1 alpha-2 compliant country codes yourself as parameters for the validator, e.g.:
'phonefield' => 'phone:US,BE',
// 'phonefield' => Rule::phone()->country(['US', 'BE'])
The validator will check if the number is valid in at least one of provided countries, so feel free to add as many country codes as you like.
You provide a dedicated country input field (keyed by ISO 3166-1 compliant country codes) to allow end users to supply a country on their own. Make sure the country field has the same name as the phone field but with _country appended for automatic discovery, or provide your custom country field name as a parameter to the validator:
'phonefield' => 'phone',
// 'phonefield' => Rule::phone()
'phonefield_country' => 'required_with:phonefield',
'phonefield' => 'phone:custom_country_field',
// 'phonefield' => Rule::phone()->countryField('custom_country_field')
'custom_country_field' => 'required_with:phonefield',
You instruct the validator to detect which country the number belongs to using the AUTO
keyword (and optionally any fallback countries):
'phonefield' => 'phone:AUTO,US',
// 'phonefield' => Rule::phone()->detect()->country('US')
The validator will try to extract the country from the number itself and then check if the number is valid for that country. If the country could not be guessed it will be validated using the fallback countries if provided. Note that country guessing will only work when phone numbers are entered in international format (prefixed with a +
sign, e.g. +32 ....). Leading double zeros will NOT be parsed correctly as this isn't an established consistency.
To specify constraints on the number type, just append the allowed types to the end of the parameters, e.g.:
'phonefield' => 'phone:US,BE,mobile',
// 'phonefield' => Rule::phone()->country(['US', 'BE'])->type('mobile')
// 'phonefield' => Rule::phone()->country('US', 'BE')->mobile()
The most common types are mobile
and fixed_line
, but feel free to use any of the types defined here.
You can also enable more lenient validation (for example, fixed lines without area codes) by using the LENIENT
parameter. This feature inherently doesn't play well with country autodetection and number type validation, so use such combo at own risk.
'phonefield' => 'phone:LENIENT,US',
// 'phonefield' => Rule::phone()->lenient()->country('US')
Two cast classes are provided for automatic casting of Eloquent model attributes:
use Illuminate\Database\Eloquent\Model;
use Propaganistas\LaravelPhone\Casts\RawPhoneNumberCast;
use Propaganistas\LaravelPhone\Casts\E164PhoneNumberCast;
class User extends Model
{
public $casts = [
'phone' => RawPhoneNumberCast::class.':BE',
'another_phone' => E164PhoneNumberCast::class.':BE',
];
}
Both classes automatically cast the database value to a PhoneNumber object for further use in your application.
$user->phone // PhoneNumber object or null
When setting a value, they both accept a string value or a PhoneNumber object.The RawPhoneNumberCast
mutates the database value to the raw input number, while the E164PhoneNumberCast
writes a formatted E.164 phone number to the database.
In case of RawPhoneNumberCast
, the cast needs to be hinted about the phone country in order to properly parse the raw number into a phone object.In case of E164PhoneNumberCast
and the value to be set is not already in some international format, the cast needs to be hinted about the phone country in order to properly mutate the value.
Both classes accept cast parameters in the same way:
_country
(e.g. phone_country), the cast will detect and use it automatically.public $casts = [
'phone' => RawPhoneNumberCast::class.':country_field',
'another_phone' => E164PhoneNumberCast::class.':BE',
];
In order to not encounter any unexpected issues when using these casts, please always validate any input using the validation rules previously described.
E164PhoneNumberCast
Due to the nature of E164PhoneNumberCast
a valid country attribute is expected if the number is not passed in international format. Since casts are applied in the order of the given values, be sure to set the country attribute before setting the phone number attribute. Otherwise E164PhoneNumberCast
will encounter an empty country value and throw an unexpected exception.
// Wrong
$model->fill([
'phone' => '012 34 56 78',
'phone_country' => 'BE',
]);
// Correct
$model->fill([
'phone_country' => 'BE',
'phone' => '012 34 56 78',
]);
// Wrong
$model->phone = '012 34 56 78';
$model->phone_country = 'BE';
// Correct
$model->phone_country = 'BE';
$model->phone = '012 34 56 78';
A phone number can be wrapped in the Propaganistas\LaravelPhone\PhoneNumber
class to enhance it with useful utility methods. It's safe to directly reference these objects in views or when saving to the database as they will degrade gracefully to the E.164 format.
use Propaganistas\LaravelPhone\PhoneNumber;
(string) PhoneNumber::make('+3212/34.56.78'); // +3212345678
(string) PhoneNumber::make('012 34 56 78', 'BE'); // +3212345678
(string) PhoneNumber::make('012345678')->ofCountry('BE'); // +3212345678
A PhoneNumber can be formatted in various ways:
PhoneNumber::make('012 34 56 78', 'BE')->format($format); // See libphonenumber\PhoneNumberFormat
PhoneNumber::make('012 34 56 78', 'BE')->formatE164(); // +3212345678
PhoneNumber::make('012 34 56 78', 'BE')->formatInternational(); // +32 12 34 56 78
PhoneNumber::make('012 34 56 78', 'BE')->formatRFC3966(); // +32-12-34-56-78
PhoneNumber::make('012/34.56.78', 'BE')->formatNational(); // 012 34 56 78
// Formats so the number can be called straight from the provided country.
PhoneNumber::make('012 34 56 78', 'BE')->formatForCountry('BE'); // 012 34 56 78
PhoneNumber::make('012 34 56 78', 'BE')->formatForCountry('NL'); // 00 32 12 34 56 78
PhoneNumber::make('012 34 56 78', 'BE')->formatForCountry('US'); // 011 32 12 34 56 78
// Formats so the number can be clicked on and called straight from the provided country using a cellphone.
PhoneNumber::make('012 34 56 78', 'BE')->formatForMobileDialingInCountry('BE'); // 012345678
PhoneNumber::make('012 34 56 78', 'BE')->formatForMobileDialingInCountry('NL'); // +3212345678
PhoneNumber::make('012 34 56 78', 'BE')->formatForMobileDialingInCountry('US'); // +3212345678
Get some information about the phone number:
PhoneNumber::make('012 34 56 78', 'BE')->getType(); // 'fixed_line'
PhoneNumber::make('012 34 56 78', 'BE')->isOfType('fixed_line'); // true
PhoneNumber::make('012 34 56 78', 'BE')->getCountry(); // 'BE'
PhoneNumber::make('012 34 56 78', 'BE')->isOfCountry('BE'); // true
PhoneNumber::make('+32 12 34 56 78')->isOfCountry('BE'); // true
The package exposes the phone()
helper function that returns a Propaganistas\LaravelPhone\PhoneNumber
instance or the formatted string if $format
was provided:
phone($number, $country = [], $format = null)
Disclaimer: Phone number handling is quite different in each application. The topics mentioned below are therefore meant as a set of thought starters; support will not be provided.
Storing phone numbers in a database has always been a speculative topic and there's simply no silver bullet. It all depends on your application's requirements. Here are some things to take into account, along with an implementation suggestion. Your ideal database setup will probably be a combination of some of the pointers detailed below.
The E.164 format globally and uniquely identifies a phone number across the world. It also inherently implies a specific country and can be supplied as-is to the phone()
helper.
You'll need:
Example:
012/45.65.78
phone
(varchar) = +3212456578
If you store formatted phone numbers the raw user input will unretrievably get lost. It may be beneficial to present your users with their very own inputted phone number, for example in terms of improved user experience.
You'll need:
Example:
012/34.56.78
phone
(varchar) = 012/34.56.78
phone_country
(varchar) = BE
Searching through phone numbers can quickly become ridiculously complex and will always require deep understanding of the context and extent of your application. Here's a possible approach covering quite a lot of "natural" use cases.
You'll need:
saving()
observer (or equivalent) to prefill the variants before persistenceExample:
12/34.56.78
public function saving(User $user)
{
if ($user->isDirty('phone') && $user->phone) {
$user->phone_normalized = preg_replace('[^0-9]', '', $user->phone);
$user->phone_national = preg_replace('[^0-9]', '', phone($user->phone, $user->phone_country)->formatNational());
$user->phone_e164 = phone($user->phone, $user->phone_country)->formatE164();
}
}
phone_normalized
(varchar) = 12345678
phone_national
(varchar) = 012345678
phone_e164
(varchar) = +3212345678
// $search holds the search term
User::where(function($query) use ($search) {
$query->where('phone_normalized', 'LIKE', preg_replace('[^0-9]', '', $search) . '%')
->orWhere('phone_national', 'LIKE', preg_replace('[^0-9]', '', $search) . '%')
->orWhere('phone_e164', 'LIKE', preg_replace('[^+0-9]', '', $search) . '%')
});
class GosAutoAdmin extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'gos:admin {table} {model} {modelTitle}'
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Jobs\ProcessPodcast; use App\Models\Admin\Admission; use App\Models\Admin\Order; use App\Models\Admin\Userdo; u
<?php namespace App\Http\Controllers\api; use App\Http\Controllers\Controller; use App\Models\ych\Concert; use App\Models\ych\Hall; use App\Models\ych\Seat; use App\Models\ych\Ticket; use App\Models
默认的csv导出有中文乱码的问题,需修改一下CsvExporter.php文件 打开 vendor/encore/laravel-admin/src/Grid/Exporters/CsvExporter.php 在public function export() 的$headers后面添加 print(chr(0xEF).chr(0xBB).chr(0xBF)); 但还是不太方便,改为用lar
安装laravel composer create-project --prefer-dist laravel/laravel larabbs "8.*" 查看版本号 php artisan --version 伪静态 location / { try_files $uri $uri/ /index.php?$query_string; } laravel-modules安装 首先在
<?php namespace App\Http\Controllers\api; use App\Http\Controllers\Controller; use App\Models\ych\Concert; use App\Models\ych\Hall; use App\Models\ych\Seat; use App\Models\ych\Ticket; use App\Models
概述 Laravel 是一个非常流行的 PHP 框架,我们可以使用它快速构建一个 WEB 应用程序。而现在 WEB 应用中多会采用前后端分离技术,所以我们经常会遇到使用 Laravel 搭建 API 项目的需求。 Laravel 在提供 API 这方面,很多地方都只是提供了一个规范,并没有告诉我们如何去实现它。这样带来的好处是 Laravel 放开了限制,使大家可以按照自己的习惯去使用它。 但这样
<?php namespace App\Http\Controllers\api; use App\Http\Controllers\Controller; use App\Models\ych\Concert; use App\Models\ych\Hall; use App\Models\ych\Seat; use App\Models\ych\Ticket; use App\Models
查询构造器 介绍 数据库查询构造器 (query builder) 提供方便流畅的接口来建立、执行数据库查询语法。在您的应用程序里面,它可以被使用在大部分的数据 库操作,而且它在所有支持的数据库系统上都可以执行。注意: Laravel 查询构造器使用 PDO 参数绑定,以保护应用程序免于SQL注入攻击 (SQL injection),因此传入的参数不需过滤额外的特殊字符串。 Selects 从数据
Laravel 是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。 功能特点 1、语法更富有表现力 你知道下面这行代码里 “true” 代表什么意思么? $uri = Uri::create(‘some/uri’, array(), array(), tr
我需要空间/Laravel权限的帮助。当我试图分配它给我错误哎呀,看起来像出了问题。 错误 Connection.php第761行中的QueryExcema:SQLSTATE[23000]:完整性约束冲突:1048列role_id不能为空(SQL:插入到(,)值(9,))
Laravel 作为现在最流行的 PHP 框架,其中的知识较多,所以单独拿出来写一篇。 简述 Laravel 的生命周期 Laravel 采用了单一入口模式,应用的所有请求入口都是 public/index.php 文件。 注册类文件自动加载器 : Laravel通过 composer 进行依赖管理,无需开发者手动导入各种类文件,而由自动加载器自行导入。 创建服务容器:从 bootstrap/ap
简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer
简介 Laravel 致力于让整个 PHP 开发体验变得愉快, 包括你的本地开发环境。 Vagrant 提供了一种简单,优雅的方式来管理和配置虚拟机。 Laravel Homestead 是一个官方预封装的 Vagrant box,它为你提供了一个完美的开发环境,而无需在本地机器安装 PHP 、Web 服务器和其他服务器软件。不用担心会搞乱你的操作系统!Vagrant boxes 是一次性的。如果
WebStack-Laravel 一个开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己的网址导航。 部署 克隆代码: git clone https://github.com/hui-ho/WebStack-Laravel.git 安装依赖: composer installphp artisan key:generate 编辑配置: cp .env.example .env ...D
百度编辑器 For Laravel 5 支持自定义路由, 默认前后台独立控制器,支持重写方法方便自己的业务逻辑处理,支持扩展图片助手(推荐使用Intervention\Image第三方包) 官网 NinJa911工作室. 疑问讨论 请在issue里new一个. 授权 此Laravel 扩展包基于MIT协议开源MIT license. 安装 1.Composer 安装 composer requir
laravel-admin是一个基于laravel的后台管理开发框架,能帮助你使用很少的时间和代码量开发出功能完备的管理后台,另外它作为一个三方包,可以和框架内其它项目并行开发,真正做到前后台开发分离。 功能: RBAC权限管理模块。 菜单管理,和权限系统结合。 模型数据表格,能快速构建数据表格,并支持多种模型关系。 模型表单以及30+种form元素组件,自动实现增、删、改功能。 支持本地和云存储