Criar um ambiente de testes é importante. Nesses casos, criamos dados falsos para atestar funcionalidades no nosso sistema.
Crie o model e a migration normalmente:
php artisan make:model Product -m |
Com esse código na migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration {
/** * Run the migrations.
* * @return void */
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/** * Reverse the migrations. * *
@return void */
public function down() {
Schema::dropIfExists('products');
}
}
|
E no terminal execute:
Crie uma factory
php artisan make:factory ProductFactory --model=Product |
Com o código:
<?php
namespace Database\Factories;
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ProductFactory extends Factory {
/** * The name of the factory's corresponding model.
* * @var string */
protected $model = Product::class;
/** * Define the model's default state.
* * @return array */
public function definition() {
return [
'name' => $this->faker->name,
'detail' => $this->faker->text,
]; }
}
|
Corrija as classes do projeto
Execute o tinker
php artisan tinker
Product::factory()->count(10)->create()
|
Basicamente a função tinker vai usar a factory para criar os dados falsos em 10 linhas da tabela products, usando o Faker.
Mais informações em https://github.com/fzaninotto/Faker.
Fabrício Dias de Oliveira