You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Implementação de rotas de login, register e logout usando o Laravel Sanctum com testes.
Rotas:
// routes/api.phpuseIlluminate\Http\Request;
useIlluminate\Support\Facades\Route;
useApp\Http\Controllers\Auth\RegisteredUserController;
// Rota de registroRoute::post('/register', [RegisteredUserController::class, 'store']);
// Rota de loginRoute::post('/login', function (Request$request) {
// Validar as credenciais do usuárioif (auth()->attempt($request->only('email', 'password'))) {
// Criar e retornar um token para o usuário$token = auth()->user()->createToken('AuthToken')->plainTextToken;
returnresponse()->json(['token' => $token]);
}
// Caso as credenciais sejam inválidasreturnresponse()->json(['error' => 'Credenciais inválidas'], 401);
});
// Rota de logoutRoute::post('/logout', function (Request$request) {
// Revoke o token atual do usuário autenticado$request->user()->currentAccessToken()->delete();
returnresponse()->json(['message' => 'Logout realizado com sucesso']);
})->middleware('auth:sanctum');
Testes:
Testes para as rotas de login, register e logout:
This file contains 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
// You can use this on your middleware logic:// If system bypas on proxy (E.g load balancer, nginx proxy, etc)// X-FORWARDED-FOR$remoteAddress = $request->header('X-FORWARDED-FOR');
// or$remoteAddress = $request->header('X-FORWARDED-FOR') ?? $request->header('REMOTE-ADDR');
// Default remote address// REMOTE-ADDR$remoteAddress = $request->header('REMOTE-ADDR');
$allowedAddresses = [
'192.168.1.50',
'192.17.1.50/24',
'10.17.0.0/16',
];
if (!\Symfony\Component\HttpFoundation\IpUtils::checkIp($remoteAddress, $allowedAddresses)) {
abort(403); // By security proposes, I use 404 (prevent bots)
}
// All right. Is allowed
#----------------------------------------------------//Out of convention/** * The primary key associated with the table. * * @var string */protected$primaryKey = 'flight_id';
/** * Indicates if the model's ID is auto-incrementing. * * @var bool */public$incrementing = false;
/** * The data type of the auto-incrementing ID. * * @var string */protected$keyType = 'string';
#----------------------------------------------------
<<<'ENV'
# Abrir arquivo no debug ignition com o VSCode e mudando o tema para dark//Mais em vendor/facade/ignition/config/ignition.php/* ENVsIGNITION_EDITOR='vscode'IGNITION_THEME='dark'
ENV;
#----------------------------------------------------#like foreach chunk loop foreach eloquent model quebra em pedaçosFlight::chunk(200, function ($flights) {
foreach ($flightsas$flight) {
//
}
});
#----------------------------------------------------
<<<'blade'
No template@stack('styles')No herdeiro@push('styles')@endpush
blade;
//Laravel model custom methods - > best way is using traits// https://stackoverflow.com/a/70550612/11716408
<<<'PHP'
//Stet #1: Create a trait//Stet #2: Add to model//Stet #3: Use the method//Stet #4: User::first()->confirmEmailNow()//app/Model/User.phpuse App\Traits\EmailConfirmation;class User extends Authenticatable{ use EmailConfirmation; //...}//app/Traits/EmailConfirmation.php<?phpnamespace App\Traits;trait EmailConfirmation{ /** * Set email_verified_at to now and save. * */ public function confirmEmailNow() { $this->email_verified_at = now(); $this->save(); return $this; }}
PHP;
// Posso usar tanto pela model quanto pela factory
ChamadoFactory::times(3)->create();
Chamado::factory()->times(3)->create();
#----------------------------------------------------
])
#----------------------------------------------------
--WhereJson pesquisa por valor do json
select preferences->'beta' from users where (preferences->>'beta')::boolean is true;
--Pesquisar se JSON é vazio
Eloquent: ->whereJsonLength('domain_names', '<=', 0)
--Mesmo resultado que
and t.domain_names::text = '[]'
and json_array_length(("domain_names")::json) <= 0
--Select query regex? busca com regex
where lower(domain_names::text) similar to '%(gmail.com|yahoo.com)%'
where lower(resultado::text) similar to '%(positivo)%'
where resultado::text similar to '%(positivo)%'
#----------------------------------------------------
#----------------------------------------------------
//php - change database connection in laravel model - Stack Overflow
#https://stackoverflow.com/questions/28985472/change-database-connection-in-laravel-model
$ClientRO = new ClientRO(); $ClientRO->setConnection('dev_pgsql'); $ClientRO->where('id', 1123)->first();
(new ClientRO())->on('dev_pgsql')->get()->where('id', 1123)->first();
#----------------------------------------------------
//Detalhes da coluna de uma tabela
https://stackoverflow.com/a/18563068/11716408
//Qual é o tipo de uma coluna
$coluna->getType()->getName();
//Se o campo é obrigatório (not null)
$coluna->getNotnull();
//Valor default
$coluna->getDefault();
//Todos os métodos disponíveis:
get_class_methods($coluna);
#----------------------------------------------------
//Pesquisar com e sem scope (search)
//modo 1
public static function scopeSearch($query, $search)
{
$search = str_replace(['-'], '%', \Str::slug($search));
$numeric_search = !is_numeric($search) ? ''
: "id::text like '%". $search ."%' OR";
$paciente = $query->whereRaw("(
$numeric_search
LOWER(name) like '%". strtolower($search) ."%' OR
LOWER(sku) like '%". strtolower($search) ."%' OR
LOWER(codigo) like '%". strtolower($search) ."%' OR
LOWER(descricao_curta) like '%". strtolower($search) ."%'
)");
return $query;
#----------------------------------------------------
//Where com range de data usando whereRaw
->whereRaw('examined_at >= ?', [$start_date])
->whereRaw('examined_at <= ?', [$end_date])
#----------------------------------------------------
//Delete/update cascade na model sem migration
public function users()
{
return $this->hasMany('App\User');
}
public static function boot()
{
//Ao excluir um uma entidade dessa model(X), exclui também a relação em Y
//https://stackoverflow.com/a/20108037/11716408
parent::boot();
// antes de chamar o método delete() chama faz a(s) ações abaixo
static::deleting(function($supplier)
{
//Remove a referência (quando o campo é NULLABLE)
$supplier->users()->update(['supplier_id' => null]);
// ou
//Exclui os elementos com referência (Não entra aqui se a referência for removida na linha anterior)
$supplier->users()->delete();
});
// antes de chamar o método update() chama faz a(s) ações abaixo
static::updating(function($supplier)
{
//Ação: atualiza o ip
$supplier->users()->update(['supplier_id' => $supplier->id]);
});
#----------------------------------------------------
//Email templates:
http://dev.tiagofranca.com/notas/devemailtemplate_01
#----------------------------------------------------
//Usando o Gate/Can @can
https://www.itsolutionstuff.com/post/laravel-gates-and-policies-tutorial-with-exampleexample.html
#----------------------------------------------------
//Where and (or) / Multiplas verificações por exemplo em uma busca por 'name' ou 'email'
if(request()->search && !empty(request()->search))
{
$users = $users->whereRaw("(name like '%". strtolower(request()->search) ."%' or email like '%". strtolower(request()->search) ."%')");
}
//No SQL ficará assim:
where role_id in (1, 2)
and (name like '%admin%' or email like '%admin%')
#----------------------------------------------------
#----------------------------------------------------
//Automatically deleting related rows in Laravel (Eloquent ORM): https://stackoverflow.com/a/20108037/11716408
//model events
class User extends Eloquent
{
public function photos()
{
return $this->has_many('Photo');
}
// this is a recommended way to declare event handlers
public static function boot() {
parent::boot();
static::deleting(function($user) { // before delete() method call this
$user->photos()->delete();
// do the rest of the cleanup...
});
}
#----------------------------------------------------
//Unset um valor da request
unset($request['contrato_id']);
#----------------------------------------------------
//Laravel cache (redis, file)
/* START CACHE SET */
$expiration = 30; //secs
$url = request()->url();
$queryParams = request()->query();
ksort($queryParams);
$queryString = http_build_query($queryParams);
$fullUrl = "{$url}?{$queryString}";
$key_to_cache = sha1($fullUrl);
/* END CACHE SET */
$pacientes = \Illuminate\Support\Facades\Cache::remember($key_to_cache, $expiration /*secs*/, function () use ($pacientes) {
return $pacientes->paginate(20);
});
#----------------------------------------------------
//Busca textual full text com Laravel collections
$paises = \Illuminate\Support\Facades\Cache::remember('paises', 3600 /secs/, function () {
return \App\Enums\Countries::enumList();
});
$itemCollection = collect($paises);
$search = 'bras';
$filtered = $itemCollection->filter(function($item) use ($search) {
This file contains 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
//nos snippets tem o arquivo: ExecTimeTrack.php//Rastrear pontos da aplicação que demoram mais tempo$timer = newExecTimeTrack('aaa');
$timer->startCheckpointToList('validacao');
sleep(1);
$timer->endCheckpointToList('validacao');
dd($timer->getCheckpointList());
This file contains 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
Warning: This feature is experimental, and you may encounter bugs while using it. Please report any issues you find to Livewire with a pull request containing a failing test.
SPA mode utilizes Livewire's wire:navigate feature to make your server-rendered panel feel like a single-page-application, with less delay between page loads and a loading bar for longer requests. To enable SPA mode on a panel, you can use the spa() method:
Placeholder::make('open_child_modal')
->disableLabel()
->content(
newHtmlString('Click <button onclick="Livewire.emit(\'modal:open\', \'create-user-child\')" type="button" class="text-primary-500">here</button> to open a child modal🤩')
),
// View column// You may render a custom view for a cell using the view() method:useFilament\Tables\Columns\ViewColumn;
ViewColumn::make('status')->view('filament.tables.columns.status-switcher');
// Inside your view, you may retrieve the state of the cell using the $getState() method:
<div>
{{ $getState() }}
</div>
Custom row classes (v3)
You may want to conditionally style rows based on the record data. This can be achieved by specifying a string or array of CSS classes to be applied to the row using the $table->recordClasses() method:
You may want to conditionally style rows based on the record data. This can be achieved by specifying a string or array of CSS classes to be applied to the row using the $table->recordClasses() method:
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
runOnQueueScope('sync', fn () => /* Your actions here */);
// orrunOnQueueScope('sync', function() {
/* Your actions here */
});
// Other connectionrunOnQueueScope('another-queue-connection', function() {
/* Your actions here */
});
Algumas das design patterns mais usadas no PHP e Laravel incluem:
Factory Pattern: Nesse padrão, uma classe cria o objeto que você deseja usar. Por exemplo, em Laravel, o Factory Pattern é usado para criar instâncias de modelos de banco de dados[4].
Facade Pattern: O Facade Pattern é usado para simplificar a interface de um sistema complexo, oferecendo uma interface simples e intuitiva para os usuários[4].
Observer Pattern: O Observer Pattern é usado para notificar objetos sobre eventos ou alterações em outros objetos. Em Laravel, o Observer Pattern é usado para registrar eventos e executar ações quando esses eventos ocorrem[5].
Pipeline Pattern: O Pipeline Pattern é usado para executar uma série de etapas em uma sequência específica. Em Laravel, o Pipeline Pattern é usado para processar requisições HTTP e executar ações em cada etapa do pipeline[5].
Command Pattern: O Command Pattern é usado para encapsular uma operação e executá-la depois. Em Laravel, o Command Pattern é usado para executar tarefas específicas, como enviar e-mails ou executar tarefas de manutenção[5].
Essas design patterns são amplamente adotadas pela comunidade de desenvolvimento de software e oferecem suporte para diferentes aspectos da implementação e operação de aplicativos em PHP e Laravel.
Além dos design patterns mencionados, existem outros amplamente utilizados em diferentes tecnologias. Os design patterns são soluções comuns para problemas recorrentes no desenvolvimento de software, e existem três categorias principais: Padrões Criacionais, Padrões Estruturais e Padrões Comportamentais[4].
Alguns exemplos adicionais de design patterns incluem:
Singleton Pattern: Garante que uma classe tenha apenas uma instância e fornece um ponto global de acesso a essa instância[4].
Adapter Pattern: Permite que a interface de uma classe seja usada como interface esperada por outra classe[4].
Decorator Pattern: Adiciona responsabilidades a objetos de forma dinâmica[4].
Strategy Pattern: Define uma família de algoritmos, encapsula cada um deles e os torna intercambiáveis[4].
Esses design patterns são aplicáveis em diversas tecnologias e podem contribuir significativamente para a eficiência, flexibilidade e legibilidade do código.
O Repository Pattern é um padrão de projeto de software que cria uma camada de abstração entre a camada de domínio e a camada de acesso a dados, isolando objetos de domínio dos detalhes do código de acesso ao banco de dados e minimizando a dispersão e a duplicação do código de consulta[1].
O Repository Pattern é especialmente útil em sistemas onde o número de objetos de domínio é grande ou onde há pesquisas pesadas utilizadas[1]. Algumas vantagens do Repository Pattern incluem:
Melhor manutenção, pois centraliza a funcionalidade de acesso a dados comum[1].
Decoupling da infraestrutura ou tecnologia usada para acessar bancos de dados do modelo de domínio[1].
Facilita a adição de novos objetos de domínio e a pesquisa de objetos existentes[1].
O Repository Pattern pode ser aplicado em diferentes tecnologias e linguagens de programação, como PHP, Laravel, Python e outras[1][2][3].
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
// If you factory is out of standard, you can set an specifc// On your model, create a static method named newFactoryprotectedstaticfunctionnewFactory()
{
return \Database\Factories\MyModelFactory::new();
}
//On your factory, add thisprotected$model = \App\Models\MyModel::class;
Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
Faker is heavily inspired by Perl's Data::Faker, and by ruby's Faker.
<?php# When installed via composerrequire_once'vendor/autoload.php';
You can also load Fakers shipped PSR-0 autoloader
<?php# Load Fakers own autoloaderrequire_once'/path/to/Faker/src/autoload.php';
alternatively, you can use any another PSR-4 compliant autoloader
Create fake data
Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.
<?php// use the factory to create a Faker\Generator instance$faker = Faker\Factory::create();
// generate data by accessing propertiesecho$faker->name;
// 'Lucy Cechtelar';echo$faker->address;
// "426 Jordy Lodge// Cartwrightshire, SC 88120-6700"echo$faker->text;
// Dolores sit sint laboriosam dolorem culpa et autem. Beatae nam sunt fugit// et sit et mollitia sed.// Fuga deserunt tempora facere magni omnis. Omnis quia temporibus laudantium// sit minima sint.
Even if this example shows a property access, each call to $faker->name yields a different (random) result. This is because Faker uses __get() magic, and forwards Faker\Generator->$property calls to Faker\Generator->format($property).
Tip: For a quick generation of fake data, you can also use Faker as a command line tool thanks to faker-cli.
Formatters
Each of the generator properties (like name, address, and lorem) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale.
word // 'aut'words($nb = 3, $asText = false) // array('porro', 'sed', 'magni')
sentence($nbWords = 6, $variableNbWords = true) // 'Sit vitae voluptas sint non voluptates.'sentences($nb = 3, $asText = false) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.')
paragraph($nbSentences = 3, $variableNbSentences = true) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.'paragraphs($nb = 3, $asText = false) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.')
text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.'
realText($maxNbChars = 200, $indexSize = 2) // "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied."
Methods accepting a $timezone argument default to date_default_timezone_get(). You can pass a custom timezone string to each method, or define a custom timezone for all time methods at once using $faker::setDefaultTimezone($timezone).
fileExtension // 'avi'
mimeType // 'video/x-msvideo'
// Copy a random file from the source to the target directory and returns the fullpath or filename
file($sourceDir = '/tmp', $targetDir = '/tmp') // '/path/to/targetDir/13b73edae8443990be1aa8f1a483bc27.jpg'file($sourceDir, $targetDir, false) // '13b73edae8443990be1aa8f1a483bc27.jpg'
// get a random number between 10 and 20,// with more chances to be close to 20biasedNumberBetween($min = 10, $max = 20, $function = 'sqrt')
Faker\Provider\HtmlLorem
//Generate HTML document which is no more than 2 levels deep, and no more than 3 elements wide at any level.randomHtml(2,3) // <html><head><title>Aut illo dolorem et accusantium eum.</title></head><body><form action="example.com" method="POST"><label for="username">sequi</label><input type="text" id="username"><label for="password">et</label><input type="password" id="password"></form><b>Id aut saepe non mollitia voluptas voluptas.</b><table><thead><tr><tr>Non consequatur.</tr><tr>Incidunt est.</tr><tr>Aut voluptatem.</tr><tr>Officia voluptas rerum quo.</tr><tr>Asperiores similique.</tr></tr></thead><tbody><tr><td>Sapiente dolorum dolorem sint laboriosam commodi qui.</td><td>Commodi nihil nesciunt eveniet quo repudiandae.</td><td>Voluptates explicabo numquam distinctio necessitatibus repellat.</td><td>Provident ut doloremque nam eum modi aspernatur.</td><td>Iusto inventore.</td></tr><tr><td>Animi nihil ratione id mollitia libero ipsa quia tempore.</td><td>Velit est officia et aut tenetur dolorem sed mollitia expedita.</td><td>Modi modi repudiandae pariatur voluptas rerum ea incidunt non molestiae eligendi eos deleniti.</td><td>Exercitationem voluptatibus dolor est iste quod molestiae.</td><td>Quia reiciendis.</td></tr><tr><td>Inventore impedit exercitationem voluptatibus rerum cupiditate.</td><td>Qui.</td><td>Aliquam.</td><td>Autem nihil aut et.</td><td>Dolor ut quia error.</td></tr><tr><td>Enim facilis iusto earum et minus rerum assumenda quis quia.</td><td>Reprehenderit ut sapiente occaecati voluptatum dolor voluptatem vitae qui velit.</td><td>Quod fugiat non.</td><td>Sunt nobis totam mollitia sed nesciunt est deleniti cumque.</td><td>Repudiandae quo.</td></tr><tr><td>Modi dicta libero quisquam doloremque qui autem.</td><td>Voluptatem aliquid saepe laudantium facere eos sunt dolor.</td><td>Est eos quis laboriosam officia expedita repellendus quia natus.</td><td>Et neque delectus quod fugit enim repudiandae qui.</td><td>Fugit soluta sit facilis facere repellat culpa magni voluptatem maiores tempora.</td></tr><tr><td>Enim dolores doloremque.</td><td>Assumenda voluptatem eum perferendis exercitationem.</td><td>Quasi in fugit deserunt ea perferendis sunt nemo consequatur dolorum soluta.</td><td>Maxime repellat qui numquam voluptatem est modi.</td><td>Alias rerum rerum hic hic eveniet.</td></tr><tr><td>Tempore voluptatem.</td><td>Eaque.</td><td>Et sit quas fugit iusto.</td><td>Nemo nihil rerum dignissimos et esse.</td><td>Repudiandae ipsum numquam.</td></tr><tr><td>Nemo sunt quia.</td><td>Sint tempore est neque ducimus harum sed.</td><td>Dicta placeat atque libero nihil.</td><td>Et qui aperiam temporibus facilis eum.</td><td>Ut dolores qui enim et maiores nesciunt.</td></tr><tr><td>Dolorum totam sint debitis saepe laborum.</td><td>Quidem corrupti ea.</td><td>Cum voluptas quod.</td><td>Possimus consequatur quasi dolorem ut et.</td><td>Et velit non hic labore repudiandae quis.</td></tr></tbody></table></body></html>
Modifiers
Faker provides three special providers, unique(), optional(), and valid(), to be called before any provider.
// unique() forces providers to return unique values$values = array();
for ($i = 0; $i < 10; $i++) {
// get a random digit, but always a new one, to avoid duplicates$values []= $faker->unique()->randomDigit;
}
print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3]// providers with a limited range will throw an exception when no new unique value can be generated$values = array();
try {
for ($i = 0; $i < 10; $i++) {
$values []= $faker->unique()->randomDigitNotNull;
}
} catch (\OverflowException$e) {
echo"There are only 9 unique digits not null, Faker can't generate 10 of them!";
}
// you can reset the unique modifier for all providers by passing true as first argument$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset// tip: unique() keeps one array of values per provider// optional() sometimes bypasses the provider to return a default value instead (which defaults to NULL)$values = array();
for ($i = 0; $i < 10; $i++) {
// get a random digit, but also null sometimes$values []= $faker->optional()->randomDigit;
}
print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null]// optional() accepts a weight argument to specify the probability of receiving the default value.// 0 will always return the default value; 1 will always return the provider. Default weight is 0.5 (50% chance).$faker->optional($weight = 0.1)->randomDigit; // 90% chance of NULL$faker->optional($weight = 0.9)->randomDigit; // 10% chance of NULL// optional() accepts a default argument to specify the default value to return.// Defaults to NULL.$faker->optional($weight = 0.5, $default = false)->randomDigit; // 50% chance of FALSE$faker->optional($weight = 0.9, $default = 'abc')->word; // 10% chance of 'abc'// valid() only accepts valid values according to the passed validator functions$values = array();
$evenValidator = function($digit) {
return$digit % 2 === 0;
};
for ($i = 0; $i < 10; $i++) {
$values []= $faker->valid($evenValidator)->randomDigit;
}
print_r($values); // [0, 4, 8, 4, 2, 6, 0, 8, 8, 6]// just like unique(), valid() throws an overflow exception when it can't generate a valid value$values = array();
try {
$faker->valid($evenValidator)->randomElement([1, 3, 5, 7, 9]);
} catch (\OverflowException$e) {
echo"Can't pick an even number in that set!";
}
If you would like to use a modifier with a value not generated by Faker, use the passthrough() method. passthrough() simply returns whatever value it was given.
$faker->optional()->passthrough(mt_rand(5, 15));
Localization
Faker\Factory can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_US).
<?php$faker = Faker\Factory::create('fr_FR'); // create a French fakerfor ($i = 0; $i < 10; $i++) {
echo$faker->name, "\n";
}
// Luce du Coulon// Auguste Dupont// Roger Le Voisin// Alexandre Lacroix// Jacques Humbert-Roy// Thérèse Guillet-Andre// Gilles Gros-Bodin// Amélie Pires// Marcel Laporte// Geneviève Marchal
You can check available Faker locales in the source code, under the Provider directory. The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR!
Populating Entities Using an ORM or an ODM
Faker provides adapters for Object-Relational and Object-Document Mappers (currently, Propel, Doctrine2, CakePHP, Spot2, Mandango and Eloquent are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library).
To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the execute() method.
Note that some of the populators could require additional parameters. As example the doctrine populator has an option to specify
its batchSize on how often it will flush the UnitOfWork to the database.
Here is an example showing how to populate 5 Author and 10 Book objects:
The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named first_name using the firstName formatter, and a column with a TIMESTAMP type using the dateTime formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to addEntity():
In this example, Faker will guess a formatter for all columns except ISBN, for which the given anonymous function will be used.
Tip: To ignore some columns, specify null for the column names in the third argument of addEntity(). This is usually necessary for columns added by a behavior:
Of course, Faker does not populate autoincremented primary keys. In addition, Faker\ORM\Propel\Populator::execute() returns the list of inserted PKs, indexed by class:
Note: Due to the fact that Faker returns all the primary keys inserted, the memory consumption will go up drastically when you do batch inserts due to the big list of data.
In the previous example, the Book and Author models share a relationship. Since Author entities are populated first, Faker is smart enough to relate the populated Book entities to one of the populated Author entities.
Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the addEntity() method:
You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a seed() method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results.
Tip: DateTime formatters won't reproduce the same fake data if you don't fix the $max value:
<?php// even when seeded, this line will return different results because $max varies$faker->dateTime(); // equivalent to $faker->dateTime($max = 'now')// make sure you fix the $max parameter$faker->dateTime('2014-02-25 08:37:17'); // will return always the same date when seeded
Tip: Formatters won't reproduce the same fake data if you use the rand() php function. Use $faker or mt_rand() instead:
A Faker\Generator alone can't do much generation. It needs Faker\Provider objects to delegate the data generation to them. Faker\Factory::create() actually creates a Faker\Generator bundled with the default providers. Here is what happens under the hood:
Whenever you try to access a property on the $faker object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling $faker->name triggers a call to Faker\Provider\Person::name(). And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override.
That means that you can easily add your own providers to a Faker\Generator instance. A provider is usually a class extending \Faker\Provider\Base. This parent class allows you to use methods like lexify() or randomNumber(); it also gives you access to formatters of other providers, through the protected $generator property. The new formatters are the public methods of the provider class.
Here is an example provider for populating Book data:
Running this script produces a document looking like:
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<contactfirstName="Ona"lastName="Bednar"email="[email protected]">
<phonenumber="1-265-479-1196x714"/>
<address>
<street>182 Harrison Cove</street>
<city>North Lloyd</city>
<postcode>45577</postcode>
<state>Alabama</state>
</address>
<companyname="Veum, Funk and Shanahan"catchPhrase="Function-based stable solution">
<offer>orchestrate compelling web-readiness</offer>
</company>
<details>
<![CDATA[Alias accusantium voluptatum autem nobis cumque neque modi. Voluptatem error molestiae consequatur alias.Illum commodi molestiae aut repellat id. Et sit consequuntur aut et ullam asperiores. Cupiditate culpa voluptatem et mollitia dolor. Nisi praesentium qui ut.]]>
</details>
</contact>
<contactfirstName="Aurelie"lastName="Paucek"email="[email protected]">
<phonenumber="863.712.1363x9425"/>
<address>
<street>90111 Hegmann Inlet</street>
<city>South Geovanymouth</city>
<postcode>69961-9311</postcode>
<state>Colorado</state>
</address>
<companyname="Krajcik-Grimes"catchPhrase="Switchable cohesive instructionset">
</company>
</contact>
<contactfirstName="Clifton"lastName="Kshlerin"email="[email protected]">
<phonenumber="692-194-4746"/>
<address>
<street>9791 Nona Corner</street>
<city>Harberhaven</city>
<postcode>74062-8191</postcode>
<state>RhodeIsland</state>
</address>
<companyname="Rosenbaum-Aufderhar"catchPhrase="Realigned asynchronous encryption">
</company>
</contact>
<contactfirstName="Alexandre"lastName="Orn"email="[email protected]">
<phonenumber="189.655.8677x027"/>
<address>
<street>11161 Schultz Via</street>
<city>Feilstad</city>
<postcode>98019</postcode>
<state>NewJersey</state>
</address>
<companyname="O'Hara-Prosacco"catchPhrase="Re-engineered solution-oriented algorithm">
<directorname="Dr. Berenice Auer V" />
</company>
<details>
<![CDATA[Ut itaque et quaerat doloremque eum praesentium. Rerum in saepe dolorem. Explicabo qui consequuntur commodi minima rem.Harum temporibus rerum dolores. Non molestiae id dolorem placeat.Aut asperiores nihil eius repellendus. Vero nihil corporis voluptatem explicabo commodi. Occaecati omnis blanditiis beatae quod aspernatur eos.]]>
</details>
</contact>
<contactfirstName="Katelynn"lastName="Kohler"email="[email protected]">
<phonenumber="(665)713-1657"/>
<address>
<street>6106 Nader Village Suite 753</street>
<city>McLaughlinstad</city>
<postcode>43189-8621</postcode>
<state>Missouri</state>
</address>
<companyname="Herman-Tremblay"catchPhrase="Object-based explicit service-desk">
<offer>expedite viral synergies</offer>
<directorname="Arden Deckow" />
</company>
</contact>
<contactfirstName="Blanca"lastName="Stark"email="[email protected]">
<phonenumber="168.719.4692x87177"/>
<address>
<street>7546 Kuvalis Plaza</street>
<city>South Wilfrid</city>
<postcode>77069</postcode>
<state>Georgia</state>
</address>
<companyname="Upton, Braun and Rowe"catchPhrase="Visionary leadingedge pricingstructure">
</company>
</contact>
<contactfirstName="Rene"lastName="Spencer"email="[email protected]">
<phonenumber="715.222.0095x175"/>
<birthdate="2008-08-07"place="Zulaufborough"/>
<address>
<street>478 Daisha Landing Apt. 510</street>
<city>West Lizethhaven</city>
<postcode>30566-5362</postcode>
<state>WestVirginia</state>
</address>
<companyname="Wiza Inc"catchPhrase="Persevering reciprocal approach">
<offer>orchestrate dynamic networks</offer>
<directorname="Erwin Nienow" />
</company>
<details>
<![CDATA[Dolorem consequatur voluptates unde optio unde. Accusantium dolorem est est architecto impedit. Corrupti et provident quo.Reprehenderit dolores aut quidem suscipit repudiandae corporis error. Molestiae enim aperiam illo.Et similique qui non expedita quia dolorum. Ex rem incidunt ea accusantium temporibus minus non.]]>
</details>
</contact>
<contactfirstName="Alessandro"lastName="Hagenes"email="[email protected]">
<phonenumber="1-284-958-6768"/>
<address>
<street>1251 Koelpin Mission</street>
<city>North Revastad</city>
<postcode>81620</postcode>
<state>Maryland</state>
</address>
<companyname="Stiedemann-Bruen"catchPhrase="Re-engineered 24/7 success">
</company>
</contact>
<contactfirstName="Novella"lastName="Rutherford"email="[email protected]">
<phonenumber="(091)825-7971"/>
<address>
<street>6396 Langworth Hills Apt. 446</street>
<city>New Carlos</city>
<postcode>89399-0268</postcode>
<state>Wyoming</state>
</address>
<companyname="Stroman-Legros"catchPhrase="Expanded 4thgeneration moratorium">
<directorname="Earlene Bayer" />
</company>
</contact>
<contactfirstName="Andreane"lastName="Mann"email="[email protected]">
<phonenumber="941-659-9982x5689"/>
<birthdate="1934-02-21"place="Stantonborough"/>
<address>
<street>2246 Kreiger Station Apt. 291</street>
<city>Kaydenmouth</city>
<postcode>11397-1072</postcode>
<state>Wyoming</state>
</address>
<companyname="Lebsack, Bernhard and Kiehn"catchPhrase="Persevering actuating framework">
<offer>grow sticky portals</offer>
</company>
<details>
<![CDATA[Quia dolor ut quia error libero. Enim facilis iusto earum et minus rerum assumenda. Quia doloribus et reprehenderit ut. Occaecati voluptatum dolor voluptatem vitae qui velit quia.Fugiat non in itaque sunt nobis totam. Sed nesciunt est deleniti cumque alias. Repudiandae quo aut numquam modi dicta libero.]]>
</details>
</contact>
</contacts>
Language specific formatters
Faker\Provider\ar_SA\Person
<?phpecho$faker->idNumber; // ID numberecho$faker->nationalIdNumber // CitizenID number
echo $faker->foreignerIdNumber // ForeignerID number
echo $faker->companyIdNumber // CompanyID number
<?phpecho$faker->vat; // "AT U12345678" - Austrian Value Added Tax numberecho$faker->vat(false); // "ATU12345678" - unspaced Austrian Value Added Tax number
Faker\Provider\bg_BG\Payment
<?phpecho$faker->vat; // "BG 0123456789" - Bulgarian Value Added Tax numberecho$faker->vat(false); // "BG0123456789" - unspaced Bulgarian Value Added Tax number
Faker\Provider\cs_CZ\Address
<?phpecho$faker->region; // "Liberecký kraj"
Faker\Provider\cs_CZ\Company
<?php// Generates a valid IČOecho$faker->ico; // "69663963"
Faker\Provider\cs_CZ\DateTime
<?phpecho$faker->monthNameGenitive; // "prosince"echo$faker->formattedDate; // "12. listopadu 2015"
Faker\Provider\cs_CZ\Person
<?phpecho$faker->birthNumber; // "7304243452"
Faker\Provider\da_DK\Person
<?php// Generates a random CPR numberecho$faker->cpr; // "051280-2387"
Faker\Provider\da_DK\Address
<?php// Generates a random 'kommune' nameecho$faker->kommune; // "Frederiksberg"// Generates a random region nameecho$faker->region; // "Region Sjælland"
Faker\Provider\da_DK\Company
<?php// Generates a random CVR numberecho$faker->cvr; // "32458723"// Generates a random P numberecho$faker->p; // "5398237590"
Faker\Provider\de_CH\Person
<?php// Generates a random AVS13/AHV13 social security numberecho$faker->avs13; // "756.1234.5678.97" ORecho$faker->ahv13; // "756.1234.5678.97"
<?php// Generates a fake town name based on the words commonly found in Hong Kongecho$faker->town; // "Yuen Long"// Generates a fake village name based on the words commonly found in Hong Kongecho$faker->village; // "O Tau"// Generates a fake estate name based on the words commonly found in Hong Kongecho$faker->estate; // "Ching Lai Court"
Faker\Provider\en_HK\Phone
<?php// Generates a Hong Kong mobile number (starting with 5, 6 or 9)echo$faker->mobileNumber; // "92150087"// Generates a Hong Kong landline number (starting with 2 or 3)echo$faker->landlineNumber; // "32750132"// Generates a Hong Kong fax number (starting with 7)echo$faker->faxNumber; // "71937729"
Faker\Provider\en_NG\Address
<?php// Generates a random region nameecho$faker->region; // 'Katsina'
Faker\Provider\en_NG\Person
<?php// Generates a random person nameecho$faker->name; // 'Oluwunmi Mayowa'
Faker\Provider\en_NZ\Phone
<?php// Generates a cell (mobile) phone numberecho$faker->mobileNumber; // "021 123 4567"// Generates a toll free numberecho$faker->tollFreeNumber; // "0800 123 456"// Area Codeecho$faker->areaCode; // "03"
Faker\Provider\en_US\Company
<?php// Generate a random Employer Identification Numberecho$faker->ein; // '12-3456789'
<?php// Generates a random Social Security Numberecho$faker->ssn; // '123-45-6789'
Faker\Provider\en_ZA\Company
<?php// Generates a random company registration numberecho$faker->companyNumber; // 1999/789634/01
Faker\Provider\en_ZA\Person
<?php// Generates a random national identification numberecho$faker->idNumber; // 6606192211041// Generates a random valid licence codeecho$faker->licenceCode; // EB
Faker\Provider\en_ZA\PhoneNumber
<?php// Generates a special rate toll free phone numberecho$faker->tollFreeNumber; // 0800 555 5555// Generates a mobile phone numberecho$faker->mobileNumber; // 082 123 5555
Faker\Provider\es_ES\Person
<?php// Generates a Documento Nacional de Identidad (DNI) numberecho$faker->dni; // '77446565E'// Generates a random valid licence codeecho$faker->licenceCode; // B
Faker\Provider\es_ES\Payment
<?php// Generates a Código de identificación Fiscal (CIF) numberecho$faker->vat; // "A35864370"
Faker\Provider\es_ES\PhoneNumber
<?php// Generates a special rate toll free phone numberecho$faker->tollFreeNumber; // 900 123 456// Generates a mobile phone numberecho$faker->mobileNumber; // +34 612 12 24
Faker\Provider\es_PE\Person
<?php// Generates a Peruvian Documento Nacional de Identidad (DNI) numberecho$faker->dni; // '83367512'
Faker\Provider\fa_IR\Person
<?php// Generates a valid nationalCodeecho$faker->nationalCode; // "0078475759"
Faker\Provider\fa_IR\Address
<?php// Generates a random building nameecho$faker->building; // "ساختمان آفتاب"// Returns a random city nameecho$faker->city // "استان زنجان"
Faker\Provider\fa_IR\Company
<?php// Generates a random contract typeecho$faker->contract; // "رسمی"
Faker\Provider\fi_FI\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "FI8350799879879616"
Faker\Provider\fi_FI\Person
<?php//Generates a valid Finnish personal identity number (in Finnish - Henkilötunnus)echo$faker->personalIdentityNumber() // '170974-007J'
//Since the numbers are different for male and female persons, optionally you can specify gender.
echo $faker->personalIdentityNumber(\DateTime::createFromFormat('Y-m-d', '2015-12-14'), 'female') // '141215A520B'
Faker\Provider\fr_BE\Payment
<?phpecho$faker->vat; // "BE 0123456789" - Belgian Value Added Tax numberecho$faker->vat(false); // "BE0123456789" - unspaced Belgian Value Added Tax number
Faker\Provider\es_VE\Person
<?php// Generate a Cédula de identidad number, you can pass one argument to add separatorecho$faker->nationalId; // 'V11223344'
Faker\Provider\es_VE\Company
<?php// Generates a R.I.F. number, you can pass one argument to add separatorsecho$faker->taxpayerIdentificationNumber; // 'J1234567891'
Faker\Provider\fr_CH\Person
<?php// Generates a random AVS13/AHV13 social security numberecho$faker->avs13; // "756.1234.5678.97"
Faker\Provider\fr_FR\Address
<?php// Generates a random department nameecho$faker->departmentName; // "Haut-Rhin"// Generates a random department numberecho$faker->departmentNumber; // "2B"// Generates a random department info (department number => department name)$faker->department; // array('18' => 'Cher');// Generates a random regionecho$faker->region; // "Saint-Pierre-et-Miquelon"// Generates a random appartement,stairecho$faker->secondaryAddress; // "Bat. 961"
Faker\Provider\fr_FR\Company
<?php// Generates a random SIREN numberecho$faker->siren; // 082 250 104// Generates a random SIRET numberecho$faker->siret; // 347 355 708 00224
Faker\Provider\fr_FR\Payment
<?php// Generates a random VATecho$faker->vat; // FR 12 123 456 789
Faker\Provider\fr_FR\Person
<?php// Generates a random NIR / Sécurité Sociale numberecho$faker->nir; // 1 88 07 35 127 571 - 19
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "HU09904437680048220079300783"
Faker\Provider\id_ID\Person
<?php// Generates a random Nomor Induk Kependudukan (NIK)// first argument is gender, either Person::GENDER_MALE or Person::GENDER_FEMALE, if none specified random gender is used// second argument is birth date (DateTime object), if none specified, random birth date is usedecho$faker->nik(); // "8522246001570940"
Faker\Provider\it_CH\Person
<?php// Generates a random AVS13/AHV13 social security numberecho$faker->avs13; // "756.1234.5678.97"
Faker\Provider\it_IT\Company
<?php// Generates a random Vat Idecho$faker->vatId(); // "IT98746784967"
Faker\Provider\it_IT\Person
<?php// Generates a random Tax Id code (Codice fiscale)echo$faker->taxId(); // "DIXDPZ44E08F367A"
Faker\Provider\ja_JP\Person
<?php// Generates a 'kana' nameecho$faker->kanaName($gender = null|'male'|'female') // "アオタ ミノル"
// Generates a 'kana' first name
echo $faker->firstKanaName($gender = null|'male'|'female') // "ヒデキ"
// Generates a 'kana' first name on the male
echo$faker->firstKanaNameMale // "ヒデキ"
// Generates a 'kana' first name on the female
echo$faker->firstKanaNameFemale // "マアヤ"
// Generates a 'kana' last name
echo $faker->lastKanaName; // "ナカジマ"
Faker\Provider\ka_GE\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "GE33ZV9773853617253389"
Faker\Provider\kk_KZ\Company
<?php// Generates an business identification numberecho$faker->businessIdentificationNumber; // "150140000019"
Faker\Provider\kk_KZ\Payment
<?php// Generates a random bank nameecho$faker->bank; // "Қазкоммерцбанк"// Generates a random bank account numberecho$faker->bankAccountNumber; // "KZ1076321LO4H6X41I37"
Faker\Provider\kk_KZ\Person
<?php// Generates an individual identification numberecho$faker->individualIdentificationNumber; // "780322300455"// Generates an individual identification number based on his/her birth dateecho$faker->individualIdentificationNumber(new \DateTime('1999-03-01')); // "990301300455"
Faker\Provider\ko_KR\Address
<?php// Generates a metropolitan cityecho$faker->metropolitanCity; // "서울특별시"// Generates a boroughecho$faker->borough; // "강남구"
Faker\Provider\ko_KR\PhoneNumber
<?php// Generates a local area phone numerecho$faker->localAreaPhoneNumber; // "02-1234-4567"// Generates a cell phone numberecho$faker->cellPhoneNumber; // "010-9876-5432"
<?php// Generates a random personal identity card numberecho$faker->personalIdentityNumber; // "140190-12301"
Faker\Provider\ms_MY\Address
<?php// Generates a random Malaysian townshipecho$faker->township; // "Taman Bahagia"// Generates a random Malaysian town address with matching postcode and stateecho$faker->townState; // "55100 Bukit Bintang, Kuala Lumpur"
Faker\Provider\ms_MY\Miscellaneous
<?php// Generates a random vehicle license plate numberecho$faker->jpjNumberPlate; // "WPL 5169"
Faker\Provider\ms_MY\Payment
<?php// Generates a random Malaysian bankecho$faker->bank; // "Maybank"// Generates a random Malaysian bank account number (10-16 digits)echo$faker->bankAccountNumber; // "1234567890123456"// Generates a random Malaysian insurance companyecho$faker->insurance; // "AIA Malaysia"// Generates a random Malaysian bank SWIFT Codeecho$faker->swiftCode; // "MBBEMYKLXXX"
Faker\Provider\ms_MY\Person
<?php// Generates a random personal identity card (myKad) numberecho$faker->myKadNumber($gender = null|'male'|'female', $hyphen = null|true|false); // "710703471796"
Faker\Provider\ms_MY\PhoneNumber
<?php// Generates a random Malaysian mobile numberecho$faker->mobileNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "+6012-705 3767"// Generates a random Malaysian landline numberecho$faker->fixedLineNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "03-7112 0455"// Generates a random Malaysian voip numberecho$faker->voipNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "015-458 7099"
Faker\Provider\ne_NP\Address
<?php//Generates a Nepali district nameecho$faker->district;
//Generates a Nepali city nameecho$faker->cityName;
Faker\Provider\nl_BE\Payment
<?phpecho$faker->vat; // "BE 0123456789" - Belgian Value Added Tax numberecho$faker->vat(false); // "BE0123456789" - unspaced Belgian Value Added Tax number
Faker\Provider\nl_BE\Person
<?phpecho$faker->rrn(); // "83051711784" - Belgian Rijksregisternummerecho$faker->rrn('female'); // "50032089858" - Belgian Rijksregisternummer for a female
Faker\Provider\nl_NL\Company
<?phpecho$faker->jobTitle; // "Houtbewerker"echo$faker->vat; // "NL123456789B01" - Dutch Value Added Tax numberecho$faker->btw; // "NL123456789B01" - Dutch Value Added Tax number (alias)
Faker\Provider\nl_NL\Person
<?phpecho$faker->idNumber; // "111222333" - Dutch Personal identification number (BSN)
Faker\Provider\nb_NO\MobileNumber
<?php// Generates a random Norwegian mobile phone numberecho$faker->mobileNumber; // "+4799988777"echo$faker->mobileNumber; // "999 88 777"echo$faker->mobileNumber; // "99988777"
Faker\Provider\nb_NO\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "NO3246764709816"
Faker\Provider\pl_PL\Person
<?php// Generates a random PESEL numberecho$faker->pesel; // "40061451555"// Generates a random personal identity card numberecho$faker->personalIdentityNumber; // "AKX383360"// Generates a random taxpayer identification number (NIP)echo$faker->taxpayerIdentificationNumber; // '8211575109'
Faker\Provider\pl_PL\Company
<?php// Generates a random REGON numberecho$faker->regon; // "714676680"// Generates a random local REGON numberecho$faker->regonLocal; // "15346111382836"
Faker\Provider\pl_PL\Payment
<?php// Generates a random bank nameecho$faker->bank; // "Narodowy Bank Polski"// Generates a random bank account numberecho$faker->bankAccountNumber; // "PL14968907563953822118075816"
Faker\Provider\pt_PT\Person
<?php// Generates a random taxpayer identification number (in portuguese - Número de Identificação Fiscal NIF)echo$faker->taxpayerIdentificationNumber; // '165249277'
Faker\Provider\pt_BR\Address
<?php// Generates a random region nameecho$faker->region; // 'Nordeste'// Generates a random region abbreviationecho$faker->regionAbbr; // 'NE'
Faker\Provider\pt_BR\PhoneNumber
<?phpecho$faker->areaCode; // 21echo$faker->cellphone; // 9432-5656echo$faker->landline; // 2654-3445echo$faker->phone; // random landline, 8-digit or 9-digit cellphone number// Using the phone functions with a false argument returns unformatted numbersecho$faker->cellphone(false); // 74336667// cellphone() has a special second argument to add the 9th digit. Ignored if generated a Radio numberecho$faker->cellphone(true, true); // 98983-3945 or 7343-1290// Using the "Number" suffix adds area code to the phoneecho$faker->cellphoneNumber; // (11) 98309-2935echo$faker->landlineNumber(false); // 3522835934echo$faker->phoneNumber; // formatted, random landline or cellphone (obeying the 9th digit rule)echo$faker->phoneNumberCleared; // not formatted, random landline or cellphone (obeying the 9th digit rule)
Faker\Provider\pt_BR\Person
<?php// The name generator may include double first or double last names, plus title and suffixecho$faker->name; // 'Sr. Luis Adriano Sepúlveda Filho'// Valid document generators have a boolean argument to remove formattingecho$faker->cpf; // '145.343.345-76'echo$faker->cpf(false); // '45623467866'echo$faker->rg; // '84.405.736-3'echo$faker->rg(false); // '844057363'
Faker\Provider\pt_BR\Company
<?php// Generates a Brazilian formatted and valid CNPJecho$faker->cnpj; // '23.663.478/0001-24'echo$faker->cnpj(false); // '23663478000124'
Faker\Provider\ro_MD\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "MD83BQW1CKMUW34HBESDP3A8"
Faker\Provider\ro_RO\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "RO55WRJE3OE8X3YQI7J26U1E"
Faker\Provider\ro_RO\Person
<?php// Generates a random male name prefix/titleecho$faker->prefixMale; // "ing."// Generates a random female name prefix/titleecho$faker->prefixFemale; // "d-na."// Generates a random male first nameecho$faker->firstNameMale; // "Adrian"// Generates a random female first nameecho$faker->firstNameFemale; // "Miruna"// Generates a random Personal Numerical Code (CNP)echo$faker->cnp; // "2800523081231"// Valid option values:// $gender: null (random), male, female// $dateOfBirth (1800+): null (random), Y-m-d, Y-m (random day), Y (random month and day)// i.e. '1981-06-16', '2015-03', '1900'// $county: 2 letter ISO 3166-2:RO county codes and B1, B2, B3, B4, B5, B6 for Bucharest's 6 sectors// $isResident true/false flag if the person resides in Romaniaecho$faker->cnp($gender = null, $dateOfBirth = null, $county = null, $isResident = true);
Faker\Provider\ro_RO\PhoneNumber
<?php// Generates a random toll-free phone numberecho$faker->tollFreePhoneNumber; // "0800123456"// Generates a random premium-rate phone numberecho$faker->premiumRatePhoneNumber; // "0900123456"
Faker\Provider\ru_RU\Payment
<?php// Generates a Russian bank name (based on list of real russian banks)echo$faker->bank; // "ОТП Банк"//Generate a Russian Tax Payment Number for Companyecho$faker->inn; // 7813540735//Generate a Russian Tax Code for Companyecho$faker->kpp; // 781301001
Faker\Provider\sv_SE\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "SE5018548608468284909192"
Faker\Provider\sv_SE\Person
<?php//Generates a valid Swedish personal identity number (in Swedish - Personnummer)echo$faker->personalIdentityNumber() // '950910-0799'
//Since the numbers are different for male and female persons, optionally you can specify gender.
echo $faker->personalIdentityNumber('female') // '950910-0781'
Faker\Provider\tr_TR\Person
<?php//Generates a valid Turkish identity number (in Turkish - T.C. Kimlik No)echo$faker->tcNo // '55300634882'
Faker\Provider\zh_CN\Payment
<?php// Generates a random bank name (based on list of real chinese banks)echo$faker->bank; // '中国建设银行'
Faker\Provider\uk_UA\Payment
<?php// Generates an Ukraine bank name (based on list of real Ukraine banks)echo$faker->bank; // "Ощадбанк"
Faker\Provider\zh_TW\Person
<?php// Generates a random personal identify numberecho$faker->personalIdentityNumber; // A223456789
Faker\Provider\zh_TW\Company
<?php// Generates a random VAT / Company Tax numberecho$faker->VAT; //23456789
Third-Party Libraries Extending/Based On Faker
Symfony bundles:
willdurand/faker-bundle: Put the awesome Faker library into the Symfony2 DIC and populate your database with fake data.
pattern-lab/plugin-faker: Pattern Lab is a Styleguide, Component Library, and Prototyping tool. This creates unique content each time Pattern Lab is generated.
namespaceApp\Models;
useIlluminate\Database\Eloquent\Model;
classFlightextendsModel
{
/** * # Table Names * * Eloquent will assume the 'Flight' model stores records in the 'flights' table, * AirTrafficController model would store records in an air_traffic_controllers table etc. * If your model's corresponding database table does not fit this convention, you may manually specify the model's table * name by defining a table property on the model: * *//** * The table associated with the model. * * @var string */protected$table = 'my_flights';
/** * ---------------------------------------------------------------------------------------------------- *//** * # Primary Keys * * Eloquent will also assume that each model's corresponding database table has a primary key column named id. * If necessary, you may define a protected $primaryKey property on your model to specify a different column * that serves as your model's primary key: *//** * The primary key associated with the table. * * @var string */protected$primaryKey = 'flight_id';
/** * ---------------------------------------------------------------------------------------------------- *//** * # Incrementing * * In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that Eloquent * will automatically cast the primary key to an integer. If you wish to use a non-incrementing or a non-numeric * primary key you must define a public $incrementing property on your model that is set to false: *//** * Indicates if the model's ID is auto-incrementing. * * @var bool */public$incrementing = false;
/** * ---------------------------------------------------------------------------------------------------- *//** * # Info * * If your model's primary key is not an integer, you should define a protected $keyType property on your model. * This property should have a value of string: *//** * # "Composite" Primary Keys * Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. * "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, * unique indexes to your database tables in addition to the table's uniquely identifying primary key. *//** * The data type of the auto-incrementing ID. * * @var string */protected$keyType = 'string';
/** * ---------------------------------------------------------------------------------------------------- *//** * # Timestamps * * By default, Eloquent expects created_at and updated_at columns to exist on your model's corresponding database table. * Eloquent will automatically set these column's values when models are created or updated. * If you do not want these columns to be automatically managed by Eloquent, you should define a $timestamps property * on your model with a value of false: *//** * Indicates if the model should be timestamped. * * @var bool */public$timestamps = false;
/** * ---------------------------------------------------------------------------------------------------- *//** * # Info * * If you need to customize the format of your model's timestamps, set the $dateFormat property on your model. * This property determines how date attributes are stored in the database as well as their format when the model is * serialized to an array or JSON: *//** * The storage format of the model's date columns. * * @var string */protected$dateFormat = 'U';
/** * If you need to customize the names of the columns used to store the timestamps, you may define * CREATED_AT and UPDATED_AT constants on your model: */constCREATED_AT = 'creation_date';
constUPDATED_AT = 'updated_date';
/** * ---------------------------------------------------------------------------------------------------- *//** * # Database Connections * * By default, all Eloquent models will use the default database connection that is configured for your application. * If you would like to specify a different connection that should be used when interacting with a particular model, * you should define a $connection property on the model: *//** * The database connection that should be used by the model. * * @var string */protected$connection = 'sqlite';
/** * ---------------------------------------------------------------------------------------------------- *//** * # Default Attribute Values * * By default, a newly instantiated model instance will not contain any attribute values. If you would like to define * the default values for some of your model's attributes, you may define an $attributes property on your model: *//** * The model's default values for attributes. * * @var array */protected$attributes = [
'delayed' => false,
];
/** * ---------------------------------------------------------------------------------------------------- */
}
This file contains 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
This file contains 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
This file contains 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
tenant(); // retornar o tenant da sessão (ou null se não existir um carregado)// Se passar parâmetro, retorna o atributo do tenant (se existir)tenant('id');
tenant('domains');
Função tenancy
// initialize(): inicializa um tenant na sessãotenancy()->initialize(Tenant::find('cliente1'));
// initialized attribute: informa se existe um tenant inicializadotenancy()->initialized; // boolean// end(): encerra o tenant da sessãotenancy()->end(); // null||\\\\\\\\\\\\\\\\\\\|||||||||||||||||
/* Para chamar a factory da relação conforme abaixo, o Laravel presume que a model Form tem seu relacionamento com FormInput usando o método 'formInput': App\Models\Form::formInput()*/Form::factory()->has(FormInput::factory(2))->createOne();
/* Digamos que ao invés de 'formInput', o relacionamento seja 'inputs', e por sair do padrão do Laravel, eu preciso 'inputs' informar como segundo parâmetro*/Form::factory()->has(FormInput::factory(2), 'inputs')->createOne()
/*
Se quiser alterar valores do relacionamento, usar o método 'state'
*/
Form::factory()->has(
FormInput::factory(2)->state(fn () => ['name' => 'linkedin_url']),
'inputs'
)->createOne()
Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
Faker is heavily inspired by Perl's Data::Faker, and by ruby's Faker.
<?php# When installed via composerrequire_once'vendor/autoload.php';
You can also load Fakers shipped PSR-0 autoloader
<?php# Load Fakers own autoloaderrequire_once'/path/to/Faker/src/autoload.php';
alternatively, you can use any another PSR-4 compliant autoloader
Create fake data
Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.
<?php// use the factory to create a Faker\Generator instance$faker = Faker\Factory::create();
// generate data by accessing propertiesecho$faker->name;
// 'Lucy Cechtelar';echo$faker->address;
// "426 Jordy Lodge// Cartwrightshire, SC 88120-6700"echo$faker->text;
// Dolores sit sint laboriosam dolorem culpa et autem. Beatae nam sunt fugit// et sit et mollitia sed.// Fuga deserunt tempora facere magni omnis. Omnis quia temporibus laudantium// sit minima sint.
Even if this example shows a property access, each call to $faker->name yields a different (random) result. This is because Faker uses __get() magic, and forwards Faker\Generator->$property calls to Faker\Generator->format($property).
Tip: For a quick generation of fake data, you can also use Faker as a command line tool thanks to faker-cli.
Formatters
Each of the generator properties (like name, address, and lorem) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale.
word // 'aut'
words($nb = 3, $asText = false) // array('porro', 'sed', 'magni')
sentence($nbWords = 6, $variableNbWords = true) // 'Sit vitae voluptas sint non voluptates.'
sentences($nb = 3, $asText = false) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.')
paragraph($nbSentences = 3, $variableNbSentences = true) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.'
paragraphs($nb = 3, $asText = false) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.')
text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.'
realText($maxNbChars = 200, $indexSize = 2) // "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied."
Methods accepting a $timezone argument default to date_default_timezone_get(). You can pass a custom timezone string to each method, or define a custom timezone for all time methods at once using $faker::setDefaultTimezone($timezone).
userAgent // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350'
chrome // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312'
firefox // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6'
safari // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3'
opera // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00'
internetExplorer // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)'
Faker\Provider\Payment
creditCardType // 'MasterCard'
creditCardNumber // '4485480221084675'
creditCardExpirationDate // 04/13
creditCardExpirationDateString // '04/13'
creditCardDetails // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13')
// Generates a random IBAN. Set $countryCode to null for a random country
iban($countryCode) // 'IT31A8497112740YZ575DJ28BP4'
swiftBicNumber // 'RZTIAT22263'
fileExtension // 'avi'
mimeType // 'video/x-msvideo'
// Copy a random file from the source to the target directory and returns the fullpath or filename
file($sourceDir = '/tmp', $targetDir = '/tmp') // '/path/to/targetDir/13b73edae8443990be1aa8f1a483bc27.jpg'
file($sourceDir, $targetDir, false) // '13b73edae8443990be1aa8f1a483bc27.jpg'
// get a random number between 10 and 20,
// with more chances to be close to 20
biasedNumberBetween($min = 10, $max = 20, $function = 'sqrt')
Faker\Provider\HtmlLorem
//Generate HTML document which is no more than 2 levels deep, and no more than 3 elements wide at any level.
randomHtml(2,3) // <html><head><title>Aut illo dolorem et accusantium eum.</title></head><body><form action="example.com" method="POST"><label for="username">sequi</label><input type="text" id="username"><label for="password">et</label><input type="password" id="password"></form><b>Id aut saepe non mollitia voluptas voluptas.</b><table><thead><tr><tr>Non consequatur.</tr><tr>Incidunt est.</tr><tr>Aut voluptatem.</tr><tr>Officia voluptas rerum quo.</tr><tr>Asperiores similique.</tr></tr></thead><tbody><tr><td>Sapiente dolorum dolorem sint laboriosam commodi qui.</td><td>Commodi nihil nesciunt eveniet quo repudiandae.</td><td>Voluptates explicabo numquam distinctio necessitatibus repellat.</td><td>Provident ut doloremque nam eum modi aspernatur.</td><td>Iusto inventore.</td></tr><tr><td>Animi nihil ratione id mollitia libero ipsa quia tempore.</td><td>Velit est officia et aut tenetur dolorem sed mollitia expedita.</td><td>Modi modi repudiandae pariatur voluptas rerum ea incidunt non molestiae eligendi eos deleniti.</td><td>Exercitationem voluptatibus dolor est iste quod molestiae.</td><td>Quia reiciendis.</td></tr><tr><td>Inventore impedit exercitationem voluptatibus rerum cupiditate.</td><td>Qui.</td><td>Aliquam.</td><td>Autem nihil aut et.</td><td>Dolor ut quia error.</td></tr><tr><td>Enim facilis iusto earum et minus rerum assumenda quis quia.</td><td>Reprehenderit ut sapiente occaecati voluptatum dolor voluptatem vitae qui velit.</td><td>Quod fugiat non.</td><td>Sunt nobis totam mollitia sed nesciunt est deleniti cumque.</td><td>Repudiandae quo.</td></tr><tr><td>Modi dicta libero quisquam doloremque qui autem.</td><td>Voluptatem aliquid saepe laudantium facere eos sunt dolor.</td><td>Est eos quis laboriosam officia expedita repellendus quia natus.</td><td>Et neque delectus quod fugit enim repudiandae qui.</td><td>Fugit soluta sit facilis facere repellat culpa magni voluptatem maiores tempora.</td></tr><tr><td>Enim dolores doloremque.</td><td>Assumenda voluptatem eum perferendis exercitationem.</td><td>Quasi in fugit deserunt ea perferendis sunt nemo consequatur dolorum soluta.</td><td>Maxime repellat qui numquam voluptatem est modi.</td><td>Alias rerum rerum hic hic eveniet.</td></tr><tr><td>Tempore voluptatem.</td><td>Eaque.</td><td>Et sit quas fugit iusto.</td><td>Nemo nihil rerum dignissimos et esse.</td><td>Repudiandae ipsum numquam.</td></tr><tr><td>Nemo sunt quia.</td><td>Sint tempore est neque ducimus harum sed.</td><td>Dicta placeat atque libero nihil.</td><td>Et qui aperiam temporibus facilis eum.</td><td>Ut dolores qui enim et maiores nesciunt.</td></tr><tr><td>Dolorum totam sint debitis saepe laborum.</td><td>Quidem corrupti ea.</td><td>Cum voluptas quod.</td><td>Possimus consequatur quasi dolorem ut et.</td><td>Et velit non hic labore repudiandae quis.</td></tr></tbody></table></body></html>
Modifiers
Faker provides three special providers, unique(), optional(), and valid(), to be called before any provider.
// unique() forces providers to return unique values$values = array();
for ($i = 0; $i < 10; $i++) {
// get a random digit, but always a new one, to avoid duplicates$values []= $faker->unique()->randomDigit;
}
print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3]// providers with a limited range will throw an exception when no new unique value can be generated$values = array();
try {
for ($i = 0; $i < 10; $i++) {
$values []= $faker->unique()->randomDigitNotNull;
}
} catch (\OverflowException$e) {
echo"There are only 9 unique digits not null, Faker can't generate 10 of them!";
}
// you can reset the unique modifier for all providers by passing true as first argument$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset// tip: unique() keeps one array of values per provider// optional() sometimes bypasses the provider to return a default value instead (which defaults to NULL)$values = array();
for ($i = 0; $i < 10; $i++) {
// get a random digit, but also null sometimes$values []= $faker->optional()->randomDigit;
}
print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null]// optional() accepts a weight argument to specify the probability of receiving the default value.// 0 will always return the default value; 1 will always return the provider. Default weight is 0.5 (50% chance).$faker->optional($weight = 0.1)->randomDigit; // 90% chance of NULL$faker->optional($weight = 0.9)->randomDigit; // 10% chance of NULL// optional() accepts a default argument to specify the default value to return.// Defaults to NULL.$faker->optional($weight = 0.5, $default = false)->randomDigit; // 50% chance of FALSE$faker->optional($weight = 0.9, $default = 'abc')->word; // 10% chance of 'abc'// valid() only accepts valid values according to the passed validator functions$values = array();
$evenValidator = function($digit) {
return$digit % 2 === 0;
};
for ($i = 0; $i < 10; $i++) {
$values []= $faker->valid($evenValidator)->randomDigit;
}
print_r($values); // [0, 4, 8, 4, 2, 6, 0, 8, 8, 6]// just like unique(), valid() throws an overflow exception when it can't generate a valid value$values = array();
try {
$faker->valid($evenValidator)->randomElement([1, 3, 5, 7, 9]);
} catch (\OverflowException$e) {
echo"Can't pick an even number in that set!";
}
If you would like to use a modifier with a value not generated by Faker, use the passthrough() method. passthrough() simply returns whatever value it was given.
$faker->optional()->passthrough(mt_rand(5, 15));
Localization
Faker\Factory can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_US).
<?php$faker = Faker\Factory::create('fr_FR'); // create a French fakerfor ($i = 0; $i < 10; $i++) {
echo$faker->name, "\n";
}
// Luce du Coulon// Auguste Dupont// Roger Le Voisin// Alexandre Lacroix// Jacques Humbert-Roy// Thérèse Guillet-Andre// Gilles Gros-Bodin// Amélie Pires// Marcel Laporte// Geneviève Marchal
You can check available Faker locales in the source code, under the Provider directory. The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR!
Populating Entities Using an ORM or an ODM
Faker provides adapters for Object-Relational and Object-Document Mappers (currently, Propel, Doctrine2, CakePHP, Spot2, Mandango and Eloquent are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library).
To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the execute() method.
Note that some of the populators could require additional parameters. As example the doctrine populator has an option to specify
its batchSize on how often it will flush the UnitOfWork to the database.
Here is an example showing how to populate 5 Author and 10 Book objects:
The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named first_name using the firstName formatter, and a column with a TIMESTAMP type using the dateTime formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to addEntity():
In this example, Faker will guess a formatter for all columns except ISBN, for which the given anonymous function will be used.
Tip: To ignore some columns, specify null for the column names in the third argument of addEntity(). This is usually necessary for columns added by a behavior:
Of course, Faker does not populate autoincremented primary keys. In addition, Faker\ORM\Propel\Populator::execute() returns the list of inserted PKs, indexed by class:
Note: Due to the fact that Faker returns all the primary keys inserted, the memory consumption will go up drastically when you do batch inserts due to the big list of data.
In the previous example, the Book and Author models share a relationship. Since Author entities are populated first, Faker is smart enough to relate the populated Book entities to one of the populated Author entities.
Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the addEntity() method:
You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a seed() method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results.
Tip: DateTime formatters won't reproduce the same fake data if you don't fix the $max value:
<?php// even when seeded, this line will return different results because $max varies$faker->dateTime(); // equivalent to $faker->dateTime($max = 'now')// make sure you fix the $max parameter$faker->dateTime('2014-02-25 08:37:17'); // will return always the same date when seeded
Tip: Formatters won't reproduce the same fake data if you use the rand() php function. Use $faker or mt_rand() instead:
A Faker\Generator alone can't do much generation. It needs Faker\Provider objects to delegate the data generation to them. Faker\Factory::create() actually creates a Faker\Generator bundled with the default providers. Here is what happens under the hood:
Whenever you try to access a property on the $faker object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling $faker->name triggers a call to Faker\Provider\Person::name(). And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override.
That means that you can easily add your own providers to a Faker\Generator instance. A provider is usually a class extending \Faker\Provider\Base. This parent class allows you to use methods like lexify() or randomNumber(); it also gives you access to formatters of other providers, through the protected $generator property. The new formatters are the public methods of the provider class.
Here is an example provider for populating Book data:
Running this script produces a document looking like:
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<contactfirstName="Ona"lastName="Bednar"email="[email protected]">
<phonenumber="1-265-479-1196x714"/>
<address>
<street>182 Harrison Cove</street>
<city>North Lloyd</city>
<postcode>45577</postcode>
<state>Alabama</state>
</address>
<companyname="Veum, Funk and Shanahan"catchPhrase="Function-based stable solution">
<offer>orchestrate compelling web-readiness</offer>
</company>
<details>
<![CDATA[Alias accusantium voluptatum autem nobis cumque neque modi. Voluptatem error molestiae consequatur alias.Illum commodi molestiae aut repellat id. Et sit consequuntur aut et ullam asperiores. Cupiditate culpa voluptatem et mollitia dolor. Nisi praesentium qui ut.]]>
</details>
</contact>
<contactfirstName="Aurelie"lastName="Paucek"email="[email protected]">
<phonenumber="863.712.1363x9425"/>
<address>
<street>90111 Hegmann Inlet</street>
<city>South Geovanymouth</city>
<postcode>69961-9311</postcode>
<state>Colorado</state>
</address>
<companyname="Krajcik-Grimes"catchPhrase="Switchable cohesive instructionset">
</company>
</contact>
<contactfirstName="Clifton"lastName="Kshlerin"email="[email protected]">
<phonenumber="692-194-4746"/>
<address>
<street>9791 Nona Corner</street>
<city>Harberhaven</city>
<postcode>74062-8191</postcode>
<state>RhodeIsland</state>
</address>
<companyname="Rosenbaum-Aufderhar"catchPhrase="Realigned asynchronous encryption">
</company>
</contact>
<contactfirstName="Alexandre"lastName="Orn"email="[email protected]">
<phonenumber="189.655.8677x027"/>
<address>
<street>11161 Schultz Via</street>
<city>Feilstad</city>
<postcode>98019</postcode>
<state>NewJersey</state>
</address>
<companyname="O'Hara-Prosacco"catchPhrase="Re-engineered solution-oriented algorithm">
<directorname="Dr. Berenice Auer V" />
</company>
<details>
<![CDATA[Ut itaque et quaerat doloremque eum praesentium. Rerum in saepe dolorem. Explicabo qui consequuntur commodi minima rem.Harum temporibus rerum dolores. Non molestiae id dolorem placeat.Aut asperiores nihil eius repellendus. Vero nihil corporis voluptatem explicabo commodi. Occaecati omnis blanditiis beatae quod aspernatur eos.]]>
</details>
</contact>
<contactfirstName="Katelynn"lastName="Kohler"email="[email protected]">
<phonenumber="(665)713-1657"/>
<address>
<street>6106 Nader Village Suite 753</street>
<city>McLaughlinstad</city>
<postcode>43189-8621</postcode>
<state>Missouri</state>
</address>
<companyname="Herman-Tremblay"catchPhrase="Object-based explicit service-desk">
<offer>expedite viral synergies</offer>
<directorname="Arden Deckow" />
</company>
</contact>
<contactfirstName="Blanca"lastName="Stark"email="[email protected]">
<phonenumber="168.719.4692x87177"/>
<address>
<street>7546 Kuvalis Plaza</street>
<city>South Wilfrid</city>
<postcode>77069</postcode>
<state>Georgia</state>
</address>
<companyname="Upton, Braun and Rowe"catchPhrase="Visionary leadingedge pricingstructure">
</company>
</contact>
<contactfirstName="Rene"lastName="Spencer"email="[email protected]">
<phonenumber="715.222.0095x175"/>
<birthdate="2008-08-07"place="Zulaufborough"/>
<address>
<street>478 Daisha Landing Apt. 510</street>
<city>West Lizethhaven</city>
<postcode>30566-5362</postcode>
<state>WestVirginia</state>
</address>
<companyname="Wiza Inc"catchPhrase="Persevering reciprocal approach">
<offer>orchestrate dynamic networks</offer>
<directorname="Erwin Nienow" />
</company>
<details>
<![CDATA[Dolorem consequatur voluptates unde optio unde. Accusantium dolorem est est architecto impedit. Corrupti et provident quo.Reprehenderit dolores aut quidem suscipit repudiandae corporis error. Molestiae enim aperiam illo.Et similique qui non expedita quia dolorum. Ex rem incidunt ea accusantium temporibus minus non.]]>
</details>
</contact>
<contactfirstName="Alessandro"lastName="Hagenes"email="[email protected]">
<phonenumber="1-284-958-6768"/>
<address>
<street>1251 Koelpin Mission</street>
<city>North Revastad</city>
<postcode>81620</postcode>
<state>Maryland</state>
</address>
<companyname="Stiedemann-Bruen"catchPhrase="Re-engineered 24/7 success">
</company>
</contact>
<contactfirstName="Novella"lastName="Rutherford"email="[email protected]">
<phonenumber="(091)825-7971"/>
<address>
<street>6396 Langworth Hills Apt. 446</street>
<city>New Carlos</city>
<postcode>89399-0268</postcode>
<state>Wyoming</state>
</address>
<companyname="Stroman-Legros"catchPhrase="Expanded 4thgeneration moratorium">
<directorname="Earlene Bayer" />
</company>
</contact>
<contactfirstName="Andreane"lastName="Mann"email="[email protected]">
<phonenumber="941-659-9982x5689"/>
<birthdate="1934-02-21"place="Stantonborough"/>
<address>
<street>2246 Kreiger Station Apt. 291</street>
<city>Kaydenmouth</city>
<postcode>11397-1072</postcode>
<state>Wyoming</state>
</address>
<companyname="Lebsack, Bernhard and Kiehn"catchPhrase="Persevering actuating framework">
<offer>grow sticky portals</offer>
</company>
<details>
<![CDATA[Quia dolor ut quia error libero. Enim facilis iusto earum et minus rerum assumenda. Quia doloribus et reprehenderit ut. Occaecati voluptatum dolor voluptatem vitae qui velit quia.Fugiat non in itaque sunt nobis totam. Sed nesciunt est deleniti cumque alias. Repudiandae quo aut numquam modi dicta libero.]]>
</details>
</contact>
</contacts>
Language specific formatters
Faker\Provider\ar_SA\Person
<?phpecho$faker->idNumber; // ID numberecho$faker->nationalIdNumber // CitizenID number
echo $faker->foreignerIdNumber // ForeignerID number
echo $faker->companyIdNumber // CompanyID number
<?phpecho$faker->vat; // "AT U12345678" - Austrian Value Added Tax numberecho$faker->vat(false); // "ATU12345678" - unspaced Austrian Value Added Tax number
Faker\Provider\bg_BG\Payment
<?phpecho$faker->vat; // "BG 0123456789" - Bulgarian Value Added Tax numberecho$faker->vat(false); // "BG0123456789" - unspaced Bulgarian Value Added Tax number
Faker\Provider\cs_CZ\Address
<?phpecho$faker->region; // "Liberecký kraj"
Faker\Provider\cs_CZ\Company
<?php// Generates a valid IČOecho$faker->ico; // "69663963"
Faker\Provider\cs_CZ\DateTime
<?phpecho$faker->monthNameGenitive; // "prosince"echo$faker->formattedDate; // "12. listopadu 2015"
Faker\Provider\cs_CZ\Person
<?phpecho$faker->birthNumber; // "7304243452"
Faker\Provider\da_DK\Person
<?php// Generates a random CPR numberecho$faker->cpr; // "051280-2387"
Faker\Provider\da_DK\Address
<?php// Generates a random 'kommune' nameecho$faker->kommune; // "Frederiksberg"// Generates a random region nameecho$faker->region; // "Region Sjælland"
Faker\Provider\da_DK\Company
<?php// Generates a random CVR numberecho$faker->cvr; // "32458723"// Generates a random P numberecho$faker->p; // "5398237590"
Faker\Provider\de_CH\Person
<?php// Generates a random AVS13/AHV13 social security numberecho$faker->avs13; // "756.1234.5678.97" ORecho$faker->ahv13; // "756.1234.5678.97"
<?php// Generates a fake town name based on the words commonly found in Hong Kongecho$faker->town; // "Yuen Long"// Generates a fake village name based on the words commonly found in Hong Kongecho$faker->village; // "O Tau"// Generates a fake estate name based on the words commonly found in Hong Kongecho$faker->estate; // "Ching Lai Court"
Faker\Provider\en_HK\Phone
<?php// Generates a Hong Kong mobile number (starting with 5, 6 or 9)echo$faker->mobileNumber; // "92150087"// Generates a Hong Kong landline number (starting with 2 or 3)echo$faker->landlineNumber; // "32750132"// Generates a Hong Kong fax number (starting with 7)echo$faker->faxNumber; // "71937729"
Faker\Provider\en_NG\Address
<?php// Generates a random region nameecho$faker->region; // 'Katsina'
Faker\Provider\en_NG\Person
<?php// Generates a random person nameecho$faker->name; // 'Oluwunmi Mayowa'
Faker\Provider\en_NZ\Phone
<?php// Generates a cell (mobile) phone numberecho$faker->mobileNumber; // "021 123 4567"// Generates a toll free numberecho$faker->tollFreeNumber; // "0800 123 456"// Area Codeecho$faker->areaCode; // "03"
Faker\Provider\en_US\Company
<?php// Generate a random Employer Identification Numberecho$faker->ein; // '12-3456789'
<?php// Generates a random Social Security Numberecho$faker->ssn; // '123-45-6789'
Faker\Provider\en_ZA\Company
<?php// Generates a random company registration numberecho$faker->companyNumber; // 1999/789634/01
Faker\Provider\en_ZA\Person
<?php// Generates a random national identification numberecho$faker->idNumber; // 6606192211041// Generates a random valid licence codeecho$faker->licenceCode; // EB
Faker\Provider\en_ZA\PhoneNumber
<?php// Generates a special rate toll free phone numberecho$faker->tollFreeNumber; // 0800 555 5555// Generates a mobile phone numberecho$faker->mobileNumber; // 082 123 5555
Faker\Provider\es_ES\Person
<?php// Generates a Documento Nacional de Identidad (DNI) numberecho$faker->dni; // '77446565E'// Generates a random valid licence codeecho$faker->licenceCode; // B
Faker\Provider\es_ES\Payment
<?php// Generates a Código de identificación Fiscal (CIF) numberecho$faker->vat; // "A35864370"
Faker\Provider\es_ES\PhoneNumber
<?php// Generates a special rate toll free phone numberecho$faker->tollFreeNumber; // 900 123 456// Generates a mobile phone numberecho$faker->mobileNumber; // +34 612 12 24
Faker\Provider\es_PE\Person
<?php// Generates a Peruvian Documento Nacional de Identidad (DNI) numberecho$faker->dni; // '83367512'
Faker\Provider\fa_IR\Person
<?php// Generates a valid nationalCodeecho$faker->nationalCode; // "0078475759"
Faker\Provider\fa_IR\Address
<?php// Generates a random building nameecho$faker->building; // "ساختمان آفتاب"// Returns a random city nameecho$faker->city // "استان زنجان"
Faker\Provider\fa_IR\Company
<?php// Generates a random contract typeecho$faker->contract; // "رسمی"
Faker\Provider\fi_FI\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "FI8350799879879616"
Faker\Provider\fi_FI\Person
<?php//Generates a valid Finnish personal identity number (in Finnish - Henkilötunnus)echo$faker->personalIdentityNumber() // '170974-007J'
//Since the numbers are different for male and female persons, optionally you can specify gender.
echo $faker->personalIdentityNumber(\DateTime::createFromFormat('Y-m-d', '2015-12-14'), 'female') // '141215A520B'
Faker\Provider\fr_BE\Payment
<?phpecho$faker->vat; // "BE 0123456789" - Belgian Value Added Tax numberecho$faker->vat(false); // "BE0123456789" - unspaced Belgian Value Added Tax number
Faker\Provider\es_VE\Person
<?php// Generate a Cédula de identidad number, you can pass one argument to add separatorecho$faker->nationalId; // 'V11223344'
Faker\Provider\es_VE\Company
<?php// Generates a R.I.F. number, you can pass one argument to add separatorsecho$faker->taxpayerIdentificationNumber; // 'J1234567891'
Faker\Provider\fr_CH\Person
<?php// Generates a random AVS13/AHV13 social security numberecho$faker->avs13; // "756.1234.5678.97"
Faker\Provider\fr_FR\Address
<?php// Generates a random department nameecho$faker->departmentName; // "Haut-Rhin"// Generates a random department numberecho$faker->departmentNumber; // "2B"// Generates a random department info (department number => department name)$faker->department; // array('18' => 'Cher');// Generates a random regionecho$faker->region; // "Saint-Pierre-et-Miquelon"// Generates a random appartement,stairecho$faker->secondaryAddress; // "Bat. 961"
Faker\Provider\fr_FR\Company
<?php// Generates a random SIREN numberecho$faker->siren; // 082 250 104// Generates a random SIRET numberecho$faker->siret; // 347 355 708 00224
Faker\Provider\fr_FR\Payment
<?php// Generates a random VATecho$faker->vat; // FR 12 123 456 789
Faker\Provider\fr_FR\Person
<?php// Generates a random NIR / Sécurité Sociale numberecho$faker->nir; // 1 88 07 35 127 571 - 19
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "HU09904437680048220079300783"
Faker\Provider\id_ID\Person
<?php// Generates a random Nomor Induk Kependudukan (NIK)// first argument is gender, either Person::GENDER_MALE or Person::GENDER_FEMALE, if none specified random gender is used// second argument is birth date (DateTime object), if none specified, random birth date is usedecho$faker->nik(); // "8522246001570940"
Faker\Provider\it_CH\Person
<?php// Generates a random AVS13/AHV13 social security numberecho$faker->avs13; // "756.1234.5678.97"
Faker\Provider\it_IT\Company
<?php// Generates a random Vat Idecho$faker->vatId(); // "IT98746784967"
Faker\Provider\it_IT\Person
<?php// Generates a random Tax Id code (Codice fiscale)echo$faker->taxId(); // "DIXDPZ44E08F367A"
Faker\Provider\ja_JP\Person
<?php// Generates a 'kana' nameecho$faker->kanaName($gender = null|'male'|'female') // "アオタ ミノル"
// Generates a 'kana' first name
echo $faker->firstKanaName($gender = null|'male'|'female') // "ヒデキ"
// Generates a 'kana' first name on the male
echo$faker->firstKanaNameMale // "ヒデキ"
// Generates a 'kana' first name on the female
echo$faker->firstKanaNameFemale // "マアヤ"
// Generates a 'kana' last name
echo $faker->lastKanaName; // "ナカジマ"
Faker\Provider\ka_GE\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "GE33ZV9773853617253389"
Faker\Provider\kk_KZ\Company
<?php// Generates an business identification numberecho$faker->businessIdentificationNumber; // "150140000019"
Faker\Provider\kk_KZ\Payment
<?php// Generates a random bank nameecho$faker->bank; // "Қазкоммерцбанк"// Generates a random bank account numberecho$faker->bankAccountNumber; // "KZ1076321LO4H6X41I37"
Faker\Provider\kk_KZ\Person
<?php// Generates an individual identification numberecho$faker->individualIdentificationNumber; // "780322300455"// Generates an individual identification number based on his/her birth dateecho$faker->individualIdentificationNumber(new \DateTime('1999-03-01')); // "990301300455"
Faker\Provider\ko_KR\Address
<?php// Generates a metropolitan cityecho$faker->metropolitanCity; // "서울특별시"// Generates a boroughecho$faker->borough; // "강남구"
Faker\Provider\ko_KR\PhoneNumber
<?php// Generates a local area phone numerecho$faker->localAreaPhoneNumber; // "02-1234-4567"// Generates a cell phone numberecho$faker->cellPhoneNumber; // "010-9876-5432"
<?php// Generates a random personal identity card numberecho$faker->personalIdentityNumber; // "140190-12301"
Faker\Provider\ms_MY\Address
<?php// Generates a random Malaysian townshipecho$faker->township; // "Taman Bahagia"// Generates a random Malaysian town address with matching postcode and stateecho$faker->townState; // "55100 Bukit Bintang, Kuala Lumpur"
Faker\Provider\ms_MY\Miscellaneous
<?php// Generates a random vehicle license plate numberecho$faker->jpjNumberPlate; // "WPL 5169"
Faker\Provider\ms_MY\Payment
<?php// Generates a random Malaysian bankecho$faker->bank; // "Maybank"// Generates a random Malaysian bank account number (10-16 digits)echo$faker->bankAccountNumber; // "1234567890123456"// Generates a random Malaysian insurance companyecho$faker->insurance; // "AIA Malaysia"// Generates a random Malaysian bank SWIFT Codeecho$faker->swiftCode; // "MBBEMYKLXXX"
Faker\Provider\ms_MY\Person
<?php// Generates a random personal identity card (myKad) numberecho$faker->myKadNumber($gender = null|'male'|'female', $hyphen = null|true|false); // "710703471796"
Faker\Provider\ms_MY\PhoneNumber
<?php// Generates a random Malaysian mobile numberecho$faker->mobileNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "+6012-705 3767"// Generates a random Malaysian landline numberecho$faker->fixedLineNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "03-7112 0455"// Generates a random Malaysian voip numberecho$faker->voipNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "015-458 7099"
Faker\Provider\ne_NP\Address
<?php//Generates a Nepali district nameecho$faker->district;
//Generates a Nepali city nameecho$faker->cityName;
Faker\Provider\nl_BE\Payment
<?phpecho$faker->vat; // "BE 0123456789" - Belgian Value Added Tax numberecho$faker->vat(false); // "BE0123456789" - unspaced Belgian Value Added Tax number
Faker\Provider\nl_BE\Person
<?phpecho$faker->rrn(); // "83051711784" - Belgian Rijksregisternummerecho$faker->rrn('female'); // "50032089858" - Belgian Rijksregisternummer for a female
Faker\Provider\nl_NL\Company
<?phpecho$faker->jobTitle; // "Houtbewerker"echo$faker->vat; // "NL123456789B01" - Dutch Value Added Tax numberecho$faker->btw; // "NL123456789B01" - Dutch Value Added Tax number (alias)
Faker\Provider\nl_NL\Person
<?phpecho$faker->idNumber; // "111222333" - Dutch Personal identification number (BSN)
Faker\Provider\nb_NO\MobileNumber
<?php// Generates a random Norwegian mobile phone numberecho$faker->mobileNumber; // "+4799988777"echo$faker->mobileNumber; // "999 88 777"echo$faker->mobileNumber; // "99988777"
Faker\Provider\nb_NO\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "NO3246764709816"
Faker\Provider\pl_PL\Person
<?php// Generates a random PESEL numberecho$faker->pesel; // "40061451555"// Generates a random personal identity card numberecho$faker->personalIdentityNumber; // "AKX383360"// Generates a random taxpayer identification number (NIP)echo$faker->taxpayerIdentificationNumber; // '8211575109'
Faker\Provider\pl_PL\Company
<?php// Generates a random REGON numberecho$faker->regon; // "714676680"// Generates a random local REGON numberecho$faker->regonLocal; // "15346111382836"
Faker\Provider\pl_PL\Payment
<?php// Generates a random bank nameecho$faker->bank; // "Narodowy Bank Polski"// Generates a random bank account numberecho$faker->bankAccountNumber; // "PL14968907563953822118075816"
Faker\Provider\pt_PT\Person
<?php// Generates a random taxpayer identification number (in portuguese - Número de Identificação Fiscal NIF)echo$faker->taxpayerIdentificationNumber; // '165249277'
Faker\Provider\pt_BR\Address
<?php// Generates a random region nameecho$faker->region; // 'Nordeste'// Generates a random region abbreviationecho$faker->regionAbbr; // 'NE'
Faker\Provider\pt_BR\PhoneNumber
<?phpecho$faker->areaCode; // 21echo$faker->cellphone; // 9432-5656echo$faker->landline; // 2654-3445echo$faker->phone; // random landline, 8-digit or 9-digit cellphone number// Using the phone functions with a false argument returns unformatted numbersecho$faker->cellphone(false); // 74336667// cellphone() has a special second argument to add the 9th digit. Ignored if generated a Radio numberecho$faker->cellphone(true, true); // 98983-3945 or 7343-1290// Using the "Number" suffix adds area code to the phoneecho$faker->cellphoneNumber; // (11) 98309-2935echo$faker->landlineNumber(false); // 3522835934echo$faker->phoneNumber; // formatted, random landline or cellphone (obeying the 9th digit rule)echo$faker->phoneNumberCleared; // not formatted, random landline or cellphone (obeying the 9th digit rule)
Faker\Provider\pt_BR\Person
<?php// The name generator may include double first or double last names, plus title and suffixecho$faker->name; // 'Sr. Luis Adriano Sepúlveda Filho'// Valid document generators have a boolean argument to remove formattingecho$faker->cpf; // '145.343.345-76'echo$faker->cpf(false); // '45623467866'echo$faker->rg; // '84.405.736-3'echo$faker->rg(false); // '844057363'
Faker\Provider\pt_BR\Company
<?php// Generates a Brazilian formatted and valid CNPJecho$faker->cnpj; // '23.663.478/0001-24'echo$faker->cnpj(false); // '23663478000124'
Faker\Provider\ro_MD\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "MD83BQW1CKMUW34HBESDP3A8"
Faker\Provider\ro_RO\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "RO55WRJE3OE8X3YQI7J26U1E"
Faker\Provider\ro_RO\Person
<?php// Generates a random male name prefix/titleecho$faker->prefixMale; // "ing."// Generates a random female name prefix/titleecho$faker->prefixFemale; // "d-na."// Generates a random male first nameecho$faker->firstNameMale; // "Adrian"// Generates a random female first nameecho$faker->firstNameFemale; // "Miruna"// Generates a random Personal Numerical Code (CNP)echo$faker->cnp; // "2800523081231"// Valid option values:// $gender: null (random), male, female// $dateOfBirth (1800+): null (random), Y-m-d, Y-m (random day), Y (random month and day)// i.e. '1981-06-16', '2015-03', '1900'// $county: 2 letter ISO 3166-2:RO county codes and B1, B2, B3, B4, B5, B6 for Bucharest's 6 sectors// $isResident true/false flag if the person resides in Romaniaecho$faker->cnp($gender = null, $dateOfBirth = null, $county = null, $isResident = true);
Faker\Provider\ro_RO\PhoneNumber
<?php// Generates a random toll-free phone numberecho$faker->tollFreePhoneNumber; // "0800123456"// Generates a random premium-rate phone numberecho$faker->premiumRatePhoneNumber; // "0900123456"
Faker\Provider\ru_RU\Payment
<?php// Generates a Russian bank name (based on list of real russian banks)echo$faker->bank; // "ОТП Банк"//Generate a Russian Tax Payment Number for Companyecho$faker->inn; // 7813540735//Generate a Russian Tax Code for Companyecho$faker->kpp; // 781301001
Faker\Provider\sv_SE\Payment
<?php// Generates a random bank account numberecho$faker->bankAccountNumber; // "SE5018548608468284909192"
Faker\Provider\sv_SE\Person
<?php//Generates a valid Swedish personal identity number (in Swedish - Personnummer)echo$faker->personalIdentityNumber() // '950910-0799'
//Since the numbers are different for male and female persons, optionally you can specify gender.
echo $faker->personalIdentityNumber('female') // '950910-0781'
Faker\Provider\tr_TR\Person
<?php//Generates a valid Turkish identity number (in Turkish - T.C. Kimlik No)echo$faker->tcNo // '55300634882'
Faker\Provider\zh_CN\Payment
<?php// Generates a random bank name (based on list of real chinese banks)echo$faker->bank; // '中国建设银行'
Faker\Provider\uk_UA\Payment
<?php// Generates an Ukraine bank name (based on list of real Ukraine banks)echo$faker->bank; // "Ощадбанк"
Faker\Provider\zh_TW\Person
<?php// Generates a random personal identify numberecho$faker->personalIdentityNumber; // A223456789
Faker\Provider\zh_TW\Company
<?php// Generates a random VAT / Company Tax numberecho$faker->VAT; //23456789
Third-Party Libraries Extending/Based On Faker
Symfony bundles:
willdurand/faker-bundle: Put the awesome Faker library into the Symfony2 DIC and populate your database with fake data.
pattern-lab/plugin-faker: Pattern Lab is a Styleguide, Component Library, and Prototyping tool. This creates unique content each time Pattern Lab is generated.
This file contains 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
This file contains 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
"name":"spatie/invade",
"description":"APHP function to work with private properties and methods",
// Olhar pra entender melhor
// vendor/spatie/invade/src/functions.php
// Acessa métodos protegidos
// > class P2 { protected function getNome() { return 'Tiago'; }}
// > $p = newP2()
// = P2 {#11802}// > $p->getNome()// Error Call to protected method P2::getNome() from global scope.// > invade($p)->getNome()// = "Tiago"
Prompt: tenho 2 models no Laravel; Model1 has many Model2 Quero trazer os itens de Model1 que tenha mais de X Model2
Filtrando Modelos com Base em Relações no Laravel
Para trazer os itens de Model1 que têm mais de um número específico de Model2, você pode usar o método has do Eloquent. O método has permite que você filtre os resultados com base na contagem de registros relacionados.
Exemplo de Código
Aqui está um exemplo de como você pode implementar isso:
useApp\Models\Model1;
$x = 5; // Defina o número mínimo de Model2 que você deseja$model1s = Model1::has('model2s', '>', $x)->get();
Explicação
Model1::has('model2s', '>', $x): Este método verifica se Model1 tem mais de X registros relacionados de Model2. O 'model2s' deve ser o nome do método de relacionamento definido no seu modelo Model1.
get(): Este método recupera todos os registros que atendem à condição especificada.
Definindo o Relacionamento
Certifique-se de que o relacionamento entre Model1 e Model2 esteja definido corretamente no seu modelo Model1. Aqui está um exemplo de como isso pode ser feito:
Performance: Usar has é eficiente, pois o Laravel gera uma consulta SQL que conta os registros relacionados, evitando a necessidade de carregar todos os registros de Model2.
Personalização: Você pode ajustar a condição para >=, <=, ou outros operadores conforme necessário.
Se precisar de mais detalhes ou ajuda com outra parte do seu projeto, estou aqui para ajudar! 😊
// If ProductPrice relation is 'productPrice', just runProduct::factory(1)->has(ProductPrice::factory(3))->create();
// But if has another name, like 'priceList', run thisProduct::factory(1)->has(ProductPrice::factory(3), 'priceList')->create()
// If ProductPrice relation is 'productPrice', just runProduct::factory(1)->has(ProductPrice::factory(3))->create();
// But if has another name, like 'priceList', run thisProduct::factory(1)->has(ProductPrice::factory(3), 'priceList')->create()
This file contains 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
This file contains 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
Não pode começar ou terminar com hífen, mas pode ter hífen no meio
Regex que valida um slug com letras minúsculas, números e hífen, permitindo hífen no meio, mas não permitindo começar ou terminar com hífen:
/^(?!-)(?!.*--)[a-z0-9-]+(?<!-)$/
Explicação do regex:
^ - Início da string.
(?!-) - Negative lookahead para garantir que não comece com hífen.
(?!.*--) - Negative lookahead para garantir que não contenha dois hífens consecutivos.
[a-z0-9-]+ - Permite letras minúsculas, números e hífen.
(?<!-)$ - Negative lookbehind para garantir que não termine com hífen.
$ - Fim da string.
Você pode usar esse regex para validar um slug em PHP, por exemplo:
No Laravel, o método fill é utilizado para preencher um modelo com um array de atributos. No entanto, ele não salva automaticamente as alterações no banco de dados. Para saber se houve alguma atualização após usar o fill, você deve seguir alguns passos.
Verificando Atualizações
Usar o Método isDirty:
Após preencher o modelo com fill, você pode usar o método isDirty para verificar se algum atributo foi modificado. Este método retorna true se algum dos atributos do modelo foi alterado desde a última vez que ele foi salvo.
This file contains 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