Skip to content

Instantly share code, notes, and snippets.

@tiagofrancafernandes
Last active May 3, 2024 14:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagofrancafernandes/25d801091d6fabbee23aac6c690c7aba to your computer and use it in GitHub Desktop.
Save tiagofrancafernandes/25d801091d6fabbee23aac6c690c7aba to your computer and use it in GitHub Desktop.
dev-laravel_snippets | snippets Laravel #devlaravel_snippets #/devlaravel_snippets #laravel

#----------------------------------------------------

.htaccess que parece resolver problemas no rewrite do laravel com Apache

Exemplo quando acontece do root path ao inves de '/' fica como '/index.php/'

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
<IfModule mod_headers.c>
	Header set Access-Control-Allow-Origin *
</IfModule>

#----------------------------------------------------

Route::middleware('auth:sanctum')->post('/current-token', function (\Illuminate\Http\Request $request) {
    // $request->user()->currentAccessToken()->logoutOtherDevices();

    /**
     * @var User $user
     */
    $user = $request->user();

    return response()->json([
        'user' => $user,
        'currentAccessToken' => $user->currentAccessToken(),
    ]);
});

Implementação de rotas de login, register e logout usando o Laravel Sanctum com testes.

  1. Rotas:
// routes/api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\RegisteredUserController;

// Rota de registro
Route::post('/register', [RegisteredUserController::class, 'store']);

// Rota de login
Route::post('/login', function (Request $request) {
    // Validar as credenciais do usuário
    if (auth()->attempt($request->only('email', 'password'))) {
        // Criar e retornar um token para o usuário
        $token = auth()->user()->createToken('AuthToken')->plainTextToken;
        return response()->json(['token' => $token]);
    }
    // Caso as credenciais sejam inválidas
    return response()->json(['error' => 'Credenciais inválidas'], 401);
});

// Rota de logout
Route::post('/logout', function (Request $request) {
    // Revoke o token atual do usuário autenticado
    $request->user()->currentAccessToken()->delete();
    return response()->json(['message' => 'Logout realizado com sucesso']);
})->middleware('auth:sanctum');
  1. Testes: Testes para as rotas de login, register e logout:
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithFaker;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class AuthTest extends TestCase
{
    use DatabaseTransactions;
    use WithFaker;

    public function testRegister()
    {
        $userData = [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'password' => 'password',
            'password_confirmation' => 'password',
        ];

        $response = $this->postJson('/api/register', $userData);

        $response->assertStatus(201)
            ->assertJsonStructure(['token']);
    }

    public function testLogin()
    {
        $user = User::factory()->create([
            'password' => bcrypt($password = 'password'),
        ]);

        $response = $this->postJson('/api/login', [
            'email' => $user->email,
            'password' => $password,
        ]);

        $response->assertStatus(200)
            ->assertJsonStructure(['token']);
    }

    public function testLogout()
    {
        Sanctum::actingAs(
            User::factory()->create()
        );

        $response = $this->postJson('/api/logout');

        $response->assertStatus(200)
            ->assertJson(['message' => 'Logout realizado com sucesso']);
    }
}
<?php

namespace App\Macroables;

use Closure;
use Illuminate\Support\Arr;

class MacroableCollection
{
    public static function dotGet(
        ?string $macroKey = 'dotGet',
        bool $onlyClosure = false,
    ): array|Closure {
        $macro = [
            $macroKey,
            function ($key) {
                return Arr::get(tap($this)->all(), $key);
            }
        ];

        return $onlyClosure ? $macro[1] : $macro;
    }
}
$myData = collect([
    'updated_at' => [
        'name' => 'updated_at',
        'label' => 'Deleted at',
    ],
    'id' => [
        'name' => 'id',
        'label' => 'ID',
    ],
]);
$myData->macro(...\App\Macroables\MacroableCollection::dotGet());

echo $myData->dotGet('id.name'); // id
echo $myData->dotGet('id.label'); // ID
# Environment
cp -n .env.example .env
sed -i '' 's/DB_CONNECTION=mysql/DB_CONNECTION=sqlite/' .env
sed -i '' 's/DB_DATABASE=/#DB_DATABASE=/' .env
touch database/database.sqlite
<?php
// Route Laravel Like (dev-snippets.../routing-pure-PHP.php)
// https://gist.githubusercontent.com/tiagofrancafernandes/abee4ff72fecde56e5a05a76528b7683/raw/1eb52fb9cce97dcd9aff5d9d6304211b8879b509/routing-pure-PHP.php

// https://shortcode.dev/laravel/faker.html

#----------------------------------------------------
//Arquivos / conteúdos yaml
// https://www.php.net/manual/pt_BR/function.yaml-parse-file.php
#----------------------------------------------------
//Validations
http://dev.tiagofranca.com/notas/devlaravel_snippets_validations
//GIST snippets Laravel
https://gist.github.com/tiagofrancafernandes/25d801091d6fabbee23aac6c690c7aba/edit

# Laravel-AdminLTE snippets
https://gist.github.com/tiagofrancafernandes/2c1ffb77d0e867e933cb627825828d9a
#----------------------------------------------------
// Debug SQL query
// app/Providers/AppServiceProvider.php
public function boot()
{
    //...

    $this->debugQueries();
}
protected function debugQueries()
{
    if (env('APP_DEBUG_QUERIES')) {
        DB::listen(function ($query) {
            error_log(
                "Query [$query->time ms]: $query->sql\n"
                . "Params: " . print_r($query->bindings, true)
            );
        });
    }
}

#----------------------------------------------------

## Laravel custom log

use Illuminate\Support\Facades\Log;

if (!function_exists('__log')) {
    /**
     * __log function
     *
     * a info level log
     *
     * @param mixed ...$params
     * @return void
     */
    function __log(...$params)
    {
        if (!$params) {
            throw new \TypeError("Too few arguments to function __log(). 0 passed and at least 1 expected", 1);
        }

        $logBuild = Log::build([
            'driver' => 'single',
            'path'   => storage_path('logs/laravel.log'),
        ]);

        if (count($params) === 1) {
            $logBuild->info($params[0] ?? '');
        } else {
            $logBuild->info($params);
        }
    }
}

#----------------------------------------------------

Validar ips dentro de um range

use Symfony\Component\HttpFoundation\IpUtils;

IpUtils::checkIp('187.32.131.210', ['187.32.131.0/32']);
// false

IpUtils::checkIp('187.32.131.210', ['187.32.131.0/24']);
// true

IpUtils::checkIp('187.32.132.210', ['187.32.131.0/24']);
// false

IpUtils::checkIp('187.32.132.210', ['187.32.131.0/24', '187.32.132.0/24']);
// true
// 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

#----------------------------------------------------

//Custom attributes
<<<'PHP'
    protected $appends = ['cover'];

    //define accessor
    public function getCoverAttribute()
    {
        return json_decode($this->InJson)->cover;
    }
PHP;

Vários items separado por virgulaviram array sem espaços. Bom para utilizar em configs

$items = 'abc, 123, sdsd, dfgf, sdff, ,some here'
array_map('trim', array_filter(explode(',', $items), 'trim'));

//Returns:
/*
    [
     0 => "abc",
     1 => "123",
     2 => "sdsd",
     3 => "dfgf",
     4 => "sdff",
     6 => "some here",
   ]
*/

#----------------------------------------------------

## aliases

alias artisan-clear-all='php ./artisan clear-compiled; php ./artisan auth:clear-resets; php ./artisan cache:clear; php ./artisan config:clear; php ./artisan event:clear; php ./artisan optimize:clear; php ./artisan queue:clear; php ./artisan route:clear; php ./artisan schedule:clear-cache; php ./artisan view:clear'

#----------------------------------------------------

#----------------------------------------------------
//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
/* ENVs
IGNITION_EDITOR='vscode'
IGNITION_THEME='dark'
ENV;
#----------------------------------------------------
#like foreach chunk loop foreach eloquent model quebra em pedaços
Flight::chunk(200, function ($flights) {

    foreach ($flights as $flight) {
        //
    }

});
#----------------------------------------------------
<<<'blade'
No template
@stack('styles')

No herdeiro
@push('styles')
@endpush
blade;

#---------------------------------------------------- #----------------------------------------------------

Ver queries executadas . SQL ou não (vi as do mongo aparecerem tbm)

#----------------------------------------------------

//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.php
use App\Traits\EmailConfirmation;

class User extends Authenticatable
{

    use EmailConfirmation;
    //...

}

//app/Traits/EmailConfirmation.php
<?php
namespace 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;

#---------------------------------------------------- // Massive import data from XLSX file assync // https://www.toptal.com/laravel/handling-intensive-tasks-with-laravel #----------------------------------------------------

Laravel factories / Factory

// Posso usar tanto pela model quanto pela factory ChamadoFactory::times(3)->create(); Chamado::factory()->times(3)->create(); #----------------------------------------------------

Queues e jobs

  • queues-e-jobs.php

Dispatching closure like a job

#---------------------------------------------------- //Laravel casts // custom-casts // https://laravel.com/docs/8.x/eloquent-mutators#custom-casts // json como collection <<<'PHP' use Illuminate\Database\Eloquent\Casts\AsCollection;

/**

  • The attributes that should be cast.

  • @var array */ protected $casts = [

    'options' => AsCollection::class,

]; PHP; #---------------------------------------------------- #Eventos e listeners https://dev.to/kingsconsult/laravel-8-events-and-listeners-with-practical-example-9m7 #---------------------------------------------------- #Enviando emails com o laravel https://mailtrap.io/blog/send-email-in-laravel/ #----------------------------------------------------

Criar error fake no Laravel

Artisan::command('fake-error', function () {

echo 5/0;

})->describe('Generate error - to test error actions'); #php artisan fake-error #---------------------------------------------------- #---------------------------------------------------- #Log personalizado

protected function logThis($logThis='',$toExit=false,$toAppend=false){
  $filename = base_path('storage/logs/temp_tgo_log.log');
  if($toAppend == false)
  file_put_contents($filename,'');
  $msg_log = "\n[".date('Y-m-d H:i:s')."]  ".print_r($logThis,true)."\n";
  error_log($msg_log, 3, $filename);
  if($toExit){
    exit();
  }
}

#---------------------------------------------------- //Mais em https://gist.github.com/tiagofrancafernandes/25d801091d6fabbee23aac6c690c7aba#file-form_unique_validation-php

//Validar unico e ignora igual se o igual tiver o campo deleted_at por softdelete https://stackoverflow.com/a/23376215/11716408

//usos: 'email' => 'required|min:1|unique:users, email, NULL, id, deleted_at, NULL' 'email' => 'required|string|max:60|unique: App\Models\User, email, NULL, id, deleted_at, NULL',

#---------------------------------------------------- #---------------------------------------------------- //with com colunas específicar (relações com colunas específicas) ->with([

'unidade' => function($query) {
    $query->select('id','nome',);
},
'usuario' => function($query) {
    $query->select('id','name',);
},

]) #---------------------------------------------------- --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

-- https://laravel.com/docs/7.x/queries#json-where-clauses UserOnZendesk::whereJsonContains('zendesk_data->suspended', true)->count(); --Ou -- https://laravel.com/docs/8.x/queries#whereraw-orwhereraw UserOnZendesk::whereRaw("zendesk_data::jsonb @> '{"suspended": true}'")->count();

--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)%'

-- https://www.postgresql.org/docs/12/functions-json.html

--Eloquent (https://laravel.com/docs/7.x/queries#json-where-clauses) -- DB::table('client_is_zendesk_organizations')->whereJsonContains('domain_names', 'pontomais.com.br')->toSql();

--Psql where (t.domain_names)::jsonb @> '["pontomais.com.br"]'::jsonb and t.zendesk_data::jsonb @> '{"suspended": true}'

#---------------------------------------------------- //Where on relationship (subquery?) App\Request::where('id', 4)

->whereHas('quotes', function ($query) {
    $query->where('status','=','3');
})
->with('quotes','sourceTable','destinationTable')
->get();

#---------------------------------------------------- #laravel doc menu scroll http://dev.tiagofranca.com/notas/devlaravel_doc_menu_scroll #---------------------------------------------------- #duplicate key value violates unique constraint "users_pkey" //No eloquent if(\DB::connection()->getPDO()->getAttribute(PDO:: ATTR_DRIVER_NAME) == 'pgsql') {

\DB::select("SELECT setval(pg_get_serial_sequence('users', 'id'), coalesce(max(id)+1, 1), false) FROM users;");

} #----------------------------------------------------

.htaccess que parece resolver problemas no rewrite do laravel com Apache

Exemplo quando acontece do root path ao inves de '/' fica como '/index.php/'

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L]

Header set Access-Control-Allow-Origin *
#---------------------------------------------------- #---------------------------------------------------- //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

$coluna = DB::connection()->getDoctrineColumn('partners', 'range_commissions');

//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;

}

//modo 2 $query = str_replace('PREQUERY', '', $query);

            $query      = str_replace('.', '%', $query);
            $query      = str_replace('-', '%', $query);
            $plan_query = str_replace('%', '', $query);
            $plan_query = implode('%',str_split($plan_query, 1));
            $paciente = Paciente::whereRaw("(
                LOWER(cpf) like '%". strtolower($query) ."%' OR
                LOWER(cpf) like '%". strtolower($plan_query) ."%'
            )");

#---------------------------------------------------- //Soft deletes no Laravel https://laravel.com/docs/8.x/eloquent#soft-deleting https://medium.com/@mateusgalasso/laravel-softdelete-53225310848f

//em uma tabela existente https://medium.com/@erickosma/laravel-adicionando-soft-deletes-em-uma-tabela-existente-c64c185c54aa #----------------------------------------------------

Helpers (não facades)

#Paths (https://laravel.com/docs/7.x/helpers#available-methods) app_path base_path config_path database_path mix public_path resource_path storage_path #----------------------------------------------------

Desabilitando o delete de um model:

protected static function boot()
{
    parent::boot();
    static::deleting(function ($model) {
        return false;
    });
}

#---------------------------------------------------- //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]);
});

} #---------------------------------------------------- //Breadcumbs

<ol class="breadcrumb">
    <?php $segments = ''; ?>
    @foreach(Request::segments() as $segment)
        <?php $segments .= '/'.$segment; ?>
        <?php $current = $segments === '/'.\Request::path() ?>
        @if($current)
        <li class="breadcrumb-item active" aria-current="page">
            {{ ucfirst($segment) }}
        </li>
        @else
        <li class="breadcrumb-item">
            <a href="{{ $segments }}">{{ ucfirst($segment) }}</a>
        </li>
        @endif
    @endforeach
</ol>
#---------------------------------------------------- //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...
    });
}

} #---------------------------------------------------- //Se rota atual é : // https://laracasts.com/discuss/channels/laravel/how-to-check-if-i-am-on-current-route-or-url @if(Route::current()->getName() != 'login') #---------------------------------------------------- //Criação fácil de formulários com 'Laravel Collective' #laraform https://laravelcollective.com/docs/6.x/html #---------------------------------------------------- //GuzzleHttp REQUEST COM RETORNO DE ERRO use GuzzleHttp\Client;

    $GET_TOKEN_PATH             = $PARTNER_PORTAL_BASE.'/api/partner_portal/leads';

        try {
            $client         = new Client();
            $response       = $client->request('POST', $GET_TOKEN_PATH, [
                'headers' => [
                    'Accept'        => 'application/json',
                    'Content-Type'  => 'application/json',
                    'Authorization' => 'Bearer '.$partner_token->portal_user_token,
                ],
                'body' => json_encode([
                    "lead"             => $lead_values,
                ])
            ]);

            return $response;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            if ($e->hasResponse()) {
                return $response = $e->getResponse();
            }

            return null;
        }

#---------------------------------------------------- //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) {

return stripos($item, $search) !== false;

});

dump($filtered); #---------------------------------------------------- //Run artisan command by route | https://laravel.com/docs/5.2/artisan#calling-commands-via-code Route::get('clear_cache', function () {

\Artisan::call('cache:clear');

dd("Cache is cleared");

});

Route::get('link', function () {

\Artisan::call('storage:link');

dd("Created storage link");

});

Route::get('artisan/{command}', function ($command) {

\Artisan::call($command);

dd("Run: ". $command);

}); #---------------------------------------------------- //Manter a query string na paginação {{ $users->withQueryString()->links() }} #---------------------------------------------------- //Validação de exists: $rules = [

#1
'business_category_id'  => 'required|numeric|exists:App\Models\BusinessCategory,id',
#2
'business_category_id'  => 'required|numeric|exists:business_categories,id',

]; #---------------------------------------------------- //validations/->validate | Validações com campos e/ou mensagens personalizadas/customizadas //https://stackoverflow.com/a/36157487/11716408 $rules = [

    'name'          => 'required|string|max:255',
    'email'         => 'required|string|email|max:255|unique:users',
    'password'      => 'required|string|min:8|confirmed',
    'role_id'       => 'required|integer|exists:roles,id',
    'supplier_id'   => 'required|integer|exists:suppliers,id',

]; $niceNames = [

'supplier_id' => 'Fornecedor',

]; $user_data = $this->validate($request, $rules, [], $niceNames); dd($user_data); #---------------------------------------------------- #---------------------------------------------------- //Validações na request $validator = \Validator::make($request->all(), [

'client_uuid'   => ['required'],
'client_secret' => ['required'],

]);

dd($validator->errors()); dd($validator->messages()); dd($validator->getMessageBag()); dd(get_class_methods($validator));

if ($validator->fails()) {} #---------------------------------------------------- #Usar o core do Laravel fora do Laravel (em um script externo)

make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); /*-------- END LARAVEL OUTSIDE ---------*/ //Your Code goes here! #---------------------------------------------------- ```php //Faker inline $faker = fn () => (\Faker\Factory::create());$faker()->name() (\Faker\Factory::create())->name() ``` #---------------------------------------------------- //Usando Faker/Factory pra gerar valores fake use Faker\Factory as Faker; $faker = Faker::create(); foreach(range(1, 30) as $index) { Employee::create([ 'email' => $faker->email(), 'name' => $faker->sentence(5), 'description' => $faker->paragraph(6), ]); } //Para doc, usar no tinker 'doc \Faker\Factory::create' //Usando Faker/Factory pra gerar valores fake $faker = \Faker\Factory::create(); $faker->email(); $faker->sentence(5); $faker->paragraph(6); #---------------------------------------------------- //Usando globalmente //resources/functions/global_functions.php if (!function_exists('faker')) { /** * Get an instance of the faker factory. * * @return \Faker\Generator */ function faker(mixed $locale = \Faker\Factory::DEFAULT_LOCALE): Faker\Generator { return \Faker\Factory::create($locale); } } /* composer.json autoload.files: [ "resources/functions/global_functions.php" ] */ #---------------------------------------------------- #Paginação Personalizada https://stackoverflow.com/questions/46617600/pagination-not-styled-in-laravel-5-5 //Pagination bootstrap 4 {{$posts->links("pagination::bootstrap-4")}} #---------------------------------------------------- @if(session()->has('error'))
{{ session()->get('error') }}
@endif @if(session()->has('success'))
{{ session()->get('success') }}
@endif #---------------------------------------------------- //Old na validação ou valor vindo da model //https://stackoverflow.com/a/62043687/11716408 {{ old('field_name') ?? $model->field_name ?? 'default' }} #---------------------------------------------------- #Referencias public function contactwhatsapp() { //'model lá' , 'referencia aqui', 'valor lá' return $this->belongsTo('App\ContactWhatsapp', 'id', 'contact_phone_id'); } #---------------------------------------------------- @if(Session::has('success'))
{{ Session::get('success') }}
@endif #---------------------------------------------------- #Intervalo de datas protected function getPartnerIsNew($partner_id) { $partner = Partner::where('id',$partner_id); $start_date = Carbon::parse( date("Y-m-d", strtotime( date('Y-m-d')." -2 month" )) ); $end_date = Carbon::parse( date('Y-m-d')); $partner->whereRaw('created_at >= ?', [$start_date->format('Y-m-d H:i:s')]); $partner->whereRaw('created_at <= ?', [$end_date->format('Y-m-d H:i:s')]); return ($partner->count() > 0); } #---------------------------------------------------- #Inserindo informaçõa na sessão: $request->session()->put('error', ['title' => 'Erro' , 'message' => $message]); ou //->with('error', ['title' => 'Erro' , 'message' => $message]); #---------------------------------------------------- #Manipulando arquivos com Laravel Se veioarquivo na requisição $request->hasFile('leads_csv_file') //Pegar o arquivo $request->file('leads_csv_file'); //Extensão: $file->getClientOriginalExtension(); //Pegar os métodos disponíveis: dd( get_class_methods($file) ); //Pegar o tmp path: $file->getPathName(); #---------------------------------------------------- #Pesquisando dd() ou dump() dentro de pastas grep -Rn -E "(dd\(|dump\()" ./resources/ && grep -Rn -E "(dd\(|dump\()" ./app/ #em um alias alias laravel-tem-dump-dd='grep -Rn -E "(dd\(|dump\()" ./resources/ && grep -Rn -E "(dd\(|dump\()" ./app/' #---------------------------------------------------- #---------------------------------------------------- //Artisan actions use Illuminate\Support\Facades\Artisan; Route::get('/clear-cache', function() { Artisan::call('cache:clear'); return "Cache is cleared"; }); #---------------------------------------------------- #script withot laravel using core php - Laravel small standalone one-off script without artisan command? https://stackoverflow.com/questions/57856875/laravel-small-standalone-one-off-script-without-artisan-command #php app/Script.php make(Illuminate\Contracts\Http\Kernel::class); $response = $kernel->handle( $request = Illuminate\Http\Request::capture() ); echo "hello world\n"; $res = User::find(9)->name; var_dump($res); echo "end!\n"; #---------------------------------------------------- #Session user data $user = $session = session()->get('session')['resource']; #---------------------------------------------------- #Multiple DB Connections in Laravel 2 databases https://fideloper.com/laravel-multiple-database-connections #---------------------------------------------------- #Baixar arquivo, no caso CSV $csv = implode("\n", $csv); $file_name = "propostas_". date('Y_m_d_H_i') ."_.csv"; $headers = array( "Content-type" => "text/csv", "Content-Disposition" => "attachment; filename=". $file_name, "Pragma" => "no-cache", "Cache-Control" => "must-revalidate, post-check=0, pre-check=0", "Expires" => "0", ); return new Response($csv, 200, $headers); #---------------------------------------------------- #Route group with middleware and prefix Route::group([ 'prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'auth', ], function () { Route::get('/', function () { // }); }); #---------------------------------------------------- /* //Coletando duplicados //Eloquent Laravel $dupli = DB::table('partners') ->select('code', DB::raw('COUNT( code )')) ->groupBy('code') ->havingRaw('COUNT( code )> 1') ->orderBy('code') ->get(); SimpleLog::logThis( $dupli, ['append','file'=>'temp_teste']); */ #---------------------------------------------------- #implementando o updateOrCreate php - laravel updateOrCreate method - Stack Overflow https://stackoverflow.com/a/42696141/11716408 https://laravel.com/docs/7.x/eloquent#other-creation-methods $newUser = \App\UserInfo::updateOrCreate([ //Add unique field combo to match here //For example, perhaps you only want one entry per user: 'user_id' => Auth::user()->id, ], [ 'about' => $request->get('about'), 'sec_email' => $request->get('sec_email'), 'gender' => $request->get("gender"), 'country' => $request->get('country'), 'dob' => $request->get('dob'), 'address' => $request->get('address'), 'mobile' => $request->get('cell_no') ]); #---------------------------------------------------- # Pegar dados contidos em config/app.php use Config; Config::get('app.locale'); //Pega o valor em 'locale' #---------------------------------------------------- #Cron jobs shell scheduling https://laravel.com/docs/5.8/scheduling #Running Laravel's scheduler without setting up CRON jo https://alexvanderbist.com/2019/running-laravel-scheduler-without-setting-up-cron/ #---------------------------------------------------- #Validar filtros booleanos em array request $bool_string = [ "keys" => ["true", "false", "1", "0"], "values" => ["true" => true,"false" => false, "1" => true, "0" => false] ]; $filter_paid = strtolower( array_get($_req_array, 'filter.paid') ); $paid = ( in_array( $filter_paid, $bool_string['keys'], true) ) ? $bool_string['values'][$filter_paid] : 'NOT_FILTER_BY_PAID'; $query = ( is_bool($paid) ) ? $query->paid( $paid ) : $query; #---------------------------------------------------- #Enum via collect e humanize abstract class ProposalTypeEnum extends Enum { const GRATIS = 1; const VANTAGEM = 2; const MAIS = 3; const MEDIO = 4; const GRANDE = 5; const FACIL = 6; const SUPER = 7; const CUSTOM = 8; const EFICAZ = 9; const FACIL_ANUAL = 11; const EFICAZ_ANUAL = 12; const VANTAGEM_ANUAL = 13; const MAIS_ANUAL = 14; const ESSENCIAL = 15; const ESSENCIAL_ANUAL = 16; protected static $humanizedNames = [ 'Gratis', 'Vantagem', 'Mais', 'Medio', 'Grande', 'Facil', 'Super', 'Custom', 'Eficaz', 'Facil Anual', 'Vantagem Anual', 'Mais Anual', 'Essencial', 'Essencial Anual', ]; protected static $attributes = [ ['id' => 1, 'grade' => 1, 'limit'=> 10, 'price' => 0], ['id' => 2, 'grade' => 4, 'limit'=> 50, 'price' => 180], ['id' => 3, 'grade' => 5, 'limit'=> 100, 'price' => 270], ['id' => 4, 'grade' => 10, 'limit'=> 300, 'price' => 239], ['id' => 5, 'grade' => 11, 'limit'=> 500, 'price' => 399], ['id' => 6, 'grade' => 2, 'limit'=> 10, 'price' => 60], ['id' => 7, 'grade' => 12, 'limit'=> 9999, 'price' => 0], ['id' => 8, 'grade' => 13, 'limit'=> 100, 'price' => 350], ['id' => 9, 'grade' => 3, 'limit'=> 25, 'price' => 120], ['id' => 11, 'grade' => 6, 'limit'=> 10, 'price' => 60], ['id' => 12, 'grade' => 7, 'limit'=> 25, 'price' => 120], ['id' => 13, 'grade' => 8, 'limit'=> 50, 'price' => 180], ['id' => 14, 'grade' => 9, 'limit'=> 100, 'price' => 270], ['id' => 15, 'grade' => 9, 'limit'=> 10, 'price' => 40], ['id' => 16, 'grade' => 9, 'limit'=> 10, 'price' => 384], ]; static function find($value) { $collection = collect(static::$attributes); $objectAttributes = $collection->where('id', $value)->first(); $values = static::getValues(); if (in_array($value, $values)) { return [ 'id' => $value, 'name' => static::humanize($value), 'grade' => $objectAttributes['grade'], 'limit' => $objectAttributes['limit'], 'price' => $objectAttributes['price'], ]; } } } #---------------------------------------------------- #Validar se uma conta existe e está ativa no login (https://stackoverflow.com/a/53305363) Custom validation # 1 - Dentro do metodo validate: ```php [ 'email' => 'required|string|email|exists:users,email,active,1', #ou (tem o mesmo resultado) $this->username() => [ 'required', \Illuminate\Validation\Rule::exists('users')->where(function ($query) { $query->where('active', 1); }), ], 'address.city_id' => [ 'required', \Illuminate\Validation\Rule::exists('App\Models\Product\CityRO', 'id'), ], 'name' => ['required', 'string', new Uppercase], ] ``` # 2 - Desntro de 'resources/lang/en/validation.php' na chave 'custom' 'email' => [ 'exists' => 'Account has been disabled. Contact our team.' ], #---------------------------------------------------- #Itens únicos por usuários: $cc_data_query_ids = DB::table('cn_checking_accounts as cc_sub') ->select(DB::raw('max(id) as biggest_ca_id')) ->distinct('partner_code') ->groupBy('partner_code') ->get(); $ids = []; foreach ($cc_data_query_ids as $id) { $ids[] = $id->biggest_ca_id; } $query = CA::whereIn('id', $ids); $query = $this->paginate($request, $query); $query = $this->sortable($request, $query); $cc_data = $this->serializeEach($query->get()); return $this->renderJson([ 'cc_data' => $cc_data, ]); #---------------------------------------------------- ##Flash message in session on blade template #-----No PHP ------------------------------ use Symfony\Component\HttpFoundation\Session\Session as SymfonySession; $messageSession = new SymfonySession; $messageSession->set('chave', 'valor'); return redirect()->route('home', compact('messageSession')); #-----No blade------------------------ @php $messageSession = new \Symfony\Component\HttpFoundation\Session\Session; @endphp if($messageSession->has("chave")){ $chave = $messageSession->get("chave"); echo $chave; $messageSession->remove('chave');//Exclui da sessão } @endphp #---------------------------------------------------- #Gmail apps https://myaccount.google.com/apppasswords DvTf=owhtrtrlraseyraz P+=ymdthxijprehvhgb MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=465 MAIL_USERNAME=email@serv.com MAIL_PASSWORD=APP_PASS MAIL_ENCRYPTION=ssl MAIL_FROM_ADDRESS=email@serv.com MAIL_FROM_NAME="${APP_NAME}" #---------------------------------------------------- #When error GuzzleHttp/Exception/RequestException with message 'cURL error 77: error setting certificate verify locations: CAfile: /tmp/curl_haxx_se_ca_cacert_pem.pem CApath: /etc/ssl/certs (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)' Use 'verify => false': new Client([ 'base_uri' => 'https://api.target', 'http_errors' => false, 'verify' => false, //guzzle/guzzle#1935 (comment) 'headers' => [ 'Content-Type' => 'application/json', 'access_token' => $this->access_token, 'app_token' => $this->app_token, ] ]); #----------- $response = Http::withOptions([ // 'debug' => true, 'verify' => false, ])->withHeaders([ 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Bearer nklxcvklxcvnklx' ])->put($url, [ "organization" => [ "domain_names" => [] ] ]); #---------------------------------------------------- //Validar range de CEP: http://dev.tiagofranca.com/notas/devphp_snippets https://repl.it/@tiagofrancafern/Validar-Range-de-Cep#index.php #---------------------------------------------------- #---------------------------------------------------- //https://github.com/ministracao-aulas/ajax_search_typeahead //Select2 Ajax (https://github.com/ministracao-aulas/ajax_search_typeahead) Informe o paciente //JS window.pesquisar_paciente = "{{ route('api.pesquisar_paciente') }}"; $('#pesquisar_paciente_input').select2({ ajax: { // url: function (params) { //Url dinamica // var _search = params.term ? params.term : ''; // return window.pesquisar_paciente +'/'+ _search; // }, url: window.pesquisar_paciente, dataType: 'json', type: 'GET', delay: 250, processResults: function (data) { return { results: $.map(data, function (item) { return { text: item.nome, id: item.id } }) }; } } }); #---------------------------------------------------- //Pesquisa no banco com regex e ignorando caracteres especiais $ignore_letters = "ãáéíàúóõê"; $query = strtolower($query); $query = str_replace('PREQUERY', '', $query); $query = str_replace('.', '%', $query); $ignore = implode("|\\", str_split($ignore_letters, 2)); $regex = "/\\$ignore/"; $query = preg_replace("/$ignore/", "%", $query); $paciente = Paciente::whereRaw("( LOWER(nome) like '%". strtolower($query) ."%' OR LOWER(responsavel_cpf) like '%". strtolower($query) ."%' OR LOWER(cpf) like '%". strtolower($query) ."%' )"); #---------------------------------------------------- #---------------------------------------------------- //Validation inline //custom validation 'sexo' => ['required', function ($attribute, $value, $fail) { if (in_array($value, ['M', 'F'])) { $fail(trans('validation.invalid_fields.sex')); } }], /* //lang/pt/validation.php 'invalid_fields' => [ 'sex' => 'O campo Sexo precisa ser válido', ], */ #---------------------------------------------------- //Laravel eloquent ignore fillable forcefill ignore fillable guard https://www.reddit.com/r/laravel/comments/ajdm7s/how_can_i_overridebypass_the_fillable_property/eeumxmh?utm_source=share&utm_medium=web2x&context=3 $user = (new DwHsClient)->forceFill($hs_clients); $user->save(); #---------------------------------------------------- #---------------------------------------------------- //Remover elementos com regex >>> preg_replace("/\W/", "", 'joaa~ao]aa'); //Deixa apenas alfa-numerico => "joaaaoaa" >>> preg_replace("/\w/", "", 'joaa~ao]aa'); //Deixa apenas NÃO alfa-numerico => "~]" >>> preg_replace("/\D+/", "", 'joaddoa34a'); //Deixa apenas números => "34" //Outros replaces https://stackoverflow.com/questions/10152894/php-replacing-special-characters-like-%c3%a0-a-%c3%a8-e/24572118#24572118 #---------------------------------------------------- //Config NGINX PHP http://dev.tiagofranca.com/notas/devnginx_laravel http://dev.tiagofranca.com/notas/devnginx #---------------------------------------------------- //php - O que Model::unguard () faz no arquivo seeder do banco de dados do Laravel 5? - Stack Overflow //Melhor explicação https://stackoverflow.com/a/59844427/11716408 Model::unguard() Currency::create([ 'rate' => 5.6, 'is_default' => true ]) Model::reguard() #---------------------------------------------------- //Has many com query public function proxima_agenda() { return $this->hasMany('App\AgendaHorario')->where('active', true)->where('date', '>=', date('Y-m-d'))->with(['unidade'])->take(1); } #---------------------------------------------------- //Constructor com middleware e except public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } #---------------------------------------------------- // Mongodb // https://github.com/jenssegers/laravel-mongodb #---------------------------------------------------- #---------------------------------------------------- ```sh ##PHP 7.4 install sudo apt install -y php7.4-fpm \ php7.4 \ php7.4-bcmath \ php7.4-bz2 \ php7.4-cli \ php7.4-common \ php7.4-curl \ php7.4-dev \ php7.4-gd \ php7.4-gmp \ php7.4-imap \ php7.4-mbstring \ php7.4-opcache \ php7.4-pgsql \ php7.4-sqlite3 \ php7.4-xml \ php7.4-zip \ php7.4-dom \ php7.4-intl \ php7.4-cli \ zip \ unzip \ openssl ``` #---------------------------------------------------- #---------------------------------------------------- #------ ## Se debian: //!! ```sh sudo apt-get install ca-certificates apt-transport-https software-properties-common wget curl lsb-release -y curl -sSL https://packages.sury.org/php/README.txt | sudo bash -x ``` ## Se debian: //!! ----------------------------------- ## Se alpine: //!! ```sh apk update && apk add --no-cache php81-fpm \ php81-bcmath \ php81-bz2 \ php81-cli \ php81-common \ php81-curl \ php81-dev \ php81-gd \ php81-gmp \ php81-imap \ php81-mbstring \ php81-opcache \ php81-mongodb \ php81-pgsql \ php81-pdo_pgsql \ php81-pdo_sqlite \ php81-mysqli \ php81-mysqlnd \ php81-sqlite3 \ php81-pecl-yaml \ php81-xml \ php81-zip \ php81-dom \ php81-intl \ php81-cli \ php81-xdebug \ php81-redis \ php81-pecl-uuid \ php81-gmp \ php81-imap \ php81-simplexml \ php81-sockets \ php81-openssl \ php81-pecl-lzf \ php81-doc \ php81-pecl-memcached \ php81-pecl-xdebug \ php81-pecl-mongodb \ php81-pecl-memcache \ php81-pecl-redis \ \ php81-pecl-swoole \ zip \ unzip \ openssl \ sqlite \ bash \ wget \ curl \ git \ nano \ util-linux \ hstr ``` ## FIM Se alpine: //!! #---------- ```sh ## set alternatives alias php-set-74='sudo update-alternatives --set php /usr/bin/php7.4; php -v' alias php-set-80='sudo update-alternatives --set php /usr/bin/php8.0; php -v' alias php-set-81='sudo update-alternatives --set php /usr/bin/php8.1; php -v' alias php-set-82='sudo update-alternatives --set php /usr/bin/php8.2; php -v' alias php-set-83='sudo update-alternatives --set php /usr/bin/php8.3; php -v' ``` ```sh ### Composer install sudo wget -c -O /usr/bin/composer 'https://getcomposer.org/download/latest-2.2.x/composer.phar' && \ sudo chmod +x /usr/bin/composer && /usr/bin/composer -V ``` ```sh ##PHP 8.0 install #Add ondrej/php PPA sudo add-apt-repository ppa:ondrej/php # Press enter when prompted. sudo apt-get update sudo apt install -y php8.0-fpm \ php8.0-bcmath \ php8.0-bz2 \ php8.0-cli \ php8.0-common \ php8.0-curl \ php8.0-dev \ php8.0-gd \ php8.0-gmp \ php8.0-imap \ php8.0-mbstring \ php8.0-opcache \ php8.0-mongodb \ php8.0-pgsql \ php8.0-mysql \ php8.0-sqlite3 \ php8.0-xml \ php8.0-zip \ php8.0-dom \ php8.0-intl \ php8.0-cli \ php8.0-xdebug \ php8.0-redis \ php8.0-yaml \ zip \ unzip \ openssl ``` #---------------------------------------------------- ```sh ##PHP 8.1 install #Add ondrej/php PPA sudo add-apt-repository ppa:ondrej/php # Press enter when prompted. sudo apt-get update sudo apt install -y \ php8.1-fpm \ php8.1-bcmath \ php8.1-bz2 \ php8.1-cli \ php8.1-common \ php8.1-curl \ php8.1-dev \ php8.1-gd \ php8.1-gmp \ php8.1-imap \ php8.1-mbstring \ php8.1-opcache \ php8.1-mongodb \ php8.1-pgsql \ php8.1-mysql \ php8.1-sqlite3 \ php8.1-xml \ php8.1-zip \ php8.1-dom \ php8.1-intl \ php8.1-cli \ php8.1-xdebug \ php8.1-redis \ php8.1-yaml \ zip \ unzip \ openssl \ sqlite3 ``` #------ #---------- ```sh ##PHP 8.2 install #Add ondrej/php PPA sudo add-apt-repository ppa:ondrej/php # Press enter when prompted. sudo apt-get update sudo apt install -y \ php8.2-fpm \ php8.2-bcmath \ php8.2-bz2 \ php8.2-cli \ php8.2-common \ php8.2-curl \ php8.2-dev \ php8.2-gd \ php8.2-gmp \ php8.2-imap \ php8.2-mbstring \ php8.2-opcache \ php8.2-mongodb \ php8.2-pgsql \ php8.2-mysql \ php8.2-sqlite3 \ php8.2-xml \ php8.2-zip \ php8.2-dom \ php8.2-redis \ php8.2-intl \ php8.2-cli \ php8.2-xdebug \ php8.2-redis \ php8.2-yaml \ zip \ unzip \ openssl \ sqlite3 ``` #---------- ```sh ##PHP 8.3 install #Add ondrej/php PPA sudo add-apt-repository ppa:ondrej/php # Press enter when prompted. sudo apt-get update sudo apt install -y \ php8.3-fpm \ php8.3 \ php8.3-bcmath \ php8.3-bz2 \ php8.3-cli \ php8.3-common \ php8.3-curl \ php8.3-dev \ php8.3-gd \ php8.3-gmp \ php8.3-imap \ php8.3-mbstring \ php8.3-opcache \ php8.3-pgsql \ php8.3-mysql \ php8.3-sqlite3 \ php8.3-xml \ php8.3-zip \ php8.3-dom \ php8.3-redis \ php8.3-intl \ php8.3-cli \ zip \ unzip \ openssl \ sqlite3 ```
<!-- Livewire typeahead -->
https://forum.laravel-livewire.com/t/search-with-autocomplete/2966/2
/**
 * scopeEasyWith function
 *
 * Usage:
 * ```
 * $query->easyWith(['category:id,name', 'brand'])
 * ```
 *
 * @param [type] $query
 * @param [type] ...$relations
 * @return void
 */
public function scopeEasyWith($query, ...$relations)
{
    $relations = is_array($relations[0] ?? null) ? $relations[0] : $relations;
    $relations = array_filter($relations, 'is_string');

    if (!$relations) {
        return $query;
    }

    foreach ($relations as $relation) {
        if (!is_string($relation) || !trim($relation)) {
            continue;
        }

        $relationOptions = array_filter(array_slice(explode(':', trim($relation)), 0, 2));

        if (!$relationOptions) {
            continue;
        }

        $relationName = trim((string) ($relationOptions[0] ?? null));
        $selectColumns = trim((string) ($relationOptions[1] ?? null));

        if (!$relationName || is_numeric($relationName)) {
            continue;
        }

        $selectColumns = $selectColumns ? array_filter(explode(',', $selectColumns), 'trim') : null;

        if ($selectColumns) {
            $query = $query->with([
                $relationName => fn($withQuery) => $withQuery->select($selectColumns),
            ]);

            continue;
        }

        $query = $query->with([$relationName]);
    }

    return $query;
}
//nos snippets tem o arquivo: ExecTimeTrack.php
//Rastrear pontos da aplicação que demoram mais tempo
$timer = new ExecTimeTrack('aaa');
$timer->startCheckpointToList('validacao');
sleep(1);
$timer->endCheckpointToList('validacao');

dd($timer->getCheckpointList());
<?php
namespace App\Libs;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class ExecTimeTrack
{
private string $timer_id = '';
public function __construct(string $timer_id = '')
{
$this->timer_id = $timer_id ? "_{$timer_id}" : '_' . Str::random(5);
$this->clear();
}
public function startCheckpointToList(string $checkpoint_name, bool $output = true)
{
$checkpoint_list = Cache::get("checkpoint_list_{$this->timer_id}", []);
$start = $checkpoint_list[$checkpoint_name]["start"] = microtime(true);
Cache::put("checkpoint_list_{$this->timer_id}", $checkpoint_list, 300);
if ($output) {
echo "\nstart checkpoint {$checkpoint_name}\n{$start}\n";
}
}
public function endCheckpointToList(string $checkpoint_name, bool $output = true)
{
$checkpoint_list = Cache::get("checkpoint_list_{$this->timer_id}", []);
$start = $checkpoint_list[$checkpoint_name]["start"] ?? null;
if (!$start) {
return;
}
$end = $checkpoint_list[$checkpoint_name]["end"] = microtime(true);
$diff = $checkpoint_list[$checkpoint_name]["diff"] = round(($end - $start), 4);
Cache::put("checkpoint_list_{$this->timer_id}", $checkpoint_list, 300);
if ($output) {
echo "\nend checkpoint {$checkpoint_name}\n{$end}\ndiff: {$diff}\n";
}
}
public function getCheckpointList()
{
return Cache::get("checkpoint_list_{$this->timer_id}", []);
}
public function clear()
{
Cache::forget("checkpoint_list_{$this->timer_id}");
}
}
<?php

namespace Yemenpoint\FilamentCustomFields\Resources;

use Closure;
use Filament\Forms;
use Filament\Tables;
use Illuminate\Support\Str;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Spatie\Html\Facades\Html;
use Filament\Resources\Resource;
use Filament\Forms\Components\Card;
use Filament\Forms\Components\Grid;
use Illuminate\Database\Eloquent\Model;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Yemenpoint\FilamentCustomFields\Models\CustomField;
use Yemenpoint\FilamentCustomFields\CustomFields\PermissionsHelper;
use Yemenpoint\FilamentCustomFields\Resources\CustomFieldResource\Pages;
use Yemenpoint\FilamentCustomFields\CustomFields\FilamentCustomFieldsHelper;

class CustomFieldResource extends Resource
{
    use PermissionsHelper;

    protected static ?string $resourceKey = 'custom_fields';

    protected static array $options = [];

    protected static ?string $model = CustomField::class;

    protected static ?string $navigationIcon = 'heroicon-o-collection';

    protected static function getNavigationGroup(): ?string
    {
        return __('filament-custom-fields::resource.navigation_group');
    }

    public static function getPluralModelLabel(): string
    {
        return __('filament-custom-fields::resource.custom_field_plural_label');
    }

    public static function getModelLabel(): string
    {
        return __('filament-custom-fields::resource.custom_field_label');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Card::make()->schema([
                    Forms\Components\Grid::make()->schema([
                        Forms\Components\Select::make('model_type')
                            ->label(__('filament-custom-fields::resource.custom_field.form.model_type.label'))
                            ->options(config("filament-custom-fields.models"))
                            ->required(),

                        Forms\Components\Select::make('type')
                            ->label(__('filament-custom-fields::resource.custom_field.form.type.label'))
                            ->reactive()
                            ->options(FilamentCustomFieldsHelper::getTypes())->default("text")
                            ->required(),

                        Forms\Components\TextInput::make('title')
                            ->label(__('filament-custom-fields::resource.custom_field.form.title.label'))
                            ->required(),
                        Forms\Components\TextInput::make('hint')
                            ->label(__('filament-custom-fields::resource.custom_field.form.hint.label')),

                        \Filament\Forms\Components\Fieldset::make('options_fieldset')
                            ->label(__('filament-custom-fields::resource.custom_field.form.select.options_fieldset.label'))
                            ->schema([
                                Forms\Components\Repeater::make('options')
                                    ->disableLabel()
                                    ->before(function (?Model $record) {
                                        static::$options = (array) ($record?->options ?? []);
                                    })
                                    ->columnSpan("full")
                                    ->hidden(fn (callable $get) => $get("type") != "select")
                                    ->schema([
                                        Grid::make(2)
                                            ->schema([
                                                Forms\Components\Hidden::make('updatedAt')
                                                    ->disabled()
                                                    ->dehydrateStateUsing(fn () => now()->format('c')),

                                                Forms\Components\TextInput::make('label')
                                                    ->label(__('filament-custom-fields::resource.custom_field.form.select.label.label'))
                                                    ->required()
                                                    ->reactive()
                                                    ->afterStateUpdated(
                                                        function (
                                                            ?string $state,
                                                            callable $set,
                                                            callable $get,
                                                            string $context,
                                                            ?Model $record,
                                                        ) {
                                                            if (($context != 'create') && $get('updatedAt')) {
                                                                return;
                                                            }

                                                            $count = collect($record?->options)
                                                                ->where('value', $state)->count();

                                                            $set('value', str($state)->slug()->append(
                                                                $count ? '_' . ($count + 1) : ''
                                                            ));
                                                        }
                                                    )
                                                    ->columnSpan(1),

                                                Forms\Components\TextInput::make('value')
                                                    ->label(__('filament-custom-fields::resource.custom_field.form.select.value.label'))
                                                    ->string()
                                                    ->required()
                                                    ->reactive()
                                                    ->afterStateUpdated(
                                                        function (
                                                            ?string $state,
                                                            ?string $old,
                                                            callable $get,
                                                            callable $set,
                                                            ?Model $record,
                                                        ) {
                                                            $state = trim((string) $state);

                                                            if ($get('updatedAt') || !($state && collect($record?->options)
                                                                ->where('value', $state)->count())) {
                                                                return;
                                                            }

                                                            Notification::make()
                                                                ->danger()
                                                                ->title(
                                                                    __('filament-custom-fields::resource.custom_field.form.select.value.validation.duplicated.title')
                                                                )
                                                                ->body(
                                                                    __('filament-custom-fields::resource.custom_field.form.select.value.validation.duplicated.body')
                                                                )
                                                                ->seconds(3)
                                                                ->id('select.value.validation.duplicated') // prevent duplication
                                                                ->send();

                                                            $set('value', $old ?: '');
                                                        }
                                                    )
                                                    ->disabled(function (?string $state, callable $get, ?Model $record) {
                                                        return $state && collect($record?->options)
                                                            ->where('value', $state)->count() && $get('updatedAt');
                                                    })
                                                    ->columnSpan(1),
                                            ]),
                                    ])
                                    ->grid(1),
                            ])
                            ->hidden(fn (callable $get) => $get("type") != "select"),

                        Grid::make(4)
                            ->schema([
                                Grid::make(4)
                                    ->schema([
                                        Forms\Components\Toggle::make('required')
                                            ->label(__('filament-custom-fields::resource.custom_field.form.required.label'))
                                            ->columnSpan(1)->default(true),
                                        Forms\Components\Toggle::make('show_in_columns')
                                            ->label(__('filament-custom-fields::resource.custom_field.form.show_in_columns.label'))
                                            ->columnSpan(1)->default(true),
                                    ]),
                                Forms\Components\TextInput::make('default_value')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.default_value.label')),
                                Forms\Components\TextInput::make('column_span')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.column_span.label'))
                                    ->numeric()->maxValue(12)->minValue(1)->default(1),
                                Forms\Components\TextInput::make('order')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.order.label'))
                                    ->numeric()->default(1),
                                Forms\Components\TextInput::make('rules')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.rules.label')),
                            ]),
                    ])
                ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make("id")
                    ->label(__('filament-custom-fields::resource.custom_field.table.id.label'))
                    ->searchable(isIndividual: true)
                    ->sortable(),

                Tables\Columns\TextColumn::make("order")
                    ->label(__('filament-custom-fields::resource.custom_field.table.order.label'))
                    ->sortable(),

                Tables\Columns\TextColumn::make("title")
                    ->label(__('filament-custom-fields::resource.custom_field.table.title.label'))
                    ->searchable(isIndividual: true),

                Tables\Columns\TextColumn::make("type")
                    ->label(__('filament-custom-fields::resource.custom_field.table.type.label')),

                Tables\Columns\TextColumn::make("model_type")
                    ->label(__('filament-custom-fields::resource.custom_field.table.model_type.label'))
                    ->searchable(isIndividual: true)
                    ->formatStateUsing(function ($state) {
                        $display = $state;
                        foreach (config("filament-custom-fields.models") as $key => $value) {
                            if ($key == $state) {
                                $display = $value;
                                break;
                            }
                        }
                        return $display;
                    }),

                Tables\Columns\TextColumn::make("rules")
                    ->label(__('filament-custom-fields::resource.custom_field.table.rules.label')),
                Tables\Columns\IconColumn::make("required")
                    ->label(__('filament-custom-fields::resource.custom_field.table.required.label'))

                    ->boolean(),
                Tables\Columns\IconColumn::make("show_in_columns")
                    ->label(__('filament-custom-fields::resource.custom_field.table.show_in_columns.label'))
                    ->boolean(),
            ])
            ->filters([
                Tables\Filters\Filter::make('type_number')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_number_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'number')),

                Tables\Filters\Filter::make('type_text')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_text_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'text')),

                Tables\Filters\Filter::make('type_select')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_select_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'select')),

                Tables\Filters\Filter::make('type_textarea')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_textarea_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'textarea')),

                Tables\Filters\Filter::make('type_rich_editor')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_rich_editor_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'rich_editor')),

                Tables\Filters\Filter::make('type_toggle')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_toggle_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'toggle')),

            ])
            ->actions([
                ...static::getTableActions(),
            ])
            ->headerActions([
                // Spatie import!!!!
                Tables\Actions\Action::make('import')
                    ->label(__('Import'))
                    ->action(fn () => static::getEloquentQuery())
                    ->requiresConfirmation()
                    ->modalContent(function () {
                        return Html::div('aaa');
                    })
                    // ->modalCancelAction()
                    // ->modalHeading()
                    // ->modalSubheading()
                    // ->modalActions([
                    //     //
                    // ])
                    ->form([
                        Forms\Components\Grid::make()->schema([
                            Forms\Components\Select::make('model_type')
                                ->label(__('filament-custom-fields::resource.custom_field.form.model_type.label'))
                                ->options(config("filament-custom-fields.models"))
                                ->required(),
                            Forms\Components\TextInput::make('email'),
                        ])
                    ])
                    ->closeModalByClickingAway(false)
                    ->formData([
                        'data' => [
                            'email' => 'aaa@sss.com',
                            'model_type' => 'model_type',
                        ],
                        'dd' => fn() => \Log::info([ __FILE__ . ':' . __LINE__])//NOCOMMIT
                    ])
                    ->mountUsing(function (?\Filament\Forms\ComponentContainer $form = null): void {
                        if (! $form) {
                            return;
                        }
                        $data = [
                            'email' => 'inited',
                        ];

                        \Log::info([__FILE__ . ':' . __LINE__]);

                        $form->fill($data);
                    })
                    // ->mountUsing(function () {
                    //     /* na abertura da modal */
                    //     \Log::info([__FILE__ . ':' . __LINE__]);//NOCOMMIT
                    //     return [
                    //         'email' => __LINE__ . 'aaa@sss.com',
                    //         'name' => 'algo',
                    //     ];
                    // })
                    ->mutateFormDataUsing(function (array $data): array {
                        /* aqui eu já tenho os dados do formulário e posso mudar os valores */
                        \Log::info([$data,  __FILE__ . ':' . __LINE__]);//NOCOMMIT
                        $data['user_id'] = auth()->id();
                        $data['line_' . __LINE__] = 'log';

                        // dd([$data, __FILE__ . ':' . __LINE__]);//NOCOMMIT
                        return $data;
                    })
                    ->before(function (array $data = []) {
                        /* aqui já tenho os dados do formulário e tratados */
                        \Log::info([$data,  __FILE__ . ':' . __LINE__]);//NOCOMMIT
                        // use Spatie\SimpleExcel\SimpleExcelReader;

                        // $rows is an instance of Illuminate\Support\LazyCollection
                        $rows = SimpleExcelReader::create($pathToCsv)->getRows();

                        $rows->each(function(array $rowProperties) {
                        // in the first pass $rowProperties will contain
                        // ['email' => 'john@example.com', 'first_name' => 'john']
                        });

                        $data['line_' . __LINE__] = 'log';
                        return $data;
                    })
                    ->after(function (array $data = []) {
                        /* depois da ação ('depois do que?) */
                        \Log::info([$data,   __FILE__ . ':' . __LINE__]);//NOCOMMIT
                        $data['line_' . __LINE__] = 'log';
                        return $data;
                    })
                    // ->successNotification(fn() => 'Success')
                    // ->successNotificationTitle(fn() => 'Success title')
                    ->tooltip(__('Import data')),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getTableActions(): array
    {
        return [
            Tables\Actions\EditAction::make(),
            Tables\Actions\ViewAction::make(),
            Tables\Actions\DeleteAction::make(),
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCustomFields::route('/'),
            'create' => Pages\CreateCustomField::route('/create'),
            'edit' => Pages\EditCustomField::route('/{record}/edit'),
        ];
    }

    /**
     * resourceKey function
     *
     * @return ?string
     */
    public static function resourceKey(): ?string
    {
        return static::$resourceKey ?? null;
    }
}

///////////////////////

<?php

namespace Yemenpoint\FilamentCustomFields\Resources;

use Closure;
use Filament\Forms;
use Filament\Tables;
use Illuminate\Support\Str;
use Filament\Resources\Form;
use Filament\Resources\Table;
use Spatie\Html\Facades\Html;
use Filament\Resources\Resource;
use Filament\Forms\Components\Card;
use Filament\Forms\Components\Grid;
use Illuminate\Database\Eloquent\Model;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Builder;
use Spatie\SimpleExcel\SimpleExcelReader;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Yemenpoint\FilamentCustomFields\Models\CustomField;
use Yemenpoint\FilamentCustomFields\CustomFields\PermissionsHelper;
use Yemenpoint\FilamentCustomFields\Resources\CustomFieldResource\Pages;
use Yemenpoint\FilamentCustomFields\CustomFields\FilamentCustomFieldsHelper;

class CustomFieldResource extends Resource
{
    use PermissionsHelper;

    protected static ?string $resourceKey = 'custom_fields';

    protected static array $options = [];

    protected static ?string $model = CustomField::class;

    protected static ?string $navigationIcon = 'heroicon-o-collection';

    protected static function getNavigationGroup(): ?string
    {
        return __('filament-custom-fields::resource.navigation_group');
    }

    public static function getPluralModelLabel(): string
    {
        return __('filament-custom-fields::resource.custom_field_plural_label');
    }

    public static function getModelLabel(): string
    {
        return __('filament-custom-fields::resource.custom_field_label');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Card::make()->schema([
                    Forms\Components\Grid::make()->schema([
                        Forms\Components\Select::make('model_type')
                            ->label(__('filament-custom-fields::resource.custom_field.form.model_type.label'))
                            ->options(config("filament-custom-fields.models"))
                            ->required(),

                        Forms\Components\Select::make('type')
                            ->label(__('filament-custom-fields::resource.custom_field.form.type.label'))
                            ->reactive()
                            ->options(FilamentCustomFieldsHelper::getTypes())->default("text")
                            ->required(),

                        Forms\Components\TextInput::make('title')
                            ->label(__('filament-custom-fields::resource.custom_field.form.title.label'))
                            ->required(),
                        Forms\Components\TextInput::make('hint')
                            ->label(__('filament-custom-fields::resource.custom_field.form.hint.label')),

                        \Filament\Forms\Components\Fieldset::make('options_fieldset')
                            ->label(__('filament-custom-fields::resource.custom_field.form.select.options_fieldset.label'))
                            ->schema([
                                Forms\Components\Repeater::make('options')
                                    ->disableLabel()
                                    ->before(function (?Model $record) {
                                        static::$options = (array) ($record?->options ?? []);
                                    })
                                    ->columnSpan("full")
                                    ->hidden(fn (callable $get) => $get("type") != "select")
                                    ->schema([
                                        Grid::make(2)
                                            ->schema([
                                                Forms\Components\Hidden::make('updatedAt')
                                                    ->disabled()
                                                    ->dehydrateStateUsing(fn () => now()->format('c')),

                                                Forms\Components\TextInput::make('label')
                                                    ->label(__('filament-custom-fields::resource.custom_field.form.select.label.label'))
                                                    ->required()
                                                    ->reactive()
                                                    ->afterStateUpdated(
                                                        function (
                                                            ?string $state,
                                                            callable $set,
                                                            callable $get,
                                                            string $context,
                                                            ?Model $record,
                                                        ) {
                                                            if (($context != 'create') && $get('updatedAt')) {
                                                                return;
                                                            }

                                                            $count = collect($record?->options)
                                                                ->where('value', $state)->count();

                                                            $set('value', str($state)->slug()->append(
                                                                $count ? '_' . ($count + 1) : ''
                                                            ));
                                                        }
                                                    )
                                                    ->columnSpan(1),

                                                Forms\Components\TextInput::make('value')
                                                    ->label(__('filament-custom-fields::resource.custom_field.form.select.value.label'))
                                                    ->string()
                                                    ->required()
                                                    ->reactive()
                                                    ->afterStateUpdated(
                                                        function (
                                                            ?string $state,
                                                            ?string $old,
                                                            callable $get,
                                                            callable $set,
                                                            ?Model $record,
                                                        ) {
                                                            $state = trim((string) $state);

                                                            if ($get('updatedAt') || !($state && collect($record?->options)
                                                                ->where('value', $state)->count())) {
                                                                return;
                                                            }

                                                            Notification::make()
                                                                ->danger()
                                                                ->title(
                                                                    __('filament-custom-fields::resource.custom_field.form.select.value.validation.duplicated.title')
                                                                )
                                                                ->body(
                                                                    __('filament-custom-fields::resource.custom_field.form.select.value.validation.duplicated.body')
                                                                )
                                                                ->seconds(3)
                                                                ->id('select.value.validation.duplicated') // prevent duplication
                                                                ->send();

                                                            $set('value', $old ?: '');
                                                        }
                                                    )
                                                    ->disabled(function (?string $state, callable $get, ?Model $record) {
                                                        return $state && collect($record?->options)
                                                            ->where('value', $state)->count() && $get('updatedAt');
                                                    })
                                                    ->columnSpan(1),
                                            ]),
                                    ])
                                    ->grid(1),
                            ])
                            ->hidden(fn (callable $get) => $get("type") != "select"),

                        Grid::make(4)
                            ->schema([
                                Grid::make(4)
                                    ->schema([
                                        Forms\Components\Toggle::make('required')
                                            ->label(__('filament-custom-fields::resource.custom_field.form.required.label'))
                                            ->columnSpan(1)->default(true),
                                        Forms\Components\Toggle::make('show_in_columns')
                                            ->label(__('filament-custom-fields::resource.custom_field.form.show_in_columns.label'))
                                            ->columnSpan(1)->default(true),
                                    ]),
                                Forms\Components\TextInput::make('default_value')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.default_value.label')),
                                Forms\Components\TextInput::make('column_span')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.column_span.label'))
                                    ->numeric()->maxValue(12)->minValue(1)->default(1),
                                Forms\Components\TextInput::make('order')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.order.label'))
                                    ->numeric()->default(1),
                                Forms\Components\TextInput::make('rules')
                                    ->label(__('filament-custom-fields::resource.custom_field.form.rules.label')),
                            ]),
                    ])
                ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make("id")
                    ->label(__('filament-custom-fields::resource.custom_field.table.id.label'))
                    ->searchable(isIndividual: true)
                    ->sortable(),

                Tables\Columns\TextColumn::make("order")
                    ->label(__('filament-custom-fields::resource.custom_field.table.order.label'))
                    ->sortable(),

                Tables\Columns\TextColumn::make("title")
                    ->label(__('filament-custom-fields::resource.custom_field.table.title.label'))
                    ->searchable(isIndividual: true),

                Tables\Columns\TextColumn::make("type")
                    ->label(__('filament-custom-fields::resource.custom_field.table.type.label')),

                Tables\Columns\TextColumn::make("model_type")
                    ->label(__('filament-custom-fields::resource.custom_field.table.model_type.label'))
                    ->searchable(isIndividual: true)
                    ->formatStateUsing(function ($state) {
                        $display = $state;
                        foreach (config("filament-custom-fields.models") as $key => $value) {
                            if ($key == $state) {
                                $display = $value;
                                break;
                            }
                        }
                        return $display;
                    }),

                Tables\Columns\TextColumn::make("rules")
                    ->label(__('filament-custom-fields::resource.custom_field.table.rules.label')),
                Tables\Columns\IconColumn::make("required")
                    ->label(__('filament-custom-fields::resource.custom_field.table.required.label'))

                    ->boolean(),
                Tables\Columns\IconColumn::make("show_in_columns")
                    ->label(__('filament-custom-fields::resource.custom_field.table.show_in_columns.label'))
                    ->boolean(),
            ])
            ->filters([
                Tables\Filters\Filter::make('type_number')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_number_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'number')),

                Tables\Filters\Filter::make('type_text')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_text_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'text')),

                Tables\Filters\Filter::make('type_select')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_select_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'select')),

                Tables\Filters\Filter::make('type_textarea')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_textarea_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'textarea')),

                Tables\Filters\Filter::make('type_rich_editor')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_rich_editor_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'rich_editor')),

                Tables\Filters\Filter::make('type_toggle')
                    ->label(__('filament-custom-fields::resource.custom_field.filters.type_toggle_label'))
                    ->query(fn (Builder $query): Builder => $query->where('type', 'toggle')),

            ])
            ->actions([
                ...static::getTableActions(),
            ])
            ->headerActions([
                // Spatie import!!!!
                Tables\Actions\Action::make('import')
                    ->label(__('Import'))
                    ->action(fn () => static::getEloquentQuery())
                    ->requiresConfirmation()
                    ->modalContent(function () {
                        return Html::div('aaa');
                    })
                    // ->modalCancelAction()
                    // ->modalHeading()
                    // ->modalSubheading()
                    // ->modalActions([
                    //     //
                    // ])
                    ->form([
                        Forms\Components\Grid::make()->schema([
                            // Forms\Components\Select::make('model_type')
                            //     ->label(__('filament-custom-fields::resource.custom_field.form.model_type.label'))
                            //     ->options(config("filament-custom-fields.models"))
                            //     ->required(),
                            // Forms\Components\TextInput::make('email'),


                            \Filament\Forms\Components\FileUpload::make('attachment')
                                ->getUploadedFileNameForStorageUsing(function (\Livewire\TemporaryUploadedFile $file): string {
                                    return (string) str($file->getClientOriginalName())->prepend('custom-prefix-');
                                }),

                            // ->acceptedFileTypes(['application/pdf'])
                            // \Filament\Forms\Components\FileUpload::make('attachment'),

                            // \Filament\Forms\Components\FileUpload::make('attachment')
                            //     // ->disk('s3')
                            //     ->directory('form-attachments')
                            //     ->visibility('private'),
                        ])
                    ])
                    ->closeModalByClickingAway(false)
                    ->formData([
                        'data' => [
                            'email' => 'aaa@sss.com',
                            'model_type' => 'model_type',
                        ],
                        'dd' => fn() => \Log::info([ __FILE__ . ':' . __LINE__])//NOCOMMIT
                    ])
                    ->mountUsing(function (?\Filament\Forms\ComponentContainer $form = null): void {
                        if (! $form) {
                            return;
                        }
                        $data = [
                            'email' => 'inited',
                        ];

                        \Log::info([__FILE__ . ':' . __LINE__]);

                        $form->fill($data);
                    })
                    // ->mountUsing(function () {
                    //     /* na abertura da modal */
                    //     \Log::info([__FILE__ . ':' . __LINE__]);//NOCOMMIT
                    //     return [
                    //         'email' => __LINE__ . 'aaa@sss.com',
                    //         'name' => 'algo',
                    //     ];
                    // })
                    ->mutateFormDataUsing(function (array $data): array {
                        /* aqui eu já tenho os dados do formulário e posso mudar os valores */
                        \Log::info([$data,  __FILE__ . ':' . __LINE__]);//NOCOMMIT

                        // $rows is an instance of Illuminate\Support\LazyCollection
                        $rows = SimpleExcelReader::create($data['attachment'], 'csv')
                            ->useDelimiter(';')
                            ->getRows();

                        $rows->each(function(array $rowProperties)use (&$data) {
                            $data['lines'][] = $rowProperties;
                            // in the first pass $rowProperties will contain
                            // ['email' => 'john@example.com', 'first_name' => 'john']
                        });
                        $data['user_id'] = auth()->id();
                        $data['line_' . __LINE__] = 'log';

                        // dd([$data, __FILE__ . ':' . __LINE__]);//NOCOMMIT
                        return $data;
                    })
                    ->before(function (array $data = []) {
                        sleep(1);
                        /* aqui já tenho os dados do formulário e tratados */
                        \Log::info([$data,  __FILE__ . ':' . __LINE__]);//NOCOMMIT

                        $data['line_' . __LINE__] = 'log';
                        return $data;
                    })
                    ->after(function (array $data = []) {
                        sleep(1);
                        /* depois da ação ('depois do que?) */
                        \Log::info([$data,   __FILE__ . ':' . __LINE__]);//NOCOMMIT
                        $data['line_' . __LINE__] = 'log';
                        return $data;
                    })
                    // ->successNotification(fn() => 'Success')
                    // ->successNotificationTitle(fn() => 'Success title')
                    ->tooltip(__('Import data')),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getTableActions(): array
    {
        return [
            Tables\Actions\EditAction::make(),
            Tables\Actions\ViewAction::make(),
            Tables\Actions\DeleteAction::make(),
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCustomFields::route('/'),
            'create' => Pages\CreateCustomField::route('/create'),
            'edit' => Pages\EditCustomField::route('/{record}/edit'),
        ];
    }

    /**
     * resourceKey function
     *
     * @return ?string
     */
    public static function resourceKey(): ?string
    {
        return static::$resourceKey ?? null;
    }
}
->actions([
                \Filament\Tables\Actions\EditAction::make(),
                \Filament\Tables\Actions\DeleteAction::make()
                    ->before(function (DeleteAction $action) {
                        $record = $action->getRecord();
                        if (!$record) {
                            return;
                        }

                        if ($record->can_be_deleted) {
                            Notification::make()
                                ->warning()
                                ->title('You don\'t have an active subscription!')
                                ->body('Choose a plan to continue.')
                                // ->persistent()
                                // ->actions([
                                //     Action::make('subscribe')
                                //         ->button()
                                //         ->url(route('subscribe'), shouldOpenInNewTab: true),
                                // ])
                                ->send();

                            $action->halt();
                        }
                    }),
            ])
new \Illuminate\Support\HtmlString('<div>Content</div>');
// teste
// .../grupo-gps/.../comptrade-web.../app/Filament/Resources/Book/BookResource/Pages/CreateBook.php ~250
protected function getTableBulkActions(): array
    {
        return [
            Tables\Actions\BulkAction::make('gerar')
                ->requiresConfirmation()
                ->deselectRecordsAfterCompletion()
                ->modalHeading('Gerar Book de PPT')
                ->label('Gerar Book de Power Point')
                ->modalContent(fn () => new HtmlString('<div>Antes de prosseguir, preencha o campo abaixo:</div>'))
                ->modalSubheading('Máximo de registros permitidos por book: 300')
                ->size(200)
                ->icon('heroicon-s-presentation-chart-line')
                ->form([
                    TextInput::make('name')
                        ->label('Nome do Book')
                        ->required(),

                    Forms\Components\Select::make('book_template_id')
                        ->label('Template')
                        ->required()
                        ->options(BookTemplate::pluck('nome', 'id'))
                        ->searchable(),
                ])
                ->deselectRecordsAfterCompletion(false)
                ->action(function (Collection $records, array $data) {
                    if(count($records) > 300){
                        Notification::make()
                            ->title('Registros selecionados atingiu o valor máximo.')
                            ->icon('heroicon-o-clock')
                            ->danger()
                            ->body('Você só pode gerar books de até 300 registros.')
                            ->iconColor('warning')
                            ->send()
                            ->sendToDatabase(auth()->user());
                        return;
                    }
                    DB::beginTransaction();

                    try {
                        $book = Book::query()->create([
                            'nome' => $data['name'],
                            'status' => 1,
                            'book_template_id' => $data['book_template_id'],
                        ]);

                        foreach ($records as $record) {
                            BookImage::query()->firstOrCreate([
                                'book_id' => $book['id'],
                                'file_id' => $record->id,
                            ]);
                        }
                    } catch (\Exception $exception) {
                        DB::rollBack();
                        dd($exception->getMessage());
                    }
                    DB::commit();

                    Notification::make()
                        ->title('Seu book está sendo gerado.')
                        ->icon('heroicon-o-clock')
                        ->warning()
                        ->body('Você será notificado quando terminarmos :)')
                        ->iconColor('warning')
                        ->send()
                        ->sendToDatabase(auth()->user());

                    ProcessBook::dispatch($book, auth()->user());
                })
            ->successNotificationTitle('Seu book está sendo gerado'),
        ];
    }
class CreateBook extends \Filament\Resources\Pages\CreateRecord
{
    protected function getTableQuery()
    {
        return File::query()
            ->select([
                //...
            ]);
    }

    //...
    protected function getDefaultTableSortColumn(): ?string
    {
        return 'roteiros.visitado_em';
    }

    protected function getDefaultTableSortDirection(): ?string
    {
        return 'desc';
    }
}

getEloquentQuery

class UserResource extends \Filament\Resources\Resource
{
    public static function getEloquentQuery(): Builder
    {
        return static::getModel()::query()
            ->select([
                //..
            ]);
    }
}
  • vendor/filament/filament/docs/09-configuration.md

SPA mode

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:

use Filament\Panel;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...
        ->spa();
}
    public static function getModelLabel(): string
    {
        return __('resources.category.label.singular');
    }

    public static function getPluralModelLabel(): string
    {
        return __('resources.category.label.plural');
    }
    // vendor/ryangjchandler/filament-feature-flags/src/Resources/FeatureFlagResource.php
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Group::make([
                    //
                ])
                    ->columnSpan(4),
                Card::make([
                    //
                ])
                    ->columnSpan(2),
            ])
            ->columns(6);
    }
FileUpload::make('Thumb')
    // ->image()
    ->acceptedFileTypes([
        'image/*', // O mesmo que efeito que->image()
    ])
// https://filamentphp.com/docs/2.x/forms/fields#date-time-picker
\Filament\Forms\Components\DatePicker::make('date_of_birth')
    ->minDate(now()->subYears(150))
    ->maxDate(now()),

    use Filament\Forms\Components\DateTimePicker;

DateTimePicker::make('date')
    ->label('Appointment date')
    ->minDate(now())
    ->maxDate(Carbon::now()->addDays(30))
    ->disabledDates(['2022-10-02', '2022-10-05', '2022-10-15'])
// Com opção 'Select all'
\Filament\Forms\Components\CheckboxList::make('technologies')
->options([
    'tailwind' => 'Tailwind CSS',
    'alpine' => 'Alpine.js',
    'laravel' => 'Laravel',
    'livewire' => 'Laravel Livewire',
])
->bulkToggleable(),

Grid

use Filament\Forms\Components\Grid;

Grid::make(1) // Força grids com 1 coluna apenas (full)
    ->schema([
        //
    ]),

Grid::make(3) // Força grids com 3 colunas
    ->schema([
        //
    ]),
Grid::make() // Grids responsivas com 2 colunas em md e lg
    ->schema([
        //
    ]),

Input full

Grid::make(3)
->schema([
    TextInput::make('slug')
        ->columnSpanFull() // Pega a coluna inteira
        ->unique(Post::class, 'slug')
        ->disabled(fn (Page $livewire) => $livewire instanceof EditRecord)
        ->dehydrated(fn (Page $livewire) => $livewire instanceof EditRecord),
]),

Código HTML

Placeholder::make('open_child_modal')
    ->disableLabel()
    ->content(
        new HtmlString('Click <button onclick="Livewire.emit(\'modal:open\', \'create-user-child\')" type="button" class="text-primary-500">here</button> to open a child modal🤩')
    ),

Input mask

https://filamentphp.com/docs/2.x/forms/fields#input-masking

use Filament\Forms\Components\TextInput;

TextInput::make('name')
    ->mask(fn (TextInput\Mask $mask) => $mask->pattern('+{7}(000)000-00-00'))

// TEM MAIS LÁ
// Enum mask
// Money mask
// etc

Páginas customizadas (alternativas ou adicionais ao edit/create/view etc)

// app/Filament/Resources/PostResource.php
public static function getPages(): array
{
    return [
        'index' => Pages\ListPosts::route('/'),
        'create' => Pages\CreatePost::route('/create'),
        'edit' => Pages\EditPost::route('/{record}/edit'),

        // Acessa: http://0.0.0.0:8000/admin/posts/1/custom
        'custom' => Pages\CustomPagePost::route('/{record}/custom'), // <<<<<====
    ];
}

Custom View

// app/Filament/Resources/PostResource/Pages/CustomPagePost.php

// Forma #1 - via atributo:
protected static string $view = 'my.custom.view';

// Forma #2 - via método render:
public function render(): View
{
    // Way 2.1
    return view(static::$view, $this->getViewData())
        ->layout(static::$layout, $this->getLayoutData());

    // Way 2.2
    return view('my.custom.view', [
        // 'data' => $this->data, // Optional???
    ])->layout(static::$layout, $this->getLayoutData());
}
public static function getPluralModelLabel(): string
{
    return __('filament/resources/customer.plural_label');
}
// vendor/filament/tables/src/Concerns/CanPaginateRecords.php:46 ~>
// vendor/filament/tables/src/Concerns/CanPaginateRecords.php:65 <~

    protected function getTableRecordsPerPageSelectOptions(): array
    {
        return config('tables.pagination.records_per_page_select_options') ?? [5, 10, 25, 50, -1];
    }

    protected function getDefaultTableRecordsPerPageSelectOption(): int
    {
        $perPage = session()->get(
            $this->getTablePerPageSessionKey(),
            $this->defaultTableRecordsPerPageSelectOption ?: config('tables.pagination.default_records_per_page'),
        );

        if (in_array($perPage, $this->getTableRecordsPerPageSelectOptions())) {
            return $perPage;
        }

        session()->remove($this->getTablePerPageSessionKey());

        return $this->getTableRecordsPerPageSelectOptions()[0];
    }

limit words and text

use Filament\Tables\Columns\TextColumn;

TextColumn::make('description')->limit(50);

TextColumn::make('description')->words(10);

Custom column view

// View column
// You may render a custom view for a cell using the view() method:

use Filament\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:

use Closure;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

public function table(Table $table): Table
{
    return $table
        ->recordClasses(fn (Model $record) => match ($record->status) {
            'draft' => 'opacity-30',
            'reviewing' => 'border-s-2 border-orange-600 dark:border-orange-300',
            'published' => 'border-s-2 border-green-600 dark:border-green-300',
            default => null,
        });
}

Render HTML (link,...) in a field label()

use Illuminate\Support\HtmlString;

Checkbox::make('accept')
    ->label(fn () => new HtmlString('I accept the <a href="" target="_blank">terms and conditions</a>'))
    ->required(),

Roles/permissins/policies

// ...
use Spatie\Permission\Models\Permission;
class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
        Permission::firstOrCreate(['name' => 'access filament']);
    }
}
// ...


class User extends Authenticatable implements \Filament\Models\Contracts\FilamentUser
{
    public function canAccessFilament(): bool
    {
        return $this->can('access filament');
    }
}
Forms\Components\Select::make('visible_to_type_user')
    ->label('USER')
    ->live()
    ->visible(
        fn(callable $get) => boolval(
            $get('visible_to_type') == DocumentVisibleToType::USER->value
        )
    )
    ->searchable()
    ->getSearchResultsUsing(
        fn(string $search): array => User::where('name', 'like', "%{$search}%")
            ->limit(30)
            ->pluck('name', 'id')
            ->toArray()
    )
    ->getOptionLabelUsing(fn($value): ?string => User::find($value)?->name),

Custom row classes

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:

use Closure;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

public function table(Table $table): Table
{
    return $table
        ->recordClasses(fn (Model $record) => match ($record->status) {
            'draft' => 'opacity-30',
            'reviewing' => 'border-s-2 border-orange-600 dark:border-orange-300',
            'published' => 'border-s-2 border-green-600 dark:border-green-300',
            default => null,
        });
}

Diversos métodos úteis na modificação do objeto:

vendor/filament/tables/src/Concerns/InteractsWithTable.php:~182 InteractsWithTable::table

Redirect

$this->redirect('some-path');
$this->redirect('some-path', ['id' => 1]);
$this->redirectRoute('profile', ['id' => 1]);
<a
class="nav-link btn btn-danger btn-flat btn-sm m-3"
onclick="if (! confirm('Confirma logout?')) {
return false;
} else {
event.preventDefault(); document.getElementById('logout-form').submit();
}"
href="#!">
Sair
</a>
<form id="logout-form" action="@route('logout')" method="POST" style="display: none;">
@csrf
</form>
<?php
use Illuminate\Validation\Rule;
$validation = Validator::make($request->all(), [
'sku' => [
'nullable', 'min:1', 'max:30',
Rule::unique('produtos')->where(function ($query) use ($request, $supplier)
{
return $query->where('sku', $request->sku)
->where('supplier_id', $supplier->id);
}),
],
// Validar unico e ignora igual se o igual tiver o campo deleted_at por softdelete
// https://stackoverflow.com/a/23376215/11716408
//usos:
'email' => 'required|min:1|unique:users,email,NULL,id,deleted_at,NULL'
'email' => 'required|string|max:60|unique:App\Models\User,email,NULL,id,deleted_at,NULL',
//Útil em uma atualização. Verifica se nao ha outro com o nome (que não seja esse)
'permission_name' => 'required|regex:/^[a-z_]+$/|string|min:5|max:30|unique:permissions,name,' . $permission_id,
]);
<?php
if (!function_exists('faker')) {
/**
* function faker
*
* @param string $locale = 'en_US'
* @return \Faker\Generator
*/
function faker(string $locale = 'en_US'): \Faker\Generator
{
return (\Faker\Factory::create())
}
}
<?php
// class-less functions
if (!function_exists('__only')) {
/**
* function __only
*
* @param array $arraySource
* @param array $arrayFilter
* @param ?callable $aditionalCallable
* @param ?int $mode ARRAY_FILTER_USE_BOTH | ARRAY_FILTER_USE_KEY
*
* @return array
*/
function __only(
array $arraySource,
array $arrayFilter,
?callable $aditionalCallable = null,
?int $mode = ARRAY_FILTER_USE_BOTH
): array {
$data = array_filter(
$arraySource,
fn ($item) => in_array($item, array_values($arrayFilter), true),
array_is_list($arraySource) ? ARRAY_FILTER_USE_BOTH : ARRAY_FILTER_USE_KEY
);
if (!$aditionalCallable) {
return $data;
}
$mode = in_array(
$mode,
[ARRAY_FILTER_USE_BOTH, ARRAY_FILTER_USE_KEY],
true
)
? $mode : ARRAY_FILTER_USE_BOTH;
return array_filter($data, $aditionalCallable, $mode);
}
}
if (!function_exists('getValidString')) {
/**
* function validString
*
* @param mixed $item
* @param ?callable $customValidation
*
* @return string
*/
function validString(mixed $item, ?callable $customValidation = null): string
{
if (!$item || !\is_string($item) || !trim($item) || empty($item)) {
return '';
}
if (!$customValidation) {
return trim($item);
}
return !$customValidation($item) ? '' : trim($item);
}
}
if (!function_exists('explodeAndMerge')) {
/**
* function explodeAndMerge
*
* @param array $current
* @param ?string $stringValue
* @param ?string $separator
* @param ?bool $stringOnly To use 'string' values only or to merge? If false|null, will merge (use both)
*
* @return array
*/
function explodeAndMerge(
array $current,
?string $stringValue,
?string $separator = ',',
?bool $stringOnly = false
): array {
$separator = $separator ?: ',';
$valuesToWork = !$stringOnly ? array_merge(
$current,
explode($separator, (string) $stringValue)
) : explode($separator, (string) $stringValue);
return array_unique(
array_values(
array_map(
'trim',
array_filter(
$valuesToWork,
'trim'
)
)
)
);
}
}
if (!function_exists('arrGetByDot')) {
/**
* function arrGetByDot
* Like \Arr::get on Laravel
* @param array $sourceData
* @param string $dotKey
* @param mixed $defaultValue
*
* @return mixed
*/
function arrGetByDot(array $sourceData, string $dotKey, mixed $defaultValue = null): mixed
{
if (!$dotKey || !trim($dotKey)) {
return $defaultValue ?? null;
}
foreach (explode('.', $dotKey) as $key) {
if (!array_key_exists($key, $sourceData)) {
return $defaultValue ?? null;
}
$sourceData = $sourceData[$key] ?? $defaultValue ?? null;
}
return $sourceData ?? $defaultValue ?? null;
}
}
if (!function_exists('filterUsingDot')) {
/**
* function filterUsingDot
*
* @param array $sourceData
* @param array $dotKeys
*
* @return mixed
*/
function filterUsingDot(array $sourceData, array $dotKeys): mixed
{
if (!array_is_list($dotKeys)) {
return null;
}
foreach ($dotKeys as $key) {
if (!$key || !is_string($key)) {
continue;
}
if ($tmp = arrGetByDot($sourceData, $key)) {
$filtered[$key] = $tmp;
}
}
return $filtered ?? null;
}
}
<?php
//app/Http/Middleware/HasValidSignature.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class HasValidSignature
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (! $request->hasValidSignature()) {
abort(401);
}
return $next($request);
}
}
//--------------------------------------------------------
//app/Http/Kernel.php
protected $routeMiddleware = [
//...
'signed_url' => \App\Http\Middleware\HasValidSignature::class,
];
//--------------------------------------------------------
//routes/web.php
Route::prefix('signed_url')->middleware(['signed_url'])->group(function () {
Route::get('/homologacao/{chamado_id}/mac{usuario_id}/email_url', [HomologacaoController::class, 'homologarEmailUrl'])->name('homologacao_email_url');
});
<?php
require_once __DIR__ . '/core.php';
use App\Models\Area;
use App\Models\AreasUsuario;
use App\Models\Unidade;
use App\Models\Usuario;
use Spatie\SimpleExcel\SimpleExcelReader;
use Spatie\SimpleExcel\SimpleExcelWriter;
function generateSheet(array $data, string $outputFilePath)
{
$extension = pathinfo($outputFilePath, PATHINFO_EXTENSION);
if (!$outputFilePath || !in_array($extension, ['csv', 'xlsx']))
{
return null;
}
SimpleExcelWriter::create($outputFilePath)
->addRows($data);
}
function getOrCreateUsuario(array $usuarioData, bool $return_error_line = false)
{
if (
!($usuarioData['nome'] ?? null) ||
!($usuarioData['email'] ?? null) ||
!filter_var($usuarioData['email'], FILTER_VALIDATE_EMAIL)
)
{
return $return_error_line ? __FILE__.':'.__LINE__ : false;
}
$randPassword = \Str::random(7);
$ecryptedPassword = \Hash::make($randPassword);
$usuario = Usuario::where('email', $usuarioData['email'])->first();
if($usuario)
{
$usuario->update(['password' => $ecryptedPassword]);
return [
'usuario' => $usuario,
'password' => $randPassword,
];
}
$usuario = Usuario::create([
'name' => $usuarioData['nome'] ?? null,
'email' => $usuarioData['email'] ?? null,
'telefone_1' => $usuarioData['telefone_1'] ?? null,
'telefone_1_wa' => $usuarioData['telefone_1_wa'] ?? null,
'ue' => null,
'versao' => 'v1',
'app_admin' => false,
'email_verified_at' => $usuarioData['email_verified_at'] ?? null,
'password' => $ecryptedPassword,
]);
if($usuario)
{
return [
'usuario' => $usuario,
'password' => $randPassword,
];
}
return $return_error_line ? __FILE__.':'.__LINE__ : false;
}
function assignRole(Usuario $usuario, string $roleName)
{
if (!$roleName)
{
return false;
}
$role = \Role::where('name', $roleName)->first();
if (!$role)
{
return false;
}
$usuario->assignRole($role);
}
function insertUsuarionOnArea(int $usuarioId, string $nomeArea)
{
if (!$usuarioId || !$nomeArea)
{
return false;
}
$area = Area::where('nome', $nomeArea)->first();
if (!$area)
{
return false;
}
AreasUsuario::create([ 'usuario_id' => $usuarioId, 'area_id' => $area->id, ]);
}
function insertUsuarionOnUnidade(Usuario $usuario, string $nomeUnidade)
{
if (!$usuario || !$nomeUnidade)
{
return false;
}
$unidade = Unidade::where('nome', $nomeUnidade)->first();
if (!$unidade)
{
return false;
}
$usuario->update([ 'unidade_id' => $unidade->id, ]);
}
function processFile(string $pathToFile)
{
$extension = pathinfo($pathToFile, PATHINFO_EXTENSION);
if (!$pathToFile || !in_array($extension, ['csv', 'xlsx']))
{
return null;
}
$requiredHeaders = [
'email', 'nome', 'area', 'atendente', 'unidade', 'papel', 'cpf',
];
$init = SimpleExcelReader::create($pathToFile)->headersToSnakeCase();
$headers = $init->getHeaders();
$valid_data = ($headers == $requiredHeaders);
$createdUsers = [];
$init->getRows()
->each(function (array $rowProperties) use (&$createdUsers)
{
$usuarioCreation = getOrCreateUsuario($rowProperties);
$usuario = $usuarioCreation['usuario'] ?? null;
$password = $usuarioCreation['password'] ?? null;
if(!$usuario)
{
return;
}
$createdUsers[] = [
'email' => $usuario->email ?? null,
'password' => $password,
];
if($rowProperties['area'] && is_string($rowProperties['area']))
{
insertUsuarionOnArea($usuario->id, $rowProperties['area']);
}
if(
$rowProperties['atendente'] &&
is_string($rowProperties['atendente']) &&
in_array(
strtolower($rowProperties['atendente']),
['sim', 'yes', '1', 'true']
)
)
{
assignRole($usuario, 'atendente');
}
assignRole($usuario, 'usuario');
if($rowProperties['papel'] && is_string($rowProperties['papel']))
{
assignRole($usuario, $rowProperties['papel']);
}
if($rowProperties['unidade'] && is_string($rowProperties['unidade']))
{
insertUsuarionOnUnidade($usuario, $rowProperties['unidade']);
}
});
generateSheet($createdUsers, 'usuarios_cadastrados.xlsx');
}
$fileName = __DIR__.'/planilha.xlsx';
/*
planilha.xlsx/csv
email;nome;area;atendente;unidade;papel;cpf
pedro@site.com;Pedro da Silva;Contabilidade;sim;Adm Central;usuario
*/
processFile($fileName);
<?php
//eloquent db get unique values
//model get unique values
$users = User::select('name')->distinct()->get();
## shell/bash
## Executando queue:work --once em loop reiniciando o processo sempre
## while true; do echo -e "\nnew proccess"; php artisan queue:work --once; done
## clear; while true; do echo -e "\nListening queues... "$(date +%H:%M:%S); php artisan queue:work --once; clear; done

Transition on show/hide

<div x-data="{ open: false }">
    <button @click.prevent="open = !open" type="button">Toggle</button>
    <span x-show="open" x-transition:enter="transition ease-in-out duration-300" x-transition:leave="transition ease-in-out duration-300 opacity-0">Hello 👋</span>
</div>
<!-- Livewire/Alpine -->
<div
    x-data="{}"
    x-sortable
    x-on:end="console.log('Sorting ended!', $event)"
    class="flex flex-col gap-2 py-3">
    @foreach (range(1, 2) as $key => $item)
        <div
            x-sortable-handle
            x-sortable-item="{{ $key }}"
            class="py-2 px-4 space-y-2 bg-white rounded-lg border border-gray-300 w-full flex dark:bg-gray-700 dark:border-gray-600"
        >
            Item #{{ $item }}
        </div>
    @endforeach
</div>
<?php
\URL::temporarySignedRoute( 'homologacao_email_url', now()->addMinutes(30), [10, 2]);
function homologarEmailUrl(Request $request, $chamado_id, $usuario_id)
{
$chamado = Chamado::with([
'usuario' => function($query) {
$query->select('id','name',);
},
])
->where('id', $chamado_id)
->where('usuario_id', $usuario_id)
->first();
if (!$chamado)
return redirect()->route('homologacao_index')->with('error', 'Chamado não encontrado ou inválido para homologação');
$usuario = $chamado->usuario;
if (!$usuario)
abort(401);
$auth = \Illuminate\Support\Facades\Auth::loginUsingId($usuario->id, true);
if (!$auth)
abort(401);
return redirect()->route('homologacao_show', $chamado_id);
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $appends = [
'has_plan'
];
public function getHasPlanAttribute()
{
return !!$this->plan_id;
}
}
//Usage
Customer::first()->has_plan;
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class Book extends Model
{
use SoftDeletes;
protected $connection = 'mongodb';
protected $collection = 'books';
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
protected $fillable = [
'title',
'image',
];
}
<?php
//...
// https://github.com/jenssegers/laravel-mongodb
return [
'connections' => [
//...
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGO_DB_HOST', '127.0.0.1'),
'port' => env('MONGO_DB_PORT', 27017),
'database' => env('MONGO_DB_DATABASE', 'homestead'),
'username' => env('MONGO_DB_USERNAME', 'homestead'),
'password' => env('MONGO_DB_PASSWORD', 'secret'),
'options' => [
// here you can pass more settings to the Mongo Driver Manager
// see
// https://www.php.net/manual/en/mongodb-driver-manager.construct.php
// under "Uri Options" for a list of complete parameters that you can use
'database' => env('MONGO_DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+
],
],
]
];
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
/**
* Usage:
* 'address.city_id' => [
* 'required',
* 'integer',
* new \App\Rules\CustomExists('App\Models\City', 'id'),
* ],
*/
class CustomExists implements Rule
{
protected static string $message = 'The :attribute is invalid';
protected string $model;
protected string $column;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(string $model, string $column)
{
$this->model = $model;
$this->column = $column;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
try {
return $this->model::exists($this->column, $value);
} catch (\Throwable $th) {
static::$message = "Some error to validate '{$attribute}'. Please, check the logs.";
\Log::error($th);
return false;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return static::$message;
}
}
<?php
use Illuminate\Support\Fluent;
if (!function_exists('fluent')) {
/**
* function fluent
*
* @param mixed $data
*
* @return Fluent
*/
function fluent($data = []): Fluent
{
if (is_a($data, Fluent::class)) {
return $data;
}
return new Fluent(
is_iterable($data) ? $data : [$data]
);
}
}
if (!function_exists('safe')) {
/**
* safe function -- A easy way to try/catch run
*
* ```php
* // Usage:
* safe(fn () => 'may be error action', fn (\Throwable $th) => 'catch action here')
* ```
*
* @param \Closure $runner
* @param \Closure|null $throwableCatcher
*
* @return mixed
*/
function safe(Closure $runner, ?Closure $throwableCatcher = null): mixed
{
try {
return $runner();
} catch (\Throwable $th) {
if (!$throwableCatcher) {
return false;
}
return $throwableCatcher($th);
}
}
}
if (!function_exists('array_first')) {
/**
* Get the first element of an array.
*
* @param array $array
* @param mixed $defaultValue
*
* @return mixed
*/
function array_first(array $array, mixed $defaultValue = null)
{
return $array[array_key_first($array)] ?? $defaultValue;
}
}
if (!function_exists('array_last')) {
/**
* Get the last element of an array.
*
* @param array $array
* @param mixed $defaultValue
*
* @return mixed
*/
function array_last(array $array, mixed $defaultValue = null)
{
return $array[array_key_last($array)] ?? $defaultValue;
}
}
if (!function_exists('rescue')) {
/**
* Catch a potential exception and return a default value.
*
* Copy of vendor/laravel/framework/src/Illuminate/Foundation/helpers.php [2023-08-22]
*
* @param callable $callback
* @param mixed $rescue
* @param bool|callable $report
* @return mixed
*/
function rescue(callable $callback, $rescue = null, $report = true)
{
try {
return $callback();
} catch (\Throwable $e) {
if (value($report, $e)) {
report($e);
}
return value($rescue, $e);
}
}
}
if (!function_exists('head')) {
/**
* Get the first element of an array. Useful for method chaining.
*
* Copy of vendor/laravel/framework/src/Illuminate/Foundation/helpers.php [2023-08-22]
*
* @param array $array
* @return mixed
*/
function head($array)
{
return reset($array);
}
}
if (!function_exists('last')) {
/**
* Get the last element from an array.
*
* Copy of vendor/laravel/framework/src/Illuminate/Foundation/helpers.php [2023-08-22]
*
* @param array $array
* @return mixed
*/
function last($array)
{
return end($array);
}
}
if (!function_exists('value')) {
/**
* Return the default value of the given value.
*
* Copy of vendor/laravel/framework/src/Illuminate/Foundation/helpers.php [2023-08-22]
*
* @param mixed $value
* @param mixed ...$args
* @return mixed
*/
function value($value, ...$args)
{
return $value instanceof \Closure ? $value(...$args) : $value;
}
}
use Illuminate\Support\Collection;

if (!function_exists('objectify')) {
    /**
     * function objectify
     *
     * @param mixed $content
     *
     * @return object
     */
    function objectify(mixed $content): object
    {
        return new class($content)
        {
            protected Collection $content;

            public function __construct(
                mixed $content
            )
            {
                $content = in_array(gettype($content), ['integer', 'double', 'NULL']) ? ['data' => $content] : $content;
                $this->content = collect($content);
            }

            public function __get(string $key)
            {
                return $this->get($key, null);
            }

            public function get(?string $key = null, mixed $defaultValue = null): mixed
            {
                if (!$key) {
                    return $this->collect();
                }

                return $this->collect()->get($key, $defaultValue);
            }

            public function collect(): Collection
            {
                return $this->content;
            }

            public function content(): Collection
            {
                return $this->collect();
            }

            public function typeIs(string $key, string $type, bool $checkInstance = false): Collection
            {
                $value = $this->get($key);

                if ($checkInstance) {
                    return is_a($value, $type);
                }

                return gettype($value, $type);
            }

            public function truly(string $key, mixed $defaultValue = null, mixed $trulyIfIs = null): mixed
            {
                $value = $this->get($key, '__NOT_FOUND__');

                if ($value === '__NOT_FOUND__') {
                    return $defaultValue;
                }

                if ($trulyIfIs !== null) {
                    return $trulyIfIs === $value ? $value : $defaultValue;
                }

                return $value ?: $defaultValue;
            }

            public function elvis(string $key, mixed $defaultValue = null): mixed
            {
                return $this->truly($key, $defaultValue);
            }
        };
    }
}
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Cache;
class PreventDuplication
{
/**
* @param array $data
* @param ?int $ttl 60
*
* Prevent duplicate
* @return bool
*/
public static function recentProcessed(array $data, ?int $ttl = 60): bool
{
$string = md5(http_build_query($data));
if (Cache::has($string)) {
return true;
}
Cache::put($string, $string, $ttl ?: 60);
return false;
}
}
<?php

use Illuminate\Support\Facades\Config;

if (!function_exists('runOnQueueScope')) {
    /**
     * function runOnQueueScope
     *
     * @param ?string $targetQueueConnectionName
     * @param ?\Closure $callableScope
     *
     * @return mixed
     */
    function runOnQueueScope(?string $targetQueueConnectionName, ?\Closure $callableScope): mixed
    {
        if (!$targetQueueConnectionName || !$callableScope) {
            return null;
        }

        $currentQueueDefault = Config::get('queue.default');

        if ($targetQueueConnectionName && ($targetQueueConnectionName != $currentQueueDefault)) {
            Config::set('queue.default', $targetQueueConnectionName);
        }

        $result = $callableScope();

        if (!$currentQueueDefault) {
            return $result ?? null;
        }

        if ($targetQueueConnectionName && ($targetQueueConnectionName != $currentQueueDefault)) {
            Config::set('queue.default', $currentQueueDefault);
        }

        return $result ?? null;
    }
}

uso da função runOnQueueScope

runOnQueueScope('sync', fn () => /* Your actions here */);

// or

runOnQueueScope('sync', function() {
    /* Your actions here */
});

// Other connection
runOnQueueScope('another-queue-connection', function() {
    /* Your actions here */
});

Principais design patterns usados no Laravel

Algumas das design patterns mais usadas no PHP e Laravel incluem:

  1. 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].
  2. 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].
  3. 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].
  4. 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].
  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.

Citations: [1] https://www.youtube.com/watch?v=wHrkL2SKjjk [2] https://laracasts.com/index.php/discuss/channels/laravel/applying-design-patterns-in-laravel [3] https://www.amazon.com/Design-Patterns-Laravel-Kelt-Dockins/dp/1484224507 [4] https://laravel-taiwan.github.io/php-the-right-way/pages/Design-Patterns.html [5] https://www.linkedin.com/posts/laravel-news_design-patterns-in-laravel-builder-pattern-activity-6995476220591124480-yjfe

Outros design patterns

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:

  1. Singleton Pattern: Garante que uma classe tenha apenas uma instância e fornece um ponto global de acesso a essa instância[4].
  2. Adapter Pattern: Permite que a interface de uma classe seja usada como interface esperada por outra classe[4].
  3. Decorator Pattern: Adiciona responsabilidades a objetos de forma dinâmica[4].
  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.

Citations: [1] https://www.grupomult.com.br/monitoramento-de-microsservicos-conheca-5-principios-basicos/ [2] https://www.youtube.com/watch?v=htneufBCTFU [3] https://www.redhat.com/pt-br/topics/microservices/what-are-microservices [4] https://pt.linkedin.com/pulse/tecnologia-16-saiba-quando-aplicar-design-patterns-em-projetos-de

Repository Pattern

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].

Citations: [1] https://java-design-patterns.com/patterns/repository/ [2] https://deviq.com/design-patterns/repository-pattern/ [3] https://dev.to/manukanne/a-python-implementation-of-the-unit-of-work-and-repository-design-pattern-using-sqlmodel-3mb5 [4] https://laracasts.com/index.php/discuss/channels/laravel/applying-design-patterns-in-laravel [5] https://www.cosmicpython.com/book/chapter_02_repository.html

<?php
namespace Modules\TiagoF2\CustomComponentsDirectives;
use Illuminate\Support\Facades\Blade;
class CustomComponentsDirectives
{
/**
* function customDirectives
*
* @return void
*/
public static function loadDirectives(): void
{
Blade::directive('config', function ($expression) {
return "<?php echo config({$expression}) ?>";
});
Blade::directive('env', function () {
return "<?php echo config('app.env') ?>";
});
Blade::directive('ifEnv', function ($expression) {
return "<?php if (fnmatch({$expression}, config('app.env'))) : ?>";
});
Blade::directive('endifEnv', function () {
return '<?php endif ?>;';
});
Blade::directive('ifEnvNot', function ($expression) {
return "<?php if (!fnmatch({$expression}, config('app.env'))) : ?>";
});
Blade::directive('endifEnvNot', function () {
return '<?php endif ?>';
});
Blade::directive('ifEnvNotIn', function ($expression) {
return "<?php if (!in_array(config('app.env'), {$expression})) : ?>";
});
Blade::directive('endifEnvNotIn', function () {
return '<?php endif ?>';
});
}
/**
* function placeInPHPBloc
*
* @param string $content
*
* > Demo:
* ```
* CustomDirectives::placeInPHPBloc('@php echo "algo"; @endphp')
*
* ```
* * output
* * ```<?php echo "algo"; ?>```
*
* @return string
*/
public static function placeInPHPBloc(string $content): string
{
return preg_replace_callback(
'/(?<!@)@php(.*?)@endphp/s',
fn ($matches) => "<?php{$matches[1]}?>",
$content
);
}
}
<?php
expect()->extend('toBeStatusCode', function (int $expected_status_code) {
return $this->toBe($expected_status_code);
});
function assertStatusCode($status_code, int $expected_status_code)
{
expect($status_code)->toBeStatusCode($expected_status_code);
}
$this->assertEquals($expected_status_code, $status_code); //Funciona - mais genérico - do PHPUnit
expect($status_code)->toBe($expected_status_code); //Funciona - mais genérico - do Pest
assertStatusCode($status_code, $expected_status_code); //Funciona - mais específico - Pest custom (não funciona com PHPUnit)
{
"preset": "psr12",
"rules": {
"simplified_null_return": false,
"braces": true,
"new_with_braces": {
"anonymous_class": true,
"named_class": true
}
},
"notPath": [
"path/to/excluded-file.php"
],
"notName": [
"*-my-file.php"
]
}

Pint

pint.json

{
    "preset": "laravel",
    "exclude": [
        "_dev_dir"
    ],
    "notName": [
        ".local*",
        ".ignore*",
        "*-ignore-*"
    ],
    "notPath": [
        "path/to/excluded-file.php"
    ]
}

Other ways

./vendor/bin/pint --config pint-file.json
./vendor/bin/pint --preset psr12
./vendor/bin/pint --preset laravel

php-cs-fixer.php

<?xml version="1.0"?>
<ruleset name="Laravel Standards">
<description>The Laravel Coding Standards</description>
<file>public</file>
<file>app</file>
<file>config</file>
<file>resources</file>
<file>routes</file>
<file>tests</file>
<exclude-pattern>*/database/*</exclude-pattern>
<exclude-pattern>*/cache/*</exclude-pattern>
<exclude-pattern>*/lang/*</exclude-pattern>
<exclude-pattern>*/*.js</exclude-pattern>
<exclude-pattern>*/*.css</exclude-pattern>
<exclude-pattern>*/*.xml</exclude-pattern>
<exclude-pattern>*/*.blade.php</exclude-pattern>
<exclude-pattern>*/autoload.php</exclude-pattern>
<exclude-pattern>*/storage/*</exclude-pattern>
<exclude-pattern>*/docs/*</exclude-pattern>
<exclude-pattern>*/vendor/*</exclude-pattern>
<exclude-pattern>*/migrations/*</exclude-pattern>
<exclude-pattern>./_ide_helper.php</exclude-pattern>
<exclude-pattern>./ignore-dir</exclude-pattern>
<exclude-pattern>./_dev_dir</exclude-pattern>
<!--
Print either the "full", "xml", "checkstyle", "csv"
"json", "junit", "emacs", "source", "summary", "diff"
"svnblame", "gitblame", "hgblame" or "notifysend" report,
or specify the path to a custom report class
(the "full" report is printed by default)
-->
<!-- <arg name="report" value="summary" /> -->
<!-- <arg name="report" value="gitblame" /> -->
<arg name="report" value="diff" />
<arg name="colors" />
<!-- <arg name="severity"/> -->
<arg value="p" />
<ini name="memory_limit" value="128M"/>
<rule ref="PSR12">
<exclude name="PSR12.Files.FileHeader.SpacingInsideBlock"/>
</rule>
<rule ref="PSR2">
<exclude name="PSR1.Methods.CamelCapsMethodName" />
<exclude name="PSR1.Files.SideEffects" />
<exclude name="PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace"/>
</rule>
<rule ref="Generic.PHP.LowerCaseConstant" />
<rule ref="Generic.Files.LineEndings" />
<rule ref="Squiz.PHP.GlobalKeyword" />
<rule ref="PSR2.Files.EndFileNewline" />
<rule ref="Generic.WhiteSpace.DisallowTabIndent" />
</ruleset>
{
"editor.defaultFormatter-bkp": "bmewburn.vscode-intelephense-client",
"editor.defaultFormatter": "mhillmann.php-ide",
"phpcs.standard-bkp": "PSR12",
"phpcs.standard": "/path/to/phpcs-laravel.xml"
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Client extends Model
{
protected $connection = 'prod_read_pgsql';
protected $fillable = [];
protected static function boot()
{
parent::boot();
static::deleting(function ($model) {
return false;
});
static::updating(function ($model) {
return false;
});
static::creating(function ($model) {
return false;
});
}
}

Lembrar de reiniciar os trabalhos (jobs queue) quando atualizar o código `php artisan queue:restart``

Processando um número especificado de empregos

Processamento de trabalhos por um determinado número de segundos

Tempo limite do trabalhador !!! Ler a nota (muito explicativa)

Dispatching closure like a job

<?php declare(strict_types=1);
function remapData(array $map_list, array $data, &$return_mapping_to)
{
$return_mapping_to = [];//Resetting values
foreach ($map_list as $key => $value)
{
$return_mapping_to[$value] = $data[$key] ?? null;
}
}
$customer_data = [
"id" => 44,
"phone" => "12341234",
"cell_phone" => null,
"plan_signed_at" => "2021-01-10",
"plan" => 8,
"agent_code" => "part#0123",
"name" => "bao2 busy",
"corporate_name" => "empresa bao2",
"first_plan_signed_at" => "2021-01-10",
"email" => "bao2@busy.com",
"cnpj" => "12345678901234",
"employees_quantity" => 5,
];
$map_keys = [
'id' => 'client_id',
'phone' => 'phone_1',
'cell_phone' => 'phone_2',
'plan_signed_at' => 'plan_date',
'plan' => 'plan_id',
'agent_code' => 'saller_code',
'name' => 'name',
'corporate_name' => 'corporate_name',
'first_plan_signed_at' => 'first_plan_signed_at',
'email' => 'email',
'cnpj' => 'cnpj',
'employees_quantity' => 'employees_quantity',
];
remapData($map_keys, $customer_data, $onboarding_data);
$expected = [
"client_id" => 44,
"phone_1" => "12341234",
"phone_2" => null,
"plan_date" => "2021-01-10",
"plan_id" => 8,
"saller_code" => "part#0123",
"name" => "bao2 busy",
"corporate_name" => "empresa bao2",
"first_plan_signed_at" => "2021-01-10",
"email" => "bao2@busy.com",
"cnpj" => "12345678901234",
"employees_quantity" => 5,
];
<?php
/*-------- START LARAVEL OUTSIDE ---------*/
/*
To use Laravel core without then
If you whant to use core by CLI without artisan
*/
require __DIR__ . '/../../vendor/autoload.php';//Full path to file maybe need to change
$app = require_once __DIR__ . '/../../bootstrap/app.php';//Full path to file maybe need to change
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
<?php
require_once __DIR__ . '/core.php';
dd([__FILE__ . ':' . __LINE__]);
<?php
require_once __DIR__ . '/core.php';
use Illuminate\Support\Facades\Artisan;
// https://github.com/kitloong/laravel-migrations-generator
$tables = [
'password_resets',
'failed_jobs',
'hd_areas',
'hd_imagens',
'hd_atividades_area',
'hd_homologacoes',
'hd_tipo_movimentacoes',
'hd_problemas',
'hd_unidades',
'hd_atendimentos',
'hd_tipo_problemas',
'hd_usuarios',
'hd_areas_usuarios',
'hd_roles',
'hd_usuario_roles',
'hd_anexos',
'permissions',
'model_has_permissions',
'hd_chamados',
'roles',
'model_has_roles',
'role_has_permissions',
'jobs',
'hd_chamado_logs',
'hd_massive_imports',
];
$tableMigrationDates = [];
foreach ($tables as $index => $table) {
if (!$table) {
continue;
}
if ($index >= 8) {
continue;
}
usleep(200 * 1000);
echo "\nTable: {$table}\n";
$date = date('Y-m-d H:i:s', time() + (($index ?: 1) * 2));
$formatedDate = date('Y_m_d_His', strtotime($date));
$tableFileName = "{$formatedDate}_create_{$table}_table.php";
$fkFilename = $tableFileName;
Artisan::call(
'migrate:generate ' . implode(
' ',
[
'--tables=' . $table,
// '-A', // aguardando PR https://github.com/kitloong/laravel-migrations-generator/pull/105
'-q',
'-n',
'--default-index-names',
'--skip-views',
'--default-fk-names',
"--date='{$date}'",
"--table-filename={$tableFileName}",
"--fk-filename={$fkFilename}",
'--squash',
]
)
);
}
<?php
require_once __DIR__ . '/core.php';
//Put here all the models you want to move
$modelsToMove = "/path/to/all-the-models-you-want-to-move.txt";
$files = explode("\n", file_get_contents($modelsToMove));
foreach ($files as $file) {
if (!$file) {
continue;
}
$newFileName = str_replace('app/', 'app/Models/', $file);
$oldFilePath = base_path($file);
$newFilePath = base_path($newFileName);
if (file_exists($oldFilePath)) {
dump(sprintf("Moving '%s' to '%s'", $file, $newFileName));
rename($oldFilePath, $newFilePath);
}
$sourceFile = $newFilePath;
$targetFile = $newFilePath;
$targetText = "namespace App;";
$replaceToText = "namespace App\Models;";
dump(sprintf("Replacing '%s' to '%s'", $targetText, $replaceToText));
$contents = file_get_contents($sourceFile);
$contents = str_replace($targetText, $replaceToText, $contents);
file_put_contents($targetFile, $contents);
}

First runs:

php scripts/move-models-to-app-Models.php

After runs:

php replace-old-namespaces-text-on-files.php
<?php
require_once __DIR__ . '/core.php';
$classesToReplace = Cache::remember(
'classesToReplace' . date('YmH'),
(60 * 60) /*secs*/,
function () {
$files = "
app/Pagamento.php
app/BasicLog.php
app/ContractTemplate.php
app/Setor.php
app/PagamentosPessoas.php
app/Combustivel.php
app/Doador.php
app/Fornecedor.php
app/Servico.php
app/Imovel.php
app/User.php
app/Pessoa.php
app/Veiculo.php
app/Candidato.php
app/File.php
";
foreach (explode("\n", $files) as $line) {
$line = trim($line);
if (!$line) {
continue;
}
$oldOriginal = $line;
$oldClassName = str_replace([
'app/', '.php',
], [
'App\\', '',
], $oldOriginal);
$classes[$oldClassName] = str_replace(
['App\\'],
['App\\Models\\'],
$oldClassName
);
}
return $classes ?? [];
}
);
function contains(string $content, string $searchBy, $target = null)
{
if (strpos($content, $searchBy) !== false) {
return true;
}
return null;
}
function listFolderFiles($dir)
{
$files = array_diff(scandir($dir), ['.', '..']);
// prevent empty ordered elements
if (count($files) < 1) {
return;
}
$all = "";
foreach ($files as $ff) {
$all .= "\n";
if (is_dir("{$dir}/{$ff}")) {
$all .= listFolderFiles("{$dir}/{$ff}");
continue;
}
$all .= "{$dir}/{$ff}";
$all = str_replace("\n\n", "\n", $all);
}
return $all;
}
function listOfFiles(string $which)
{
$listOfFilesCacheKey = md5("listOfFiles-on-{$which}");
$listOfFiles = Cache::remember(
$listOfFilesCacheKey,
(60 * 60) /*secs*/,
function () use ($which) {
foreach (explode("\n", listFolderFiles($which)) as $line) {
$line = trim($line);
if (!$line || !file_exists($line)) {
continue;
}
$tempListOfFiles[] = $line;
}
return $tempListOfFiles ?? [];
}
);
if (!$listOfFiles) {
Cache::forget($listOfFilesCacheKey);
}
return $listOfFiles ?? [];
}
function replaceAll(string $replaceThis, string $byThis, string $onThisFile)
{
$targetFile = $onThisFile;
$targetText = $replaceThis;
$replaceToText = $byThis;
dump(sprintf("Replacing '%s' to '%s'", $targetText, $replaceToText));
$newContent = str_replace(
$targetText,
$replaceToText,
file_get_contents($targetFile)
);
file_put_contents($targetFile, $newContent);
}
foreach (
[
'app',
'config',
'database',
] as $dir
) {
$which = base_path($dir);
foreach ($classesToReplace as $oldClassName => $newClassName) {
// $searchBy = 'use App\BasicLog;';
$searchBy = $oldClassName;
echo PHP_EOL;
dump(sprintf("Searching by '%s'", $searchBy));
foreach (listOfFiles($which) as $file) {
if (!file_exists($file)) {
continue;
}
if (contains(file_get_contents($file), $searchBy, $file)) {
dump(sprintf("Found '%s' on '%s'", $searchBy, $file));
replaceAll($oldClassName, $newClassName, $file);
echo PHP_EOL;
}
}
}
}
    // If you factory is out of standard, you can set an specifc
    // On your model, create a static method named newFactory

    protected static function newFactory()
    {
        return \Database\Factories\MyModelFactory::new();
    }

    //On your factory, add this
    protected $model = \App\Models\MyModel::class;

Relationship between factories

https://laravel.com/docs/9.x/eloquent-factories#defining-model-factories

public function definition()
{
    return [
        'user_id' => User::factory(),
    ];
}

Fake data on relationship

https://laravel.com/docs/9.x/eloquent-factories#defining-relationships-within-factories

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::factory(),
        'user_type' => function (array $attributes) {
            return User::find($attributes['user_id'])->type;
        },
        'title' => $this->faker->title(),
        'content' => $this->faker->paragraph(),
    ];
}

More advanced

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'user_type' => 'Admin',
        'user_permissions' => 'abc:def:ghi',
        'user_id' => function (array $attributes) {
            return User::factory([
                'user_type' => $attributes['user_type'],
                'user_permissions' => $attributes['user_permissions'],
            ]);
        },
    ];
}

Faker

Monthly Downloads Continuous Integration codecov SensioLabsInsight

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.

Faker requires PHP >= 5.3.3.

Faker is archived. Read the reasons behind this decision here: https://marmelab.com/blog/2020/10/21/sunsetting-faker.html

Table of Contents

Installation

composer require fzaninotto/faker

Basic Usage

Autoloading

Faker supports both PSR-0 as PSR-4 autoloaders.

<?php
# When installed via composer
require_once 'vendor/autoload.php';

You can also load Fakers shipped PSR-0 autoloader

<?php
# Load Fakers own autoloader
require_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 properties
echo $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).

<?php
for ($i = 0; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Adaline Reichel
  // Dr. Santa Prosacco DVM
  // Noemy Vandervort V
  // Lexi O'Conner
  // Gracie Weber
  // Roscoe Johns
  // Emmett Lebsack
  // Keegan Thiel
  // Wellington Koelpin II
  // Ms. Karley Kiehn V

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.

Faker\Provider\Base

    randomDigit             // 7
    randomDigitNot(5)       // 0, 1, 2, 3, 4, 6, 7, 8, or 9
    randomDigitNotNull      // 5
    randomNumber($nbDigits = NULL, $strict = false) // 79907610
    randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
    numberBetween($min = 1000, $max = 9000) // 8567
    randomLetter            // 'b'
    // returns randomly ordered subsequence of a provided array
    randomElements($array = array ('a','b','c'), $count = 1) // array('c')
    randomElement($array = array ('a','b','c')) // 'b'
    shuffle('hello, world') // 'rlo,h eoldlw'
    shuffle(array(1, 2, 3)) // array(2, 1, 3)
    numerify('Hello ###') // 'Hello 609'
    lexify('Hello ???') // 'Hello wgt'
    bothify('Hello ##??') // 'Hello 42jz'
    asciify('Hello ***') // 'Hello R6+'
    regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // sm0@y8k96a.ej

Faker\Provider\Lorem

    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.'

Faker\Provider\en_US\Person

    title($gender = null|'male'|'female')     // 'Ms.'
    titleMale                                 // 'Mr.'
    titleFemale                               // 'Ms.'
    suffix                                    // 'Jr.'
    name($gender = null|'male'|'female')      // 'Dr. Zane Stroman'
    firstName($gender = null|'male'|'female') // 'Maynard'
    firstNameMale                             // 'Maynard'
    firstNameFemale                           // 'Rachel'
    lastName                                  // 'Zulauf'

Faker\Provider\en_US\Address

    cityPrefix                          // 'Lake'
    secondaryAddress                    // 'Suite 961'
    state                               // 'NewMexico'
    stateAbbr                           // 'OH'
    citySuffix                          // 'borough'
    streetSuffix                        // 'Keys'
    buildingNumber                      // '484'
    city                                // 'West Judge'
    streetName                          // 'Keegan Trail'
    streetAddress                       // '439 Karley Loaf Suite 897'
    postcode                            // '17916'
    address                             // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473'
    country                             // 'Falkland Islands (Malvinas)'
    latitude($min = -90, $max = 90)     // 77.147489
    longitude($min = -180, $max = 180)  // 86.211205

Faker\Provider\en_US\PhoneNumber

    phoneNumber             // '201-886-0269 x3767'
    tollFreePhoneNumber     // '(888) 937-7238'
    e164PhoneNumber     // '+27113456789'

Faker\Provider\en_US\Company

    catchPhrase             // 'Monitored regional contingency'
    bs                      // 'e-enable robust architectures'
    company                 // 'Bogan-Treutel'
    companySuffix           // 'and Sons'
    jobTitle                // 'Cashier'

Faker\Provider\en_US\Text

    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."

Faker\Provider\DateTime

    unixTime($max = 'now')                // 58781813
    dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC')
    dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris')
    iso8601($max = 'now')                 // '1978-12-09T10:10:29+0000'
    date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
    time($format = 'H:i:s', $max = 'now') // '20:49:42'
    dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos')
    dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok')
    dateTimeThisCentury($max = 'now', $timezone = null)     // DateTime('1915-05-30 19:28:21', 'UTC')
    dateTimeThisDecade($max = 'now', $timezone = null)      // DateTime('2007-05-29 22:30:48', 'Europe/Paris')
    dateTimeThisYear($max = 'now', $timezone = null)        // DateTime('2011-02-27 20:52:14', 'Africa/Lagos')
    dateTimeThisMonth($max = 'now', $timezone = null)       // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok')
    amPm($max = 'now')                    // 'pm'
    dayOfMonth($max = 'now')              // '04'
    dayOfWeek($max = 'now')               // 'Friday'
    month($max = 'now')                   // '06'
    monthName($max = 'now')               // 'January'
    year($max = 'now')                    // '1993'
    century                               // 'VI'
    timezone                              // 'Europe/Paris'

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).

Faker\Provider\Internet

    email                   // 'tkshlerin@collins.com'
    safeEmail               // 'king.alford@example.org'
    freeEmail               // 'bradley72@gmail.com'
    companyEmail            // 'russel.durward@mcdermott.org'
    freeEmailDomain         // 'yahoo.com'
    safeEmailDomain         // 'example.org'
    userName                // 'wade55'
    password                // 'k&|X+a45*2['
    domainName              // 'wolffdeckow.net'
    domainWord              // 'feeney'
    tld                     // 'biz'
    url                     // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html'
    slug                    // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum'
    ipv4                    // '109.133.32.252'
    localIpv4               // '10.242.58.8'
    ipv6                    // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c'
    macAddress              // '43:85:B7:08:10:CA'

Faker\Provider\UserAgent

    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'

Faker\Provider\Color

    hexcolor               // '#fa3cc2'
    rgbcolor               // '0,255,122'
    rgbColorAsArray        // array(0,255,122)
    rgbCssColor            // 'rgb(0,255,122)'
    safeColorName          // 'fuchsia'
    colorName              // 'Gainsbor'
    hslColor               // '340,50,20'
    hslColorAsArray        // array(340,50,20)

Faker\Provider\File

    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'

Faker\Provider\Image

    // Image generation provided by LoremPixel (http://lorempixel.com/)
    imageUrl($width = 640, $height = 480) // 'http://lorempixel.com/640/480/'
    imageUrl($width, $height, 'cats')     // 'http://lorempixel.com/800/600/cats/'
    imageUrl($width, $height, 'cats', true, 'Faker') // 'http://lorempixel.com/800/400/cats/Faker'
    imageUrl($width, $height, 'cats', true, 'Faker', true) // 'http://lorempixel.com/gray/800/400/cats/Faker/' Monochrome image
    image($dir = '/tmp', $width = 640, $height = 480) // '/tmp/13b73edae8443990be1aa8f1a483bc27.jpg'
    image($dir, $width, $height, 'cats')  // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat!
    image($dir, $width, $height, 'cats', false) // '13b73edae8443990be1aa8f1a483bc27.jpg' it's a filename without path
    image($dir, $width, $height, 'cats', true, false) // it's a no randomize images (default: `true`)
    image($dir, $width, $height, 'cats', true, true, 'Faker') // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat with 'Faker' text. Default, `null`.

Faker\Provider\Uuid

    uuid // '7e57d004-2b97-0e7a-b45f-5387367791cd'

Faker\Provider\Barcode

    ean13          // '4006381333931'
    ean8           // '73513537'
    isbn13         // '9790404436093'
    isbn10         // '4881416324'

Faker\Provider\Miscellaneous

    boolean // false
    boolean($chanceOfGettingTrue = 50) // true
    md5           // 'de99a620c50f2990e87144735cd357e7'
    sha1          // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c'
    sha256        // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5'
    locale        // en_UK
    countryCode   // UK
    languageCode  // en
    currencyCode  // EUR
    emoji         // 😁

Faker\Provider\Biased

    // 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 faker
for ($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:

<?php
$generator = \Faker\Factory::create();
$populator = new \Faker\ORM\Propel\Populator($generator);
$populator->addEntity('Author', 5);
$populator->addEntity('Book', 10);
$insertedPKs = $populator->execute();

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():

<?php
$populator->addEntity('Book', 5, array(
  'ISBN' => function() use ($generator) { return $generator->ean13(); }
));

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:

<?php
$populator->addEntity('Book', 5, array(
  'CreatedAt' => null,
  'UpdatedAt' => null,
));

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:

<?php
print_r($insertedPKs);
// array(
//   'Author' => (34, 35, 36, 37, 38),
//   'Book'   => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475)
// )

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:

<?php
$populator->addEntity('Book', 5, array(), array(
  function($book) { $book->publish(); },
));

Seeding the Generator

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.

<?php
$faker = Faker\Factory::create();
$faker->seed(1234);

echo $faker->name; // 'Jess Mraz I';

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:

<?php
// bad
$faker->realText(rand(10,20));
// good
$faker->realText($faker->numberBetween(10,20));

Faker Internals: Understanding Providers

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:

<?php
$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Person($faker));
$faker->addProvider(new Faker\Provider\en_US\Address($faker));
$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker));
$faker->addProvider(new Faker\Provider\en_US\Company($faker));
$faker->addProvider(new Faker\Provider\Lorem($faker));
$faker->addProvider(new Faker\Provider\Internet($faker));

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:

<?php

namespace Faker\Provider;

class Book extends \Faker\Provider\Base
{
  public function title($nbWords = 5)
  {
    $sentence = $this->generator->sentence($nbWords);
    return substr($sentence, 0, strlen($sentence) - 1);
  }

  public function ISBN()
  {
    return $this->generator->ean13();
  }
}

To register this provider, just add a new instance of \Faker\Provider\Book to an existing generator:

<?php
$faker->addProvider(new \Faker\Provider\Book($faker));

Now you can use the two new formatters like any other Faker formatter:

<?php
$book = new Book();
$book->setTitle($faker->title);
$book->setISBN($faker->ISBN);
$book->setSummary($faker->text);
$book->setPrice($faker->randomNumber(2));

Tip: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator.

Real Life Usage

The following script generates a valid XML document:

<?php
require_once '/path/to/Faker/src/autoload.php';
$faker = Faker\Factory::create();
?>
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<?php for ($i = 0; $i < 10; $i++): ?>
  <contact firstName="<?php echo $faker->firstName ?>" lastName="<?php echo $faker->lastName ?>" email="<?php echo $faker->email ?>">
    <phone number="<?php echo $faker->phoneNumber ?>"/>
<?php if ($faker->boolean(25)): ?>
    <birth date="<?php echo $faker->dateTimeThisCentury->format('Y-m-d') ?>" place="<?php echo $faker->city ?>"/>
<?php endif; ?>
    <address>
      <street><?php echo $faker->streetAddress ?></street>
      <city><?php echo $faker->city ?></city>
      <postcode><?php echo $faker->postcode ?></postcode>
      <state><?php echo $faker->state ?></state>
    </address>
    <company name="<?php echo $faker->company ?>" catchPhrase="<?php echo $faker->catchPhrase ?>">
<?php if ($faker->boolean(33)): ?>
      <offer><?php echo $faker->bs ?></offer>
<?php endif; ?>
<?php if ($faker->boolean(33)): ?>
      <director name="<?php echo $faker->name ?>" />
<?php endif; ?>
    </company>
<?php if ($faker->boolean(15)): ?>
    <details>
<![CDATA[
<?php echo $faker->text(400) ?>
]]>
    </details>
<?php endif; ?>
  </contact>
<?php endfor; ?>
</contacts>

Running this script produces a document looking like:

<?xml version="1.0" encoding="UTF-8"?>
<contacts>
  <contact firstName="Ona" lastName="Bednar" email="schamberger.frank@wuckert.com">
    <phone number="1-265-479-1196x714"/>
    <address>
      <street>182 Harrison Cove</street>
      <city>North Lloyd</city>
      <postcode>45577</postcode>
      <state>Alabama</state>
    </address>
    <company name="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>
  <contact firstName="Aurelie" lastName="Paucek" email="alfonzo55@durgan.com">
    <phone number="863.712.1363x9425"/>
    <address>
      <street>90111 Hegmann Inlet</street>
      <city>South Geovanymouth</city>
      <postcode>69961-9311</postcode>
      <state>Colorado</state>
    </address>
    <company name="Krajcik-Grimes" catchPhrase="Switchable cohesive instructionset">
    </company>
  </contact>
  <contact firstName="Clifton" lastName="Kshlerin" email="kianna.wiegand@framiwyman.info">
    <phone number="692-194-4746"/>
    <address>
      <street>9791 Nona Corner</street>
      <city>Harberhaven</city>
      <postcode>74062-8191</postcode>
      <state>RhodeIsland</state>
    </address>
    <company name="Rosenbaum-Aufderhar" catchPhrase="Realigned asynchronous encryption">
    </company>
  </contact>
  <contact firstName="Alexandre" lastName="Orn" email="thelma37@erdmancorwin.biz">
    <phone number="189.655.8677x027"/>
    <address>
      <street>11161 Schultz Via</street>
      <city>Feilstad</city>
      <postcode>98019</postcode>
      <state>NewJersey</state>
    </address>
    <company name="O'Hara-Prosacco" catchPhrase="Re-engineered solution-oriented algorithm">
      <director name="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>
  <contact firstName="Katelynn" lastName="Kohler" email="reinger.trudie@stiedemannjakubowski.com">
    <phone number="(665)713-1657"/>
    <address>
      <street>6106 Nader Village Suite 753</street>
      <city>McLaughlinstad</city>
      <postcode>43189-8621</postcode>
      <state>Missouri</state>
    </address>
    <company name="Herman-Tremblay" catchPhrase="Object-based explicit service-desk">
      <offer>expedite viral synergies</offer>
      <director name="Arden Deckow" />
    </company>
  </contact>
  <contact firstName="Blanca" lastName="Stark" email="tad27@feest.net">
    <phone number="168.719.4692x87177"/>
    <address>
      <street>7546 Kuvalis Plaza</street>
      <city>South Wilfrid</city>
      <postcode>77069</postcode>
      <state>Georgia</state>
    </address>
    <company name="Upton, Braun and Rowe" catchPhrase="Visionary leadingedge pricingstructure">
    </company>
  </contact>
  <contact firstName="Rene" lastName="Spencer" email="anibal28@armstrong.info">
    <phone number="715.222.0095x175"/>
    <birth date="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>
    <company name="Wiza Inc" catchPhrase="Persevering reciprocal approach">
      <offer>orchestrate dynamic networks</offer>
      <director name="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>
  <contact firstName="Alessandro" lastName="Hagenes" email="tbreitenberg@oharagorczany.com">
    <phone number="1-284-958-6768"/>
    <address>
      <street>1251 Koelpin Mission</street>
      <city>North Revastad</city>
      <postcode>81620</postcode>
      <state>Maryland</state>
    </address>
    <company name="Stiedemann-Bruen" catchPhrase="Re-engineered 24/7 success">
    </company>
  </contact>
  <contact firstName="Novella" lastName="Rutherford" email="claud65@bogisich.biz">
    <phone number="(091)825-7971"/>
    <address>
      <street>6396 Langworth Hills Apt. 446</street>
      <city>New Carlos</city>
      <postcode>89399-0268</postcode>
      <state>Wyoming</state>
    </address>
    <company name="Stroman-Legros" catchPhrase="Expanded 4thgeneration moratorium">
      <director name="Earlene Bayer" />
    </company>
  </contact>
  <contact firstName="Andreane" lastName="Mann" email="meggie17@ornbaumbach.com">
    <phone number="941-659-9982x5689"/>
    <birth date="1934-02-21" place="Stantonborough"/>
    <address>
      <street>2246 Kreiger Station Apt. 291</street>
      <city>Kaydenmouth</city>
      <postcode>11397-1072</postcode>
      <state>Wyoming</state>
    </address>
    <company name="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

<?php

echo $faker->idNumber;      // ID number
echo $faker->nationalIdNumber // Citizen ID number
echo $faker->foreignerIdNumber // Foreigner ID number
echo $faker->companyIdNumber // Company ID number

Faker\Provider\ar_SA\Payment

<?php

echo $faker->bankAccountNumber // "SA0218IBYZVZJSEC8536V4XC"

Faker\Provider\at_AT\Payment

<?php

echo $faker->vat;           // "AT U12345678" - Austrian Value Added Tax number
echo $faker->vat(false);    // "ATU12345678" - unspaced Austrian Value Added Tax number

Faker\Provider\bg_BG\Payment

<?php

echo $faker->vat;           // "BG 0123456789" - Bulgarian Value Added Tax number
echo $faker->vat(false);    // "BG0123456789" - unspaced Bulgarian Value Added Tax number

Faker\Provider\cs_CZ\Address

<?php

echo $faker->region; // "Liberecký kraj"

Faker\Provider\cs_CZ\Company

<?php

// Generates a valid IČO
echo $faker->ico; // "69663963"

Faker\Provider\cs_CZ\DateTime

<?php

echo $faker->monthNameGenitive; // "prosince"
echo $faker->formattedDate; // "12. listopadu 2015"

Faker\Provider\cs_CZ\Person

<?php

echo $faker->birthNumber; // "7304243452"

Faker\Provider\da_DK\Person

<?php

// Generates a random CPR number
echo $faker->cpr; // "051280-2387"

Faker\Provider\da_DK\Address

<?php

// Generates a random 'kommune' name
echo $faker->kommune; // "Frederiksberg"

// Generates a random region name
echo $faker->region; // "Region Sjælland"

Faker\Provider\da_DK\Company

<?php

// Generates a random CVR number
echo $faker->cvr; // "32458723"

// Generates a random P number
echo $faker->p; // "5398237590"

Faker\Provider\de_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97" OR
echo $faker->ahv13; // "756.1234.5678.97"

Faker\Provider\de_DE\Payment

<?php

echo $faker->bankAccountNumber; // "DE41849025553661169313"
echo $faker->bank; // "Volksbank Stuttgart"

Faker\Provider\en_HK\Address

<?php

// Generates a fake town name based on the words commonly found in Hong Kong
echo $faker->town; // "Yuen Long"

// Generates a fake village name based on the words commonly found in Hong Kong
echo $faker->village; // "O Tau"

// Generates a fake estate name based on the words commonly found in Hong Kong
echo $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 name
echo $faker->region; // 'Katsina'

Faker\Provider\en_NG\Person

<?php

// Generates a random person name
echo $faker->name; // 'Oluwunmi Mayowa'

Faker\Provider\en_NZ\Phone

<?php

// Generates a cell (mobile) phone number
echo $faker->mobileNumber; // "021 123 4567"

// Generates a toll free number
echo $faker->tollFreeNumber; // "0800 123 456"

// Area Code
echo $faker->areaCode; // "03"

Faker\Provider\en_US\Company

<?php

// Generate a random Employer Identification Number
echo $faker->ein; // '12-3456789'

Faker\Provider\en_US\Payment

<?php

echo $faker->bankAccountNumber;  // '51915734310'
echo $faker->bankRoutingNumber;  // '212240302'

Faker\Provider\en_US\Person

<?php

// Generates a random Social Security Number
echo $faker->ssn; // '123-45-6789'

Faker\Provider\en_ZA\Company

<?php

// Generates a random company registration number
echo $faker->companyNumber; // 1999/789634/01

Faker\Provider\en_ZA\Person

<?php

// Generates a random national identification number
echo $faker->idNumber; // 6606192211041

// Generates a random valid licence code
echo $faker->licenceCode; // EB

Faker\Provider\en_ZA\PhoneNumber

<?php

// Generates a special rate toll free phone number
echo $faker->tollFreeNumber; // 0800 555 5555

// Generates a mobile phone number
echo $faker->mobileNumber; // 082 123 5555

Faker\Provider\es_ES\Person

<?php

// Generates a Documento Nacional de Identidad (DNI) number
echo $faker->dni; // '77446565E'

// Generates a random valid licence code
echo $faker->licenceCode; // B

Faker\Provider\es_ES\Payment

<?php
// Generates a Código de identificación Fiscal (CIF) number
echo $faker->vat;           // "A35864370"

Faker\Provider\es_ES\PhoneNumber

<?php

// Generates a special rate toll free phone number
echo $faker->tollFreeNumber; // 900 123 456

// Generates a mobile phone number
echo $faker->mobileNumber; // +34 612 12 24

Faker\Provider\es_PE\Person

<?php

// Generates a Peruvian Documento Nacional de Identidad (DNI) number
echo $faker->dni; // '83367512'

Faker\Provider\fa_IR\Person

<?php

// Generates a valid nationalCode
echo $faker->nationalCode; // "0078475759"

Faker\Provider\fa_IR\Address

<?php

// Generates a random building name
echo $faker->building; // "ساختمان آفتاب"

// Returns a random city name
echo $faker->city // "استان زنجان"

Faker\Provider\fa_IR\Company

<?php

// Generates a random contract type
echo $faker->contract; // "رسمی"

Faker\Provider\fi_FI\Payment

<?php

// Generates a random bank account number
echo $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

<?php

echo $faker->vat;           // "BE 0123456789" - Belgian Value Added Tax number
echo $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 separator
echo $faker->nationalId; // 'V11223344'

Faker\Provider\es_VE\Company

<?php

// Generates a R.I.F. number, you can pass one argument to add separators
echo $faker->taxpayerIdentificationNumber; // 'J1234567891'

Faker\Provider\fr_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97"

Faker\Provider\fr_FR\Address

<?php

// Generates a random department name
echo $faker->departmentName; // "Haut-Rhin"

// Generates a random department number
echo $faker->departmentNumber; // "2B"

// Generates a random department info (department number => department name)
$faker->department; // array('18' => 'Cher');

// Generates a random region
echo $faker->region; // "Saint-Pierre-et-Miquelon"

// Generates a random appartement,stair
echo $faker->secondaryAddress; // "Bat. 961"

Faker\Provider\fr_FR\Company

<?php

// Generates a random SIREN number
echo $faker->siren; // 082 250 104

// Generates a random SIRET number
echo $faker->siret; // 347 355 708 00224

Faker\Provider\fr_FR\Payment

<?php

// Generates a random VAT
echo $faker->vat; // FR 12 123 456 789

Faker\Provider\fr_FR\Person

<?php

// Generates a random NIR / Sécurité Sociale number
echo $faker->nir; // 1 88 07 35 127 571 - 19

Faker\Provider\fr_FR\PhoneNumber

<?php

// Generates phone numbers
echo $faker->phoneNumber; // +33 (0)1 67 97 01 31
echo $faker->mobileNumber; // +33 6 21 12 72 84
echo $faker->serviceNumber // 08 98 04 84 46

Faker\Provider\he_IL\Payment

<?php

echo $faker->bankAccountNumber // "IL392237392219429527697"

Faker\Provider\hr_HR\Payment

<?php

echo $faker->bankAccountNumber // "HR3789114847226078672"

Faker\Provider\hu_HU\Payment

<?php

// Generates a random bank account number
echo $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 used
echo $faker->nik(); // "8522246001570940"

Faker\Provider\it_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97"

Faker\Provider\it_IT\Company

<?php

// Generates a random Vat Id
echo $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' name
echo $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 number
echo $faker->bankAccountNumber; // "GE33ZV9773853617253389"

Faker\Provider\kk_KZ\Company

<?php

// Generates an business identification number
echo $faker->businessIdentificationNumber; // "150140000019"

Faker\Provider\kk_KZ\Payment

<?php

// Generates a random bank name
echo $faker->bank; // "Қазкоммерцбанк"

// Generates a random bank account number
echo $faker->bankAccountNumber; // "KZ1076321LO4H6X41I37"

Faker\Provider\kk_KZ\Person

<?php

// Generates an individual identification number
echo $faker->individualIdentificationNumber; // "780322300455"

// Generates an individual identification number based on his/her birth date
echo $faker->individualIdentificationNumber(new \DateTime('1999-03-01')); // "990301300455"

Faker\Provider\ko_KR\Address

<?php

// Generates a metropolitan city
echo $faker->metropolitanCity; // "서울특별시"

// Generates a borough
echo $faker->borough; // "강남구"

Faker\Provider\ko_KR\PhoneNumber

<?php

// Generates a local area phone numer
echo $faker->localAreaPhoneNumber; // "02-1234-4567"

// Generates a cell phone number
echo $faker->cellPhoneNumber; // "010-9876-5432"

Faker\Provider\lt_LT\Payment

<?php

echo $faker->bankAccountNumber // "LT300848876740317118"

Faker\Provider\lv_LV\Person

<?php

// Generates a random personal identity card number
echo $faker->personalIdentityNumber; // "140190-12301"

Faker\Provider\ms_MY\Address

<?php

// Generates a random Malaysian township
echo $faker->township; // "Taman Bahagia"

// Generates a random Malaysian town address with matching postcode and state
echo $faker->townState; // "55100 Bukit Bintang, Kuala Lumpur"

Faker\Provider\ms_MY\Miscellaneous

<?php

// Generates a random vehicle license plate number
echo $faker->jpjNumberPlate; // "WPL 5169"

Faker\Provider\ms_MY\Payment

<?php

// Generates a random Malaysian bank
echo $faker->bank; // "Maybank"

// Generates a random Malaysian bank account number (10-16 digits)
echo $faker->bankAccountNumber; // "1234567890123456"

// Generates a random Malaysian insurance company
echo $faker->insurance; // "AIA Malaysia"

// Generates a random Malaysian bank SWIFT Code
echo $faker->swiftCode; // "MBBEMYKLXXX"

Faker\Provider\ms_MY\Person

<?php

// Generates a random personal identity card (myKad) number
echo $faker->myKadNumber($gender = null|'male'|'female', $hyphen = null|true|false); // "710703471796"

Faker\Provider\ms_MY\PhoneNumber

<?php

// Generates a random Malaysian mobile number
echo $faker->mobileNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "+6012-705 3767"

// Generates a random Malaysian landline number
echo $faker->fixedLineNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "03-7112 0455"

// Generates a random Malaysian voip number
echo $faker->voipNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "015-458 7099"

Faker\Provider\ne_NP\Address

<?php

//Generates a Nepali district name
echo $faker->district;

//Generates a Nepali city name
echo $faker->cityName;

Faker\Provider\nl_BE\Payment

<?php

echo $faker->vat;           // "BE 0123456789" - Belgian Value Added Tax number
echo $faker->vat(false);    // "BE0123456789" - unspaced Belgian Value Added Tax number

Faker\Provider\nl_BE\Person

<?php

echo $faker->rrn();         // "83051711784" - Belgian Rijksregisternummer
echo $faker->rrn('female'); // "50032089858" - Belgian Rijksregisternummer for a female

Faker\Provider\nl_NL\Company

<?php

echo $faker->jobTitle; // "Houtbewerker"
echo $faker->vat; // "NL123456789B01" - Dutch Value Added Tax number
echo $faker->btw; // "NL123456789B01" - Dutch Value Added Tax number (alias)

Faker\Provider\nl_NL\Person

<?php

echo $faker->idNumber; // "111222333" - Dutch Personal identification number (BSN)

Faker\Provider\nb_NO\MobileNumber

<?php

// Generates a random Norwegian mobile phone number
echo $faker->mobileNumber; // "+4799988777"
echo $faker->mobileNumber; // "999 88 777"
echo $faker->mobileNumber; // "99988777"

Faker\Provider\nb_NO\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "NO3246764709816"

Faker\Provider\pl_PL\Person

<?php

// Generates a random PESEL number
echo $faker->pesel; // "40061451555"
// Generates a random personal identity card number
echo $faker->personalIdentityNumber; // "AKX383360"
// Generates a random taxpayer identification number (NIP)
echo $faker->taxpayerIdentificationNumber; // '8211575109'

Faker\Provider\pl_PL\Company

<?php

// Generates a random REGON number
echo $faker->regon; // "714676680"
// Generates a random local REGON number
echo $faker->regonLocal; // "15346111382836"

Faker\Provider\pl_PL\Payment

<?php

// Generates a random bank name
echo $faker->bank; // "Narodowy Bank Polski"
// Generates a random bank account number
echo $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 name
echo $faker->region; // 'Nordeste'

// Generates a random region abbreviation
echo $faker->regionAbbr; // 'NE'

Faker\Provider\pt_BR\PhoneNumber

<?php

echo $faker->areaCode;  // 21
echo $faker->cellphone; // 9432-5656
echo $faker->landline;  // 2654-3445
echo $faker->phone;     // random landline, 8-digit or 9-digit cellphone number

// Using the phone functions with a false argument returns unformatted numbers
echo $faker->cellphone(false); // 74336667

// cellphone() has a special second argument to add the 9th digit. Ignored if generated a Radio number
echo $faker->cellphone(true, true); // 98983-3945 or 7343-1290

// Using the "Number" suffix adds area code to the phone
echo $faker->cellphoneNumber;       // (11) 98309-2935
echo $faker->landlineNumber(false); // 3522835934
echo $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 suffix
echo $faker->name; // 'Sr. Luis Adriano Sepúlveda Filho'

// Valid document generators have a boolean argument to remove formatting
echo $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 CNPJ
echo $faker->cnpj;        // '23.663.478/0001-24'
echo $faker->cnpj(false); // '23663478000124'

Faker\Provider\ro_MD\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "MD83BQW1CKMUW34HBESDP3A8"

Faker\Provider\ro_RO\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "RO55WRJE3OE8X3YQI7J26U1E"

Faker\Provider\ro_RO\Person

<?php

// Generates a random male name prefix/title
echo $faker->prefixMale; // "ing."
// Generates a random female name prefix/title
echo $faker->prefixFemale; // "d-na."
// Generates a random male first name
echo $faker->firstNameMale; // "Adrian"
// Generates a random female first name
echo $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 Romania
echo $faker->cnp($gender = null, $dateOfBirth = null, $county = null, $isResident = true);

Faker\Provider\ro_RO\PhoneNumber

<?php

// Generates a random toll-free phone number
echo $faker->tollFreePhoneNumber; // "0800123456"
// Generates a random premium-rate phone number
echo $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 Company
echo $faker->inn; //  7813540735

//Generate a Russian Tax Code for Company
echo $faker->kpp; // 781301001

Faker\Provider\sv_SE\Payment

<?php

// Generates a random bank account number
echo $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 number
echo $faker->personalIdentityNumber; // A223456789

Faker\Provider\zh_TW\Company

<?php

// Generates a random VAT / Company Tax number
echo $faker->VAT; //23456789

Third-Party Libraries Extending/Based On Faker

License

Faker is released under the MIT License. See the bundled LICENSE file for details.

Dispatching closure like a job

\Log::info(['Before closure', date('Y-m-d H:i:s')]);
dispatch(function () {
    \Log::info(['Inside closure', date('Y-m-d H:i:s')]);
});
\Log::info(['After closure', date('Y-m-d H:i:s')]);

With delay

\Log::info(['Before closure', date('Y-m-d H:i:s')]);
dispatch(function () {
    \Log::info(['Inside closure with delay', date('Y-m-d H:i:s')]);
})->delay(now()->addSeconds(10));
\Log::info(['After closure', date('Y-m-d H:i:s')]);


// Inline
dispatch(function () { \Log::info(['Inside closure with delay', date('Y-m-d H:i:s')]); })->delay(now()->addSeconds(10));

https://laravel.com/docs/master/eloquent#eloquent-model-conventions

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * # 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:
    */

    const CREATED_AT = 'creation_date';
    const UPDATED_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,
    ];

    /**
     * ----------------------------------------------------------------------------------------------------
    */

}
    public function scopeUpdatePassword(
        $query,
        $userId,
        ?string $newPassword = \null,
        string $passwordColumn = 'password'
    ) {
        if (!$userId || !$newPassword) {
            return $query;
        }

        $newPassword = \Hash::make($newPassword);
        $modelInstance = (new static)->newInstance();
        return $query->where($modelInstance->getKeyName(), $userId)->update([
            $passwordColumn => $newPassword
        ]);
    }
<?php
/*-------- START LARAVEL OUTSIDE ---------*/
/*
To use Laravel core without then
If you whant to use core by CLI without artisan
*/
require __DIR__ . '/../../vendor/autoload.php';//Full path to file maybe need to change
$app = require_once __DIR__ . '/../../bootstrap/app.php';//Full path to file maybe need to change
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title"
    type="text"
    class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror
<!-- /resources/views/auth.blade.php -->

<label for="email">Email address</label>

<input id="email"
    type="email"
    class="@error('email', 'login') is-invalid @enderror">

@error('email', 'login')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror
<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->
<?php
#like foreach chunk loop foreach eloquent model break in pieces
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
}
});
#!/bin/bash
# curl -s "https://laravel.build/example-app" | bash
# bash ./start-new-laravel-app-with-docker-and-sail.sh
#########################
docker info > /dev/null 2>&1
# Ensure that Docker is running...
if [ $? -ne 0 ]; then
echo "Docker is not running."
exit 1
fi
docker run --rm \
-v "$(pwd)":/opt \
-w /opt \
laravelsail/php81-composer:latest \
bash -c "laravel new example-app && cd example-app && php ./artisan sail:install --with=mysql,redis,meilisearch,mailhog,selenium "
cd example-app
CYAN='\033[0;36m'
LIGHT_CYAN='\033[1;36m'
WHITE='\033[1;37m'
NC='\033[0m'
echo ""
if sudo -n true 2>/dev/null; then
sudo chown -R $USER: .
echo -e "${WHITE}Get started with:${NC} cd example-app && ./vendor/bin/sail up"
else
echo -e "${WHITE}Please provide your password so we can make some final adjustments to your application's permissions.${NC}"
echo ""
sudo chown -R $USER: .
echo ""
echo -e "${WHITE}Thank you! We hope you build something incredible. Dive in with:${NC} cd example-app && ./vendor/bin/sail up"
fi
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-4">
  <div class="bg-gray-100 p-4">Coluna 1, linha 1</div>
  <div class="bg-gray-100 p-4">Coluna 2, linha 1</div>
  <div class="bg-gray-100 p-4">Coluna 1, linha 2</div>
  <div class="bg-gray-100 p-4">Coluna 2, linha 2</div>
</div>
<div class="grid grid-cols-1">
    <div class="p-2">
        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-4">
            <div class="p-1">Coluna 1, linha 1</div>
            <div class="p-1">Coluna 2, linha 1</div>
            <div class="p-1">Coluna 1, linha 2</div>
            <div class="p-1">Coluna 2, linha 2</div>
        </div>
    </div>
</div>

Tenant model

/**
 * @var App\Models\Tenant|Stancl\Tenancy\Database\Models\Tenant $tenant
 */
$tenant = Tenant::first();

https://tenancyforlaravel.com/

tenancy()->initialize(Tenant::find('ti')); App\Models\AgregadorTipo\AgregadorTipo::find(1);

Manual initialization

$tenant = Tenant::find('some-id');

tenancy()->initialize($tenant);

vendor/stancl/tenancy/src/helpers.php

Função tenant

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ão
tenancy()->initialize(Tenant::find('cliente1'));

// initialized attribute: informa se existe um tenant inicializado
tenancy()->initialized; // boolean

// end(): encerra o tenant da sessão
tenancy()->end(); // null||\\\\\\\\\\\\\\\\\\\|||||||||||||||||

https://laravel.com/docs/9.x/http-tests#testing-json-apis

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Testing\Fluent\AssertableJson;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function test_making_an_api_request()
    {
        $response = $this->postJson('/api/user', ['name' => 'Sally']);

        // assert 1
        $response
            ->assertStatus(201)
            ->assertJson([
                'created' => true,
            ]);

        // assert 2
        $this->assertTrue($response['created']);

        // assert 3
        $response
            ->assertStatus(201)
            ->assertExactJson([
                'created' => true,
            ]);

        // assert 4
        $response->assertStatus(201)
            ->assertJsonPath('team.owner.name', 'Darian');

        // assert 4.a
        $response->assertJsonPath(
            'inputs.0.id', fn ($item) => Str::isUuid($item)
        );

        // assert 4.b
        $response->assertJsonPath(
            'team.owner.name',
            fn ($name) => strlen($name) >= 3
        );

        // assert 5
        $response->assertJson(fn (AssertableJson $json) =>
            $json->where('id', 1)
                 ->where('name', 'Victoria Faith')
                 ->whereNot('status', 'pending')
                 ->missing('password')
                 ->etc()
        );

        // assert 5.a
        $response->assertJson(fn (AssertableJson $json) =>
            $json->has('data')
                ->missing('message')
        );

        // assert 5.b
        $response->assertJson(fn (AssertableJson $json) =>
            $json->hasAll(['status', 'data'])
                ->missingAll(['message', 'code'])
        );

        // assert 5.c
        /*
            return User::all();
        */
        $response->assertJson(fn (AssertableJson $json) =>
            $json->has(3)
                ->first(fn ($json) =>
                    $json->where('id', 1)
                        ->where('name', 'Victoria Faith')
                        ->missing('password')
                        ->etc()
                )
        );

        // assert 5.d
        /*
            return [
                'meta' => [...],
                'users' => User::all(),
            ];
        */
        $response->assertJson(fn (AssertableJson $json) =>
            $json->has('meta')
                ->has('users', 3)
                ->has('users.0', fn ($json) =>
                    $json->where('id', 1)
                        ->where('name', 'Victoria Faith')
                        ->missing('password')
                        ->etc()
                )
        );

        // assert 6 Asserting JSON Types
        // https://laravel.com/docs/9.x/http-tests#asserting-json-types

        $response->assertJson(fn (AssertableJson $json) =>
            $json->whereType('id', 'integer')
                ->whereAllType([
                    'users.0.name' => 'string',
                    'meta' => 'array'
                ])
        );

        // assert 6.a
        $response->assertJson(fn (AssertableJson $json) =>
            $json->whereType('name', 'string|null')
                ->whereType('id', ['string', 'integer'])
        );

        // assert #
        // assert #
        // assert #
    }

    // Assert validations required
    // https://laravel.com/docs/9.x/http-tests#assert-invalid
    // assertValid/assertInvalid
    $response = $this->post(\route('surveys.new_answer'));
    $response->assertStatus(302);
    $response->assertInvalid(['survey_id' => 'The survey id field is required.']);

    $response->assertInvalid([
        'name' => 'The name field is required.',
        'email' => 'valid email address',
    ]);

}

Carbon set fake today

Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
echo Carbon::now();

factory-relationships

https://laravel.com/docs/8.x/database-testing#factory-relationships

/*
    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 inline
$faker = (\Faker\Factory::create());
#----------------------------------------------------

https://github.com/fzaninotto/Faker#formatters

randomDigit()             // 7
randomDigitNot(5)       // 0, 1, 2, 3, 4, 6, 7, 8, or 9
randomDigitNotNull()      // 5
randomNumber($nbDigits = NULL, $strict = false) // 79907610
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
numberBetween($min = 1000, $max = 9000) // 8567
randomLetter()            // 'b'
// returns randomly ordered subsequence of a provided array
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
randomElement($array = array ('a','b','c')) // 'b'
shuffle('hello, world') // 'rlo,h eoldlw'
shuffle(array(1, 2, 3)) // array(2, 1, 3)
numerify('Hello ###') // 'Hello 609'
lexify('Hello ???') // 'Hello wgt'
bothify('Hello ##??') // 'Hello 42jz'
asciify('Hello ***') // 'Hello R6+'
regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // sm0@y8k96a.ej

company() // Lourenço e Cervantes / Lovato e Zambrano Ltda.
fake('pt_BR')->company() // company name business name

Prontos

# CPF (sem validação)
numerify('###.###.###-##')
numerify('###########')

# CNPJ (sem validação)
// com máscara
numerify('##.###.###/####-##')

// sem máscara
numerify('##############')

// Um desses números
regexify('(19|2[0-5]){1}')
regexify('[PFEH](19|2[0-5]){1}M[0-1][0-2][0-2][1-9]'),// Código de parceiro

# NIS
numerify('###.#####.##-#')

# 16 itens - hexa
regexify('[a-f][0-9]{16}')

# Nascimento
date(rand(1980, 2006) . '-m-d')

# Valores monetários
numerify(str_repeat('#', rand(2, 7)).'.##')

# Telefone SEM máscara
fake()->regexify('([14689][1-9])9([1-9]){8}')
// ou
fake()->regexify('9([1-9]){10}')

# Telefone COM máscara
sprintf('(%s) 9%s-%s', fake()->regexify('([1-9]){2}'), fake()->regexify('([1-9]){4}'), fake()->regexify('([1-9]){4}'))

Faker

Monthly Downloads Continuous Integration codecov SensioLabsInsight

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.

Faker requires PHP >= 5.3.3.

Faker is archived. Read the reasons behind this decision here: https://marmelab.com/blog/2020/10/21/sunsetting-faker.html

Table of Contents

Installation

composer require fzaninotto/faker

Basic Usage

Autoloading

Faker supports both PSR-0 as PSR-4 autoloaders.

<?php
# When installed via composer
require_once 'vendor/autoload.php';

You can also load Fakers shipped PSR-0 autoloader

<?php
# Load Fakers own autoloader
require_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 properties
echo $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).

<?php
for ($i = 0; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Adaline Reichel
  // Dr. Santa Prosacco DVM
  // Noemy Vandervort V
  // Lexi O'Conner
  // Gracie Weber
  // Roscoe Johns
  // Emmett Lebsack
  // Keegan Thiel
  // Wellington Koelpin II
  // Ms. Karley Kiehn V

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.

Faker\Provider\Base

randomDigit             // 7
randomDigitNot(5)       // 0, 1, 2, 3, 4, 6, 7, 8, or 9
randomDigitNotNull      // 5
randomNumber($nbDigits = NULL, $strict = false) // 79907610
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
numberBetween($min = 1000, $max = 9000) // 8567
randomLetter            // 'b'
// returns randomly ordered subsequence of a provided array
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
randomElement($array = array ('a','b','c')) // 'b'
shuffle('hello, world') // 'rlo,h eoldlw'
shuffle(array(1, 2, 3)) // array(2, 1, 3)
numerify('Hello ###') // 'Hello 609'
lexify('Hello ???') // 'Hello wgt'
bothify('Hello ##??') // 'Hello 42jz'
asciify('Hello ***') // 'Hello R6+'
regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // sm0@y8k96a.ej

Faker\Provider\Lorem

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.'

Faker\Provider\en_US\Person

title($gender = null|'male'|'female')     // 'Ms.'
titleMale                                 // 'Mr.'
titleFemale                               // 'Ms.'
suffix                                    // 'Jr.'
name($gender = null|'male'|'female')      // 'Dr. Zane Stroman'
firstName($gender = null|'male'|'female') // 'Maynard'
firstNameMale                             // 'Maynard'
firstNameFemale                           // 'Rachel'
lastName                                  // 'Zulauf'

Faker\Provider\en_US\Address

cityPrefix                          // 'Lake'
secondaryAddress                    // 'Suite 961'
state                               // 'NewMexico'
stateAbbr                           // 'OH'
citySuffix                          // 'borough'
streetSuffix                        // 'Keys'
buildingNumber                      // '484'
city                                // 'West Judge'
streetName                          // 'Keegan Trail'
streetAddress                       // '439 Karley Loaf Suite 897'
postcode                            // '17916'
address                             // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473'
country                             // 'Falkland Islands (Malvinas)'
latitude($min = -90, $max = 90)     // 77.147489
longitude($min = -180, $max = 180)  // 86.211205

Faker\Provider\en_US\PhoneNumber

phoneNumber             // '201-886-0269 x3767'
tollFreePhoneNumber     // '(888) 937-7238'
e164PhoneNumber     // '+27113456789'

Faker\Provider\en_US\Company

catchPhrase             // 'Monitored regional contingency'
bs                      // 'e-enable robust architectures'
company                 // 'Bogan-Treutel'
companySuffix           // 'and Sons'
jobTitle                // 'Cashier'

Faker\Provider\en_US\Text

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."

Faker\Provider\DateTime

unixTime($max = 'now')                // 58781813
dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC')
dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris')
iso8601($max = 'now')                 // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos')
dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok')
dateTimeThisCentury($max = 'now', $timezone = null)     // DateTime('1915-05-30 19:28:21', 'UTC')
dateTimeThisDecade($max = 'now', $timezone = null)      // DateTime('2007-05-29 22:30:48', 'Europe/Paris')
dateTimeThisYear($max = 'now', $timezone = null)        // DateTime('2011-02-27 20:52:14', 'Africa/Lagos')
dateTimeThisMonth($max = 'now', $timezone = null)       // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok')
amPm($max = 'now')                    // 'pm'
dayOfMonth($max = 'now')              // '04'
dayOfWeek($max = 'now')               // 'Friday'
month($max = 'now')                   // '06'
monthName($max = 'now')               // 'January'
year($max = 'now')                    // '1993'
century                               // 'VI'
timezone                              // 'Europe/Paris'

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).

Faker\Provider\Internet

email                   // 'tkshlerin@collins.com'
safeEmail               // 'king.alford@example.org'
freeEmail               // 'bradley72@gmail.com'
companyEmail            // 'russel.durward@mcdermott.org'
freeEmailDomain         // 'yahoo.com'
safeEmailDomain         // 'example.org'
userName                // 'wade55'
password                // 'k&|X+a45*2['
domainName              // 'wolffdeckow.net'
domainWord              // 'feeney'
tld                     // 'biz'
url                     // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html'
slug                    // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum'
ipv4                    // '109.133.32.252'
localIpv4               // '10.242.58.8'
ipv6                    // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c'
macAddress              // '43:85:B7:08:10:CA'

Faker\Provider\UserAgent

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'

Faker\Provider\Color

hexcolor               // '#fa3cc2'
rgbcolor               // '0,255,122'
rgbColorAsArray        // array(0,255,122)
rgbCssColor            // 'rgb(0,255,122)'
safeColorName          // 'fuchsia'
colorName              // 'Gainsbor'
hslColor               // '340,50,20'
hslColorAsArray        // array(340,50,20)

Faker\Provider\File

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'

Faker\Provider\Image

// Image generation provided by LoremPixel (http://lorempixel.com/)
imageUrl($width = 640, $height = 480) // 'http://lorempixel.com/640/480/'
imageUrl($width, $height, 'cats')     // 'http://lorempixel.com/800/600/cats/'
imageUrl($width, $height, 'cats', true, 'Faker') // 'http://lorempixel.com/800/400/cats/Faker'
imageUrl($width, $height, 'cats', true, 'Faker', true) // 'http://lorempixel.com/gray/800/400/cats/Faker/' Monochrome image
image($dir = '/tmp', $width = 640, $height = 480) // '/tmp/13b73edae8443990be1aa8f1a483bc27.jpg'
image($dir, $width, $height, 'cats')  // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat!
image($dir, $width, $height, 'cats', false) // '13b73edae8443990be1aa8f1a483bc27.jpg' it's a filename without path
image($dir, $width, $height, 'cats', true, false) // it's a no randomize images (default: `true`)
image($dir, $width, $height, 'cats', true, true, 'Faker') // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat with 'Faker' text. Default, `null`.

Faker\Provider\Uuid

uuid                   // '7e57d004-2b97-0e7a-b45f-5387367791cd'

Faker\Provider\Barcode

ean13          // '4006381333931'
ean8           // '73513537'
isbn13         // '9790404436093'
isbn10         // '4881416324'

Faker\Provider\Miscellaneous

boolean // false
boolean($chanceOfGettingTrue = 50) // true
md5           // 'de99a620c50f2990e87144735cd357e7'
sha1          // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c'
sha256        // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5'
locale        // en_UK
countryCode   // UK
languageCode  // en
currencyCode  // EUR
emoji         // 😁

Faker\Provider\Biased

// 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 faker
for ($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:

<?php
$generator = \Faker\Factory::create();
$populator = new \Faker\ORM\Propel\Populator($generator);
$populator->addEntity('Author', 5);
$populator->addEntity('Book', 10);
$insertedPKs = $populator->execute();

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():

<?php
$populator->addEntity('Book', 5, array(
  'ISBN' => function() use ($generator) { return $generator->ean13(); }
));

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:

<?php
$populator->addEntity('Book', 5, array(
  'CreatedAt' => null,
  'UpdatedAt' => null,
));

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:

<?php
print_r($insertedPKs);
// array(
//   'Author' => (34, 35, 36, 37, 38),
//   'Book'   => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475)
// )

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:

<?php
$populator->addEntity('Book', 5, array(), array(
  function($book) { $book->publish(); },
));

Seeding the Generator

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.

<?php
$faker = Faker\Factory::create();
$faker->seed(1234);

echo $faker->name; // 'Jess Mraz I';

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:

<?php
// bad
$faker->realText(rand(10,20));
// good
$faker->realText($faker->numberBetween(10,20));

Faker Internals: Understanding Providers

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:

<?php
$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Person($faker));
$faker->addProvider(new Faker\Provider\en_US\Address($faker));
$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker));
$faker->addProvider(new Faker\Provider\en_US\Company($faker));
$faker->addProvider(new Faker\Provider\Lorem($faker));
$faker->addProvider(new Faker\Provider\Internet($faker));

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:

<?php

namespace Faker\Provider;

class Book extends \Faker\Provider\Base
{
  public function title($nbWords = 5)
  {
    $sentence = $this->generator->sentence($nbWords);
    return substr($sentence, 0, strlen($sentence) - 1);
  }

  public function ISBN()
  {
    return $this->generator->ean13();
  }
}

To register this provider, just add a new instance of \Faker\Provider\Book to an existing generator:

<?php
$faker->addProvider(new \Faker\Provider\Book($faker));

Now you can use the two new formatters like any other Faker formatter:

<?php
$book = new Book();
$book->setTitle($faker->title);
$book->setISBN($faker->ISBN);
$book->setSummary($faker->text);
$book->setPrice($faker->randomNumber(2));

Tip: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator.

Real Life Usage

The following script generates a valid XML document:

<?php
require_once '/path/to/Faker/src/autoload.php';
$faker = Faker\Factory::create();
?>
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<?php for ($i = 0; $i < 10; $i++): ?>
  <contact firstName="<?php echo $faker->firstName ?>" lastName="<?php echo $faker->lastName ?>" email="<?php echo $faker->email ?>">
    <phone number="<?php echo $faker->phoneNumber ?>"/>
<?php if ($faker->boolean(25)): ?>
    <birth date="<?php echo $faker->dateTimeThisCentury->format('Y-m-d') ?>" place="<?php echo $faker->city ?>"/>
<?php endif; ?>
    <address>
      <street><?php echo $faker->streetAddress ?></street>
      <city><?php echo $faker->city ?></city>
      <postcode><?php echo $faker->postcode ?></postcode>
      <state><?php echo $faker->state ?></state>
    </address>
    <company name="<?php echo $faker->company ?>" catchPhrase="<?php echo $faker->catchPhrase ?>">
<?php if ($faker->boolean(33)): ?>
      <offer><?php echo $faker->bs ?></offer>
<?php endif; ?>
<?php if ($faker->boolean(33)): ?>
      <director name="<?php echo $faker->name ?>" />
<?php endif; ?>
    </company>
<?php if ($faker->boolean(15)): ?>
    <details>
<![CDATA[
<?php echo $faker->text(400) ?>
]]>
    </details>
<?php endif; ?>
  </contact>
<?php endfor; ?>
</contacts>

Running this script produces a document looking like:

<?xml version="1.0" encoding="UTF-8"?>
<contacts>
  <contact firstName="Ona" lastName="Bednar" email="schamberger.frank@wuckert.com">
    <phone number="1-265-479-1196x714"/>
    <address>
      <street>182 Harrison Cove</street>
      <city>North Lloyd</city>
      <postcode>45577</postcode>
      <state>Alabama</state>
    </address>
    <company name="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>
  <contact firstName="Aurelie" lastName="Paucek" email="alfonzo55@durgan.com">
    <phone number="863.712.1363x9425"/>
    <address>
      <street>90111 Hegmann Inlet</street>
      <city>South Geovanymouth</city>
      <postcode>69961-9311</postcode>
      <state>Colorado</state>
    </address>
    <company name="Krajcik-Grimes" catchPhrase="Switchable cohesive instructionset">
    </company>
  </contact>
  <contact firstName="Clifton" lastName="Kshlerin" email="kianna.wiegand@framiwyman.info">
    <phone number="692-194-4746"/>
    <address>
      <street>9791 Nona Corner</street>
      <city>Harberhaven</city>
      <postcode>74062-8191</postcode>
      <state>RhodeIsland</state>
    </address>
    <company name="Rosenbaum-Aufderhar" catchPhrase="Realigned asynchronous encryption">
    </company>
  </contact>
  <contact firstName="Alexandre" lastName="Orn" email="thelma37@erdmancorwin.biz">
    <phone number="189.655.8677x027"/>
    <address>
      <street>11161 Schultz Via</street>
      <city>Feilstad</city>
      <postcode>98019</postcode>
      <state>NewJersey</state>
    </address>
    <company name="O'Hara-Prosacco" catchPhrase="Re-engineered solution-oriented algorithm">
      <director name="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>
  <contact firstName="Katelynn" lastName="Kohler" email="reinger.trudie@stiedemannjakubowski.com">
    <phone number="(665)713-1657"/>
    <address>
      <street>6106 Nader Village Suite 753</street>
      <city>McLaughlinstad</city>
      <postcode>43189-8621</postcode>
      <state>Missouri</state>
    </address>
    <company name="Herman-Tremblay" catchPhrase="Object-based explicit service-desk">
      <offer>expedite viral synergies</offer>
      <director name="Arden Deckow" />
    </company>
  </contact>
  <contact firstName="Blanca" lastName="Stark" email="tad27@feest.net">
    <phone number="168.719.4692x87177"/>
    <address>
      <street>7546 Kuvalis Plaza</street>
      <city>South Wilfrid</city>
      <postcode>77069</postcode>
      <state>Georgia</state>
    </address>
    <company name="Upton, Braun and Rowe" catchPhrase="Visionary leadingedge pricingstructure">
    </company>
  </contact>
  <contact firstName="Rene" lastName="Spencer" email="anibal28@armstrong.info">
    <phone number="715.222.0095x175"/>
    <birth date="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>
    <company name="Wiza Inc" catchPhrase="Persevering reciprocal approach">
      <offer>orchestrate dynamic networks</offer>
      <director name="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>
  <contact firstName="Alessandro" lastName="Hagenes" email="tbreitenberg@oharagorczany.com">
    <phone number="1-284-958-6768"/>
    <address>
      <street>1251 Koelpin Mission</street>
      <city>North Revastad</city>
      <postcode>81620</postcode>
      <state>Maryland</state>
    </address>
    <company name="Stiedemann-Bruen" catchPhrase="Re-engineered 24/7 success">
    </company>
  </contact>
  <contact firstName="Novella" lastName="Rutherford" email="claud65@bogisich.biz">
    <phone number="(091)825-7971"/>
    <address>
      <street>6396 Langworth Hills Apt. 446</street>
      <city>New Carlos</city>
      <postcode>89399-0268</postcode>
      <state>Wyoming</state>
    </address>
    <company name="Stroman-Legros" catchPhrase="Expanded 4thgeneration moratorium">
      <director name="Earlene Bayer" />
    </company>
  </contact>
  <contact firstName="Andreane" lastName="Mann" email="meggie17@ornbaumbach.com">
    <phone number="941-659-9982x5689"/>
    <birth date="1934-02-21" place="Stantonborough"/>
    <address>
      <street>2246 Kreiger Station Apt. 291</street>
      <city>Kaydenmouth</city>
      <postcode>11397-1072</postcode>
      <state>Wyoming</state>
    </address>
    <company name="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

<?php

echo $faker->idNumber;      // ID number
echo $faker->nationalIdNumber // Citizen ID number
echo $faker->foreignerIdNumber // Foreigner ID number
echo $faker->companyIdNumber // Company ID number

Faker\Provider\ar_SA\Payment

<?php

echo $faker->bankAccountNumber // "SA0218IBYZVZJSEC8536V4XC"

Faker\Provider\at_AT\Payment

<?php

echo $faker->vat;           // "AT U12345678" - Austrian Value Added Tax number
echo $faker->vat(false);    // "ATU12345678" - unspaced Austrian Value Added Tax number

Faker\Provider\bg_BG\Payment

<?php

echo $faker->vat;           // "BG 0123456789" - Bulgarian Value Added Tax number
echo $faker->vat(false);    // "BG0123456789" - unspaced Bulgarian Value Added Tax number

Faker\Provider\cs_CZ\Address

<?php

echo $faker->region; // "Liberecký kraj"

Faker\Provider\cs_CZ\Company

<?php

// Generates a valid IČO
echo $faker->ico; // "69663963"

Faker\Provider\cs_CZ\DateTime

<?php

echo $faker->monthNameGenitive; // "prosince"
echo $faker->formattedDate; // "12. listopadu 2015"

Faker\Provider\cs_CZ\Person

<?php

echo $faker->birthNumber; // "7304243452"

Faker\Provider\da_DK\Person

<?php

// Generates a random CPR number
echo $faker->cpr; // "051280-2387"

Faker\Provider\da_DK\Address

<?php

// Generates a random 'kommune' name
echo $faker->kommune; // "Frederiksberg"

// Generates a random region name
echo $faker->region; // "Region Sjælland"

Faker\Provider\da_DK\Company

<?php

// Generates a random CVR number
echo $faker->cvr; // "32458723"

// Generates a random P number
echo $faker->p; // "5398237590"

Faker\Provider\de_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97" OR
echo $faker->ahv13; // "756.1234.5678.97"

Faker\Provider\de_DE\Payment

<?php

echo $faker->bankAccountNumber; // "DE41849025553661169313"
echo $faker->bank; // "Volksbank Stuttgart"

Faker\Provider\en_HK\Address

<?php

// Generates a fake town name based on the words commonly found in Hong Kong
echo $faker->town; // "Yuen Long"

// Generates a fake village name based on the words commonly found in Hong Kong
echo $faker->village; // "O Tau"

// Generates a fake estate name based on the words commonly found in Hong Kong
echo $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 name
echo $faker->region; // 'Katsina'

Faker\Provider\en_NG\Person

<?php

// Generates a random person name
echo $faker->name; // 'Oluwunmi Mayowa'

Faker\Provider\en_NZ\Phone

<?php

// Generates a cell (mobile) phone number
echo $faker->mobileNumber; // "021 123 4567"

// Generates a toll free number
echo $faker->tollFreeNumber; // "0800 123 456"

// Area Code
echo $faker->areaCode; // "03"

Faker\Provider\en_US\Company

<?php

// Generate a random Employer Identification Number
echo $faker->ein; // '12-3456789'

Faker\Provider\en_US\Payment

<?php

echo $faker->bankAccountNumber;  // '51915734310'
echo $faker->bankRoutingNumber;  // '212240302'

Faker\Provider\en_US\Person

<?php

// Generates a random Social Security Number
echo $faker->ssn; // '123-45-6789'

Faker\Provider\en_ZA\Company

<?php

// Generates a random company registration number
echo $faker->companyNumber; // 1999/789634/01

Faker\Provider\en_ZA\Person

<?php

// Generates a random national identification number
echo $faker->idNumber; // 6606192211041

// Generates a random valid licence code
echo $faker->licenceCode; // EB

Faker\Provider\en_ZA\PhoneNumber

<?php

// Generates a special rate toll free phone number
echo $faker->tollFreeNumber; // 0800 555 5555

// Generates a mobile phone number
echo $faker->mobileNumber; // 082 123 5555

Faker\Provider\es_ES\Person

<?php

// Generates a Documento Nacional de Identidad (DNI) number
echo $faker->dni; // '77446565E'

// Generates a random valid licence code
echo $faker->licenceCode; // B

Faker\Provider\es_ES\Payment

<?php
// Generates a Código de identificación Fiscal (CIF) number
echo $faker->vat;           // "A35864370"

Faker\Provider\es_ES\PhoneNumber

<?php

// Generates a special rate toll free phone number
echo $faker->tollFreeNumber; // 900 123 456

// Generates a mobile phone number
echo $faker->mobileNumber; // +34 612 12 24

Faker\Provider\es_PE\Person

<?php

// Generates a Peruvian Documento Nacional de Identidad (DNI) number
echo $faker->dni; // '83367512'

Faker\Provider\fa_IR\Person

<?php

// Generates a valid nationalCode
echo $faker->nationalCode; // "0078475759"

Faker\Provider\fa_IR\Address

<?php

// Generates a random building name
echo $faker->building; // "ساختمان آفتاب"

// Returns a random city name
echo $faker->city // "استان زنجان"

Faker\Provider\fa_IR\Company

<?php

// Generates a random contract type
echo $faker->contract; // "رسمی"

Faker\Provider\fi_FI\Payment

<?php

// Generates a random bank account number
echo $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

<?php

echo $faker->vat;           // "BE 0123456789" - Belgian Value Added Tax number
echo $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 separator
echo $faker->nationalId; // 'V11223344'

Faker\Provider\es_VE\Company

<?php

// Generates a R.I.F. number, you can pass one argument to add separators
echo $faker->taxpayerIdentificationNumber; // 'J1234567891'

Faker\Provider\fr_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97"

Faker\Provider\fr_FR\Address

<?php

// Generates a random department name
echo $faker->departmentName; // "Haut-Rhin"

// Generates a random department number
echo $faker->departmentNumber; // "2B"

// Generates a random department info (department number => department name)
$faker->department; // array('18' => 'Cher');

// Generates a random region
echo $faker->region; // "Saint-Pierre-et-Miquelon"

// Generates a random appartement,stair
echo $faker->secondaryAddress; // "Bat. 961"

Faker\Provider\fr_FR\Company

<?php

// Generates a random SIREN number
echo $faker->siren; // 082 250 104

// Generates a random SIRET number
echo $faker->siret; // 347 355 708 00224

Faker\Provider\fr_FR\Payment

<?php

// Generates a random VAT
echo $faker->vat; // FR 12 123 456 789

Faker\Provider\fr_FR\Person

<?php

// Generates a random NIR / Sécurité Sociale number
echo $faker->nir; // 1 88 07 35 127 571 - 19

Faker\Provider\fr_FR\PhoneNumber

<?php

// Generates phone numbers
echo $faker->phoneNumber; // +33 (0)1 67 97 01 31
echo $faker->mobileNumber; // +33 6 21 12 72 84
echo $faker->serviceNumber // 08 98 04 84 46

Faker\Provider\he_IL\Payment

<?php

echo $faker->bankAccountNumber // "IL392237392219429527697"

Faker\Provider\hr_HR\Payment

<?php

echo $faker->bankAccountNumber // "HR3789114847226078672"

Faker\Provider\hu_HU\Payment

<?php

// Generates a random bank account number
echo $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 used
echo $faker->nik(); // "8522246001570940"

Faker\Provider\it_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97"

Faker\Provider\it_IT\Company

<?php

// Generates a random Vat Id
echo $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' name
echo $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 number
echo $faker->bankAccountNumber; // "GE33ZV9773853617253389"

Faker\Provider\kk_KZ\Company

<?php

// Generates an business identification number
echo $faker->businessIdentificationNumber; // "150140000019"

Faker\Provider\kk_KZ\Payment

<?php

// Generates a random bank name
echo $faker->bank; // "Қазкоммерцбанк"

// Generates a random bank account number
echo $faker->bankAccountNumber; // "KZ1076321LO4H6X41I37"

Faker\Provider\kk_KZ\Person

<?php

// Generates an individual identification number
echo $faker->individualIdentificationNumber; // "780322300455"

// Generates an individual identification number based on his/her birth date
echo $faker->individualIdentificationNumber(new \DateTime('1999-03-01')); // "990301300455"

Faker\Provider\ko_KR\Address

<?php

// Generates a metropolitan city
echo $faker->metropolitanCity; // "서울특별시"

// Generates a borough
echo $faker->borough; // "강남구"

Faker\Provider\ko_KR\PhoneNumber

<?php

// Generates a local area phone numer
echo $faker->localAreaPhoneNumber; // "02-1234-4567"

// Generates a cell phone number
echo $faker->cellPhoneNumber; // "010-9876-5432"

Faker\Provider\lt_LT\Payment

<?php

echo $faker->bankAccountNumber // "LT300848876740317118"

Faker\Provider\lv_LV\Person

<?php

// Generates a random personal identity card number
echo $faker->personalIdentityNumber; // "140190-12301"

Faker\Provider\ms_MY\Address

<?php

// Generates a random Malaysian township
echo $faker->township; // "Taman Bahagia"

// Generates a random Malaysian town address with matching postcode and state
echo $faker->townState; // "55100 Bukit Bintang, Kuala Lumpur"

Faker\Provider\ms_MY\Miscellaneous

<?php

// Generates a random vehicle license plate number
echo $faker->jpjNumberPlate; // "WPL 5169"

Faker\Provider\ms_MY\Payment

<?php

// Generates a random Malaysian bank
echo $faker->bank; // "Maybank"

// Generates a random Malaysian bank account number (10-16 digits)
echo $faker->bankAccountNumber; // "1234567890123456"

// Generates a random Malaysian insurance company
echo $faker->insurance; // "AIA Malaysia"

// Generates a random Malaysian bank SWIFT Code
echo $faker->swiftCode; // "MBBEMYKLXXX"

Faker\Provider\ms_MY\Person

<?php

// Generates a random personal identity card (myKad) number
echo $faker->myKadNumber($gender = null|'male'|'female', $hyphen = null|true|false); // "710703471796"

Faker\Provider\ms_MY\PhoneNumber

<?php

// Generates a random Malaysian mobile number
echo $faker->mobileNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "+6012-705 3767"

// Generates a random Malaysian landline number
echo $faker->fixedLineNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "03-7112 0455"

// Generates a random Malaysian voip number
echo $faker->voipNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "015-458 7099"

Faker\Provider\ne_NP\Address

<?php

//Generates a Nepali district name
echo $faker->district;

//Generates a Nepali city name
echo $faker->cityName;

Faker\Provider\nl_BE\Payment

<?php

echo $faker->vat;           // "BE 0123456789" - Belgian Value Added Tax number
echo $faker->vat(false);    // "BE0123456789" - unspaced Belgian Value Added Tax number

Faker\Provider\nl_BE\Person

<?php

echo $faker->rrn();         // "83051711784" - Belgian Rijksregisternummer
echo $faker->rrn('female'); // "50032089858" - Belgian Rijksregisternummer for a female

Faker\Provider\nl_NL\Company

<?php

echo $faker->jobTitle; // "Houtbewerker"
echo $faker->vat; // "NL123456789B01" - Dutch Value Added Tax number
echo $faker->btw; // "NL123456789B01" - Dutch Value Added Tax number (alias)

Faker\Provider\nl_NL\Person

<?php

echo $faker->idNumber; // "111222333" - Dutch Personal identification number (BSN)

Faker\Provider\nb_NO\MobileNumber

<?php

// Generates a random Norwegian mobile phone number
echo $faker->mobileNumber; // "+4799988777"
echo $faker->mobileNumber; // "999 88 777"
echo $faker->mobileNumber; // "99988777"

Faker\Provider\nb_NO\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "NO3246764709816"

Faker\Provider\pl_PL\Person

<?php

// Generates a random PESEL number
echo $faker->pesel; // "40061451555"
// Generates a random personal identity card number
echo $faker->personalIdentityNumber; // "AKX383360"
// Generates a random taxpayer identification number (NIP)
echo $faker->taxpayerIdentificationNumber; // '8211575109'

Faker\Provider\pl_PL\Company

<?php

// Generates a random REGON number
echo $faker->regon; // "714676680"
// Generates a random local REGON number
echo $faker->regonLocal; // "15346111382836"

Faker\Provider\pl_PL\Payment

<?php

// Generates a random bank name
echo $faker->bank; // "Narodowy Bank Polski"
// Generates a random bank account number
echo $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 name
echo $faker->region; // 'Nordeste'

// Generates a random region abbreviation
echo $faker->regionAbbr; // 'NE'

Faker\Provider\pt_BR\PhoneNumber

<?php

echo $faker->areaCode;  // 21
echo $faker->cellphone; // 9432-5656
echo $faker->landline;  // 2654-3445
echo $faker->phone;     // random landline, 8-digit or 9-digit cellphone number

// Using the phone functions with a false argument returns unformatted numbers
echo $faker->cellphone(false); // 74336667

// cellphone() has a special second argument to add the 9th digit. Ignored if generated a Radio number
echo $faker->cellphone(true, true); // 98983-3945 or 7343-1290

// Using the "Number" suffix adds area code to the phone
echo $faker->cellphoneNumber;       // (11) 98309-2935
echo $faker->landlineNumber(false); // 3522835934
echo $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 suffix
echo $faker->name; // 'Sr. Luis Adriano Sepúlveda Filho'

// Valid document generators have a boolean argument to remove formatting
echo $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 CNPJ
echo $faker->cnpj;        // '23.663.478/0001-24'
echo $faker->cnpj(false); // '23663478000124'

Faker\Provider\ro_MD\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "MD83BQW1CKMUW34HBESDP3A8"

Faker\Provider\ro_RO\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "RO55WRJE3OE8X3YQI7J26U1E"

Faker\Provider\ro_RO\Person

<?php

// Generates a random male name prefix/title
echo $faker->prefixMale; // "ing."
// Generates a random female name prefix/title
echo $faker->prefixFemale; // "d-na."
// Generates a random male first name
echo $faker->firstNameMale; // "Adrian"
// Generates a random female first name
echo $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 Romania
echo $faker->cnp($gender = null, $dateOfBirth = null, $county = null, $isResident = true);

Faker\Provider\ro_RO\PhoneNumber

<?php

// Generates a random toll-free phone number
echo $faker->tollFreePhoneNumber; // "0800123456"
// Generates a random premium-rate phone number
echo $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 Company
echo $faker->inn; //  7813540735

//Generate a Russian Tax Code for Company
echo $faker->kpp; // 781301001

Faker\Provider\sv_SE\Payment

<?php

// Generates a random bank account number
echo $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 number
echo $faker->personalIdentityNumber; // A223456789

Faker\Provider\zh_TW\Company

<?php

// Generates a random VAT / Company Tax number
echo $faker->VAT; //23456789

Third-Party Libraries Extending/Based On Faker

License

Faker is released under the MIT License. See the bundled LICENSE file for details.

<?php

namespace Tests\Feature;

// use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AuthRequiredTest extends TestCase
{
    /**
     * A basic test example.
     */
    public function testTheApplicationRedirectToLogin(): void
    {
        $response = $this->get('/');

        $response->assertStatus(302)
        ->assertRedirect(route('filament.auth.login'));
    }
}
// Illuminate\Http\Response
// Symfony\Component\HttpFoundation\Response

    public const HTTP_CONTINUE = 100;
    public const HTTP_SWITCHING_PROTOCOLS = 101;
    public const HTTP_PROCESSING = 102;            // RFC2518
    public const HTTP_EARLY_HINTS = 103;           // RFC8297
    public const HTTP_OK = 200;
    public const HTTP_CREATED = 201;
    public const HTTP_ACCEPTED = 202;
    public const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
    public const HTTP_NO_CONTENT = 204;
    public const HTTP_RESET_CONTENT = 205;
    public const HTTP_PARTIAL_CONTENT = 206;
    public const HTTP_MULTI_STATUS = 207;          // RFC4918
    public const HTTP_ALREADY_REPORTED = 208;      // RFC5842
    public const HTTP_IM_USED = 226;               // RFC3229
    public const HTTP_MULTIPLE_CHOICES = 300;
    public const HTTP_MOVED_PERMANENTLY = 301;
    public const HTTP_FOUND = 302;
    public const HTTP_SEE_OTHER = 303;
    public const HTTP_NOT_MODIFIED = 304;
    public const HTTP_USE_PROXY = 305;
    public const HTTP_RESERVED = 306;
    public const HTTP_TEMPORARY_REDIRECT = 307;
    public const HTTP_PERMANENTLY_REDIRECT = 308;  // RFC7238
    public const HTTP_BAD_REQUEST = 400;
    public const HTTP_UNAUTHORIZED = 401;
    public const HTTP_PAYMENT_REQUIRED = 402;
    public const HTTP_FORBIDDEN = 403;
    public const HTTP_NOT_FOUND = 404;
    public const HTTP_METHOD_NOT_ALLOWED = 405;
    public const HTTP_NOT_ACCEPTABLE = 406;
    public const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    public const HTTP_REQUEST_TIMEOUT = 408;
    public const HTTP_CONFLICT = 409; //slug, nicname, email, account alread exists (check if exists)
    public const HTTP_GONE = 410;
    public const HTTP_LENGTH_REQUIRED = 411;
    public const HTTP_PRECONDITION_FAILED = 412;
    public const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    public const HTTP_REQUEST_URI_TOO_LONG = 414;
    public const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    public const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    public const HTTP_EXPECTATION_FAILED = 417;
    public const HTTP_I_AM_A_TEAPOT = 418;                                               // RFC2324
    public const HTTP_MISDIRECTED_REQUEST = 421;                                         // RFC7540
    public const HTTP_UNPROCESSABLE_ENTITY = 422;                                        // RFC4918
    public const HTTP_LOCKED = 423;                                                      // RFC4918
    public const HTTP_FAILED_DEPENDENCY = 424;                                           // RFC4918
    public const HTTP_TOO_EARLY = 425;                                                   // RFC-ietf-httpbis-replay-04
    public const HTTP_UPGRADE_REQUIRED = 426;                                            // RFC2817
    public const HTTP_PRECONDITION_REQUIRED = 428;                                       // RFC6585
    public const HTTP_TOO_MANY_REQUESTS = 429;                                           // RFC6585
    public const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;                             // RFC6585
    public const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;                               // RFC7725
    public const HTTP_INTERNAL_SERVER_ERROR = 500;
    public const HTTP_NOT_IMPLEMENTED = 501;
    public const HTTP_BAD_GATEWAY = 502;
    public const HTTP_SERVICE_UNAVAILABLE = 503;
    public const HTTP_GATEWAY_TIMEOUT = 504;
    public const HTTP_VERSION_NOT_SUPPORTED = 505;
    public const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506;                        // RFC2295
    public const HTTP_INSUFFICIENT_STORAGE = 507;                                        // RFC4918
    public const HTTP_LOOP_DETECTED = 508;                                               // RFC5842
    public const HTTP_NOT_EXTENDED = 510;                                                // RFC2774
    public const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;                             // RFC6585

    /**
     * Status codes translation table.
     *
     * The list of codes is complete according to the
     * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry}
     * (last updated 2021-10-01).
     *
     * Unless otherwise noted, the status code is defined in RFC2616.
     *
     * @var array
     */
    public static $statusTexts = [
        100 => 'Continue',
        101 => 'Switching Protocols',
        102 => 'Processing',            // RFC2518
        103 => 'Early Hints',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        207 => 'Multi-Status',          // RFC4918
        208 => 'Already Reported',      // RFC5842
        226 => 'IM Used',               // RFC3229
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',
        308 => 'Permanent Redirect',    // RFC7238
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Content Too Large',                                           // RFC-ietf-httpbis-semantics
        414 => 'URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Range Not Satisfiable',
        417 => 'Expectation Failed',
        418 => 'I\'m a teapot',                                               // RFC2324
        421 => 'Misdirected Request',                                         // RFC7540
        422 => 'Unprocessable Content',                                       // RFC-ietf-httpbis-semantics
        423 => 'Locked',                                                      // RFC4918
        424 => 'Failed Dependency',                                           // RFC4918
        425 => 'Too Early',                                                   // RFC-ietf-httpbis-replay-04
        426 => 'Upgrade Required',                                            // RFC2817
        428 => 'Precondition Required',                                       // RFC6585
        429 => 'Too Many Requests',                                           // RFC6585
        431 => 'Request Header Fields Too Large',                             // RFC6585
        451 => 'Unavailable For Legal Reasons',                               // RFC7725
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates',                                     // RFC2295
        507 => 'Insufficient Storage',                                        // RFC4918
        508 => 'Loop Detected',                                               // RFC5842
        510 => 'Not Extended',                                                // RFC2774
        511 => 'Network Authentication Required',                             // RFC6585
    ];
Mail::send(new class extends \Illuminate\Mail\Mailable { public function build() { return $this->to('to@server.com') ->from('from@server.com') ->subject('subject') ->html('<h1>H1</h1>'); } })
{
"preset": "psr12",
"rules": {
"concat_space": {
"spacing": "one"
},
"simplified_null_return": false,
"braces": {
"allow_single_line_closure": false,
"allow_single_line_anonymous_class_with_empty_body": true,
"position_after_functions_and_oop_constructs": "next"
},
"class_definition": {
"space_before_parenthesis": false
},
"new_with_braces": {
"anonymous_class": true,
"named_class": true
},
"no_alternative_syntax": {
"fix_non_monolithic_code": true
},
"elseif": true,
"align_multiline_comment": {
"comment_type": "phpdocs_like"
},
"heredoc_to_nowdoc": true,
"no_binary_string": true,
"no_empty_phpdoc": true,
"no_empty_statement": true,
"indentation_type": true,
"no_closing_tag": true,
"no_singleline_whitespace_before_semicolons": true,
"object_operator_without_whitespace": true,
"no_superfluous_elseif": true,
"no_spaces_after_function_name": true,
"native_function_casing": true,
"native_function_type_declaration_casing": true,
"function_typehint_space": true,
"multiline_whitespace_before_semicolons": {
"strategy": "no_multi_line"
},
"backtick_to_shell_exec": true,
"return_assignment": true,
"array_indentation": true,
"blank_line_after_opening_tag": true,
"blank_line_after_namespace": true,
"assign_null_coalescing_to_coalesce_equal": true,
"full_opening_tag": true,
"explicit_string_variable": true,
"explicit_indirect_variable": true,
"fully_qualified_strict_types": true,
"use_arrow_functions": true,
"array_syntax": {
"syntax": "short"
},
"declare_parentheses": true,
"whitespace_after_comma_in_array": {
"ensure_single_space": true
},
"trim_array_spaces": true,
"method_argument_space": {
"on_multiline": "ensure_fully_multiline",
"after_heredoc": true,
"keep_multiple_spaces_after_comma": false
},
"function_declaration": {
"closure_function_spacing": "one"
},
"nullable_type_declaration_for_default_null_value": {
"use_nullable_type_declaration": true
},
"visibility_required": {
"elements": [
"const",
"method",
"property"
]
},
"php_unit_method_casing": {
"case": "camel_case"
},
"blank_line_before_statement": {
"statements":[
"break",
"case",
"continue",
"declare",
"default",
"do",
"exit",
"for",
"foreach",
"goto",
"if",
"include",
"include_once",
"phpdoc",
"require",
"require_once",
"return",
"switch",
"throw",
"try",
"while",
"yield",
"yield_from"
]
},
"no_extra_blank_lines": {
"tokens": [
"attribute",
"break",
"case",
"continue",
"curly_brace_block",
"default",
"extra",
"parenthesis_brace_block",
"return",
"square_brace_block",
"switch",
"throw",
"use",
"use_trait"
]
}
},
"notPath": [
"path/to/excluded-file.php"
],
"exclude": [
"_dev_dir",
"docker-envs"
],
"notName": [
"*-my-file.php",
"*_ide_helper.php",
"*_ide_*",
".phpstorm.meta.php"
],
"docs_links": [
"https://mlocati.github.io/php-cs-fixer-configurator",
"https://laravel.com/docs/pint#rules"
]
}
// Initial admin user
\App\Models\User::updateOrCreate(
    [
        'email' => 'admin@mail.com',
    ],
    [
        'name' => 'Admin',
        'email' => 'admin@mail.com',
        'password' => \Illuminate\Support\Facades\Hash::make('power@123'),
        'email_verified_at' => now(),
    ]
);
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $factoryCount = env('FACTORY_COUNT');
        $factoryCountCreate = is_numeric($factoryCount) && $factoryCount >= 1 ? (int) $factoryCount : 500;

        echo "Creating {$factoryCountCreate} records" . PHP_EOL;
        \App\Models\User::factory($factoryCountCreate)->create();
    }
}

Usage

FACTORY_COUNT=1500 php ./artisan db:seed --class=UserSeeder
<?php
// testar. Pra quse serve? Quando utilizar?
//Vi aqui: https://youtu.be/WNkNZbKsrH0?t=839
$this->withoutExceptionHandling();
?>
Fim dos snippets
"name": "spatie/invade",
"description": "A PHP 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 = new P2()
// = P2 {#11802}

// > $p->getNome()

//    Error  Call to protected method P2::getNome() from global scope.

// > invade($p)->getNome()
// = "Tiago"
### Table `table()`
/*
* //! Note:
* For seeders, use `$this->command->table`
* For command, use `$this->table`
*/

$this->command->table([], [
    ['Platform', PHP_OS],
    ['PHP', phpversion()],
    ['Laravel', app()->version()],
    ['spatie/ignition', \Composer\InstalledVersions::getVersion('spatie/ignition')],
    ['spatie/laravel-ignition', \Composer\InstalledVersions::getVersion('spatie/laravel-ignition')],
    ['spatie/flare-client-php', \Composer\InstalledVersions::getVersion('spatie/flare-client-php')],
    /** @phpstan-ignore-next-line */
    ['Curl', curl_version()['version'] ?? 'Unknown'],
    /** @phpstan-ignore-next-line */
    ['SSL', curl_version()['ssl_version'] ?? 'Unknown'],
]);

Table exists

// vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php ~ 158
app(\Illuminate\Database\Schema\Builder::class)->hasTable('users');
$faker = \fake('pt_BR');
fn (array $attributes) => User::find($attributes['user_id'])->type, //NOCOMMIT

Laravel Seeding: HasMany with Multiple Levels

$user = User::factory()
    ->has(Post::factory()->count(3))
    ->create();
public function run()
{
    Customer::factory(100)
        ->has(Order::factory(2))
            ->has(Product::factory(3))
                ->has(Ingredient::factory(5))
        ->create();
}

Note:

// If ProductPrice relation is 'productPrice', just run
Product::factory(1)->has(ProductPrice::factory(3))->create();

// But if has another name, like 'priceList', run this
Product::factory(1)->has(ProductPrice::factory(3), 'priceList')->create()
$user = User::factory()
    ->hasPosts(3)
    ->create();

// or
$user = User::factory()
    ->hasPosts(3, [
        'published' => false,
    ])
    ->create();
public function run(): void
{
    if (ProductSeller::count() <= 3) {
        ProductSeller::factory(6)->create();
    }

    Product::factory(30)
        // ->has(ProductPrice::factory(rand(1, 3)), 'priceList')
        ->create()
        ->each(
            fn(Product $product) => $product->priceList()->saveMany(
                ProductPrice::factory(rand(1, 3))->create()
            )
        );
}
$faker = \fake('pt_BR');
fn (array $attributes) => User::find($attributes['user_id'])->type, //NOCOMMIT

Laravel Seeding: HasMany with Multiple Levels

$user = User::factory()
    ->has(Post::factory()->count(3))
    ->create();
public function run()
{
    Customer::factory(100)
        ->has(Order::factory(2))
            ->has(Product::factory(3))
                ->has(Ingredient::factory(5))
        ->create();
}

Note:

// If ProductPrice relation is 'productPrice', just run
Product::factory(1)->has(ProductPrice::factory(3))->create();

// But if has another name, like 'priceList', run this
Product::factory(1)->has(ProductPrice::factory(3), 'priceList')->create()
$user = User::factory()
    ->hasPosts(3)
    ->create();

// or
$user = User::factory()
    ->hasPosts(3, [
        'published' => false,
    ])
    ->create();
public function run(): void
{
    if (ProductSeller::count() <= 3) {
        ProductSeller::factory(6)->create();
    }

    Product::factory(30)
        // ->has(ProductPrice::factory(rand(1, 3)), 'priceList')
        ->create()
        ->each(
            fn(Product $product) => $product->priceList()->saveMany(
                ProductPrice::factory(rand(1, 3))->create()
            )
        );
}
<?php
if (! function_exists('fake') && class_exists(\Faker\Factory::class)) {
/**
* Get a faker instance.
*
* @param ?string $locale
* @return \Faker\Generator
*/
function fake($locale = null)
{
$locale ??= app('config')->get('app.faker_locale') ?? 'en_US';
$abstract = \Faker\Generator::class.':'.$locale;
if (! app()->bound($abstract)) {
app()->singleton($abstract, fn () => \Faker\Factory::create($locale));
}
return app()->make($abstract);
}
}
<?php

namespace Database\Factories\Shop;

use App\Models\Shop\Product;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Database\Eloquent\Factories\Factory;
use Spatie\MediaLibrary\MediaCollections\Exceptions\UnreachableUrl;

/**
* @see https://github.com/filamentphp/demo/
*/
class ProductFactory extends Factory
{
    /**
     * @var string
     */
    protected $model = Product::class;

    public function definition(): array
    {
        return [
            'name' => $name = fake()?->unique()->catchPhrase(),
        ];
    }

    public function configure(): ProductFactory
    {
        return $this->afterCreating(function (Product $product) {
            try {
                $product
                    ->addMediaFromUrl(
                        DatabaseSeeder::getImageUrl(
                            provider: 'unsplash',
                            params: [
                                'w' => 200, // width/w
                                'height' => 200, // height/h
                                // any other params
                            ])
                    )
                    ->toMediaCollection('product-images');
            } catch (UnreachableUrl $exception) {
                return;
            }
        });
    }
}
class DatabaseSeeder extends Seeder
{
    public const IMAGE_PROVIDER_UNSPLASH = 'https://source.unsplash.com/random/#WIDTH#x#HEIGHT##PARAMS#';
    public const IMAGE_PROVIDER_PLACEHOLDER = 'https://via.placeholder.com/#WIDTH#x#HEIGHT#.#EXT##PARAMS#';

    public static function getImageUrl(
        ?string $provider = null,
        ?int $width = null,
        ?int $height = null,
        array $params = [],
    ) {
        $provider ??= 'placeholder';

        $width ??= $params['width'] ?? $params['w'] ?? 200;
        $height ??= $params['height'] ?? $params['h'] ?? 200;
        $withoutParams = boolval($params['withoutParams'] ?? $params['noParams'] ?? null);

        $providers = [
            'unsplash' => [
                'url' => static::IMAGE_PROVIDER_UNSPLASH,
                'defaultParams' => $withoutParams ? [] : [
                    'img' => 1,
                ],
            ],
            'placeholder' => [
                'url' => static::IMAGE_PROVIDER_PLACEHOLDER,
                'defaultParams' => $withoutParams ? [] : [
                    'text' => $params['text'] ?? sprintf('%sx%s', $width ?: '200', $height ?: '200'),
                ],
            ],
        ];

        $provider = $providers[$provider] ?? $providers['placeholder'] ?? [];

        $queryParams = http_build_query(
            array_merge(
                $provider['defaultParams'] ?? [],
                $params,
            )
        );

        $replacers = [
            '#EXT#' => $params['ext'] ?? 'png',
            '#TEXT#' => $params['text'] ?? sprintf('%sx%s', $width ?: '200', $height ?: '200'),
            '#WIDTH#' => $width ?: 200,
            '#HEIGHT#' => $height ?: 200,
            '#PARAMS#' => $withoutParams ? '' : '?' . $queryParams,
        ];

        $url = str_replace(
            array_keys($replacers),
            array_values($replacers),
            $provider['url'] ?? '',
        );

        return $url;
    }
}
<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Product extends Model implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;
}
<?php

/* ... */
// Sinapi.php
class Sinapi extends Model
{
    /* ... */
    protected $table = 'sinapi';

    protected $fillable = [
        'descricao',
        'codigo',
        'custo',
        'unidade_medida',
    ];

    /* ... */

    public function nbrGroup(): \Illuminate\Database\Eloquent\Relations\HasManyThrough
    {
        // select * from `nbr` inner join `sinapi_has_nbrs` on `sinapi_has_nbrs`.`codigo_nbr` = `nbr`.`codigo` where `sinapi_has_nbrs`.`codigo_sinapi` = ?
        return $this->hasManyThrough(
            Nbr::class,
            SinapiHasNbr::class,
            'codigo_sinapi',
            'codigo', // Nbr
            'codigo', // Sinapi
            'codigo_nbr',
        );
    }
}

/* ... */
// SinapiHasNbr.php
class SinapiHasNbr extends Model
{
    /* ... */
    protected $fillable = [
        'codigo_sinapi',
        'codigo_nbr',
        'descricao',
    ];
    /* ... */
}


class Nbr extends Model
{
    /* ... */
    protected $table = 'nbr';

    protected $fillable = [
        'descricao',
        'codigo',
    ];
}

Get table columns (Work with MySQL)

See: vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

// Work with MySQL

## GET TABLE NAME
$tableName = 'users';
// Or
// $tableName = (new User())->getTable();

## GET CONNECTION NAME
$connectionName = 'mysql';
// Or
// $connectionName = config('database.default');

## GET CONNECTION INSTANCE
$connection = DB::connection($connectionName); // Illuminate\Database\MySqlConnection
// Or
// $connection = (new User())->getConnection(); // Illuminate\Database\MySqlConnection

collect(
    $connection->select("DESCRIBE {$tableName}")
)->map(fn($item) => [
    'column' => $item->Field,
    'required' => $item->Null === 'NO',
])->toArray()


## SIMPLE WAY
$modelInstance = new User();
collect(
    $modelInstance->getConnection()
    ->select(
        "DESCRIBE {$modelInstance->getTable()}"
    )
)->map(fn($item) => [
    'column' => $item->Field,
    'required' => $item->Null === 'NO',
])->toArray()
<?php
try {
    \Illuminate\Support\Facades\Artisan::call('about', ['--json' => true]);

    return json_decode(\Illuminate\Support\Facades\Artisan::output(), true);
} catch (\Throwable $th) {
    \Log::error($th);
    return [
        'success' => false,
        'error' => $th->getMessage(),
    ];
}
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
class RedisHelper
{
/**
* Deleta registros do redis pelo pattern Ex: $pattern = '*user:*'
*
* @param string $pattern
* @param string $connection
*
* @return void
*/
public static function delRedisCacheByPattern(string $pattern, string $connection = 'cache'): void
{
try {
$getAll = Redis::connection($connection)->keys($pattern);
if (empty($getAll)) {
return;
}
foreach($getAll as $value) {
$keyArr = explode(':', $value);
Cache::forget(end($keyArr));
}
} catch (\Throwable $ex) {
report($ex);
}
}
}
$locale ??= app('config')->get('app.faker_locale') ?? 'en_US';

$abstract = \Faker\Generator::class.':'.$locale;

if (! app()->bound($abstract)) {
    app()->singleton($abstract, fn () => \Faker\Factory::create($locale));
}

return app()->make($abstract);
  • Regex que valida slug.
  • Letras minúsculas, números e hífen apenas.
  • 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:

$slug = "meu-slug";

if (preg_match('/^(?!-)(?!.*--)[a-z0-9-]+(?<!-)$/', $slug)) {
    echo "Slug válido!";
} else {
    echo "Slug inválido!";
}

Espero que isso ajude! Se você tiver alguma dúvida adicional, fique à vontade para perguntar.

Forms\Components\TextInput::make('slug')
->live(onBlur: true, debounce: 500)
->afterStateHydrated(
    fn($state, callable $set) => $set('slug', str($state)->trim()->slug())
)
->afterStateUpdated(
    fn($state, callable $set) => $set('slug', str($state)->trim()->slug())
)
->rules([
    function () {
        return function (string $attribute, $value, Closure $fail) {
            if (
                !preg_match(
                    '/^(?!-)(?!.*--)[a-z0-9\-]{2,100}(?<!-)$/',
                    $value
                )
            ) {
                $fail('The :attribute is invalid.');
            }
        };
    },
])
,
    /**
     * function userNumbers
     *
     * @param array $rawQueryToAppend
     * @param int $ttl
     * @param bool $clearCache
     *
     * @return User
     */
    public static function userNumbers(
        array $rawQueryToAppend = [],
        int $ttl = 120,
        bool $clearCache = false
    ): User {
        $rawQueryToAppend = \array_filter(\array_values($rawQueryToAppend), 'is_string');

        $query = [
            'count(*) as total',
            \sprintf(
                'SUM(CASE WHEN email_verified_at is null THEN 1 ELSE 0 END) as %s',
                'not_verified',
            ),
            \sprintf(
                'SUM(CASE WHEN email_verified_at is null THEN 0 ELSE 1 END) as %s',
                'total_verified',
            ),
            ...$rawQueryToAppend,
        ];

        // Campos NÃO nulos
        // select SUM(CASE WHEN email_verified_at is null THEN 0 ELSE 1 END) as not_verified from users;

        // Campos nulos
        // SUM(CASE WHEN email_verified_at is null THEN 1 ELSE 0 END) as not_verified

        $cacheKey = serialize($query);

        if ($clearCache) {
            Cache::forget($cacheKey);
        }

        return Cache::remember(
            $cacheKey,
            $ttl,
            fn () => User::select(
                \Illuminate\Support\Facades\DB::raw(\implode(',', $query))
            )->first()
        );
    }

    // Usage:
    // User::userNumbers()
    /**
     * function audioNumbers
     *
     * @param array $rawQueryToAppend
     * @param int $ttl
     * @param bool $clearCache
     *
     * @return Audio
     */
    public static function audioNumbers(
        array $rawQueryToAppend = [],
        int $ttl = 120,
        bool $clearCache = false
    ): Audio {
        $rawQueryToAppend = \array_filter(\array_values($rawQueryToAppend), 'is_string');

        $query = [
            'count(*) as total',
            \sprintf(
                'SUM(CASE WHEN status = %d THEN 1 ELSE 0 END) as %s',
                Audio::STATUS_STANDBY,
                'standby',
            ),
            \sprintf(
                'SUM(CASE WHEN status = %d THEN 1 ELSE 0 END) as %s',
                Audio::STATUS_AWAITING_MODERATION,
                'awaiting_moderation',
            ),
            \sprintf(
                'SUM(CASE WHEN status = %d THEN 1 ELSE 0 END) as %s',
                Audio::STATUS_DISAPPROVED,
                'disapproved',
            ),
            \sprintf(
                'SUM(CASE WHEN status = %d THEN 1 ELSE 0 END) as %s',
                Audio::STATUS_APPROVED,
                'approved',
            ),
            ...$rawQueryToAppend,
        ];

        $cacheKey = serialize($query);

        if ($clearCache) {
            Cache::forget($cacheKey);
        }

        return Cache::remember(
            $cacheKey,
            $ttl,
            fn () => Audio::select(
                \Illuminate\Support\Facades\DB::raw(\implode(',', $query))
            )->first()
        );
    }

    // Usage:
    // Audio::userNumbers()
  • In app/Providers/AppServiceProvider.php Add this lines:
    public function boot(): void
    {
       if (app()->isProduction()) {
            ($this->{'app'}['request'] ?? null)?->server?->set('HTTPS','on');
            \Illuminate\Support\Facades\URL::forceScheme('https');
        }
   }
<?php
//Usando Faker/Factory pra gerar valores fake
use Faker\Factory as Faker;
$faker = Faker::create();
foreach(range(1, 30) as $index) {
Employee::create([
'email' => $faker->email(),
'name' => $faker->sentence(5),
'description' => $faker->paragraph(6),
]);
}
//Para doc, usar no tinker 'doc $faker'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment