PHP code example of baconfy / factory-payload
1. Go to this page and download the library: Download baconfy/factory-payload library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
baconfy / factory-payload example snippets
$response = $this->postJson(route('posts.store'), [
'title' => fake()->sentence(),
'body' => fake()->paragraph(),
]);
$response = $this->postJson(route('posts.store'), Post::factory()->payload());
$response = $this->postJson(
route('posts.store'),
Post::factory()->payload(['title' => ''])
);
$response->assertJsonValidationErrors(['title']);
namespace Database\Factories;
use App\Models\Post;
use Baconfy\FactoryPayload\Attributes\PayloadAttributes;
use Illuminate\Database\Eloquent\Factories\Factory;
#[PayloadAttributes('title', 'body')]
class PostFactory extends Factory
{
protected $model = Post::class;
public function definition(): array
{
return [
'title' => fake()->sentence(),
'body' => fake()->paragraph(),
'user_id' => User::factory(),
'published_at' => now(),
];
}
}
namespace Database\Factories;
use App\Models\Post;
use Baconfy\FactoryPayload\HasPayloadAttributes;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
use HasPayloadAttributes;
protected $model = Post::class;
/**
* @var array<int, string>
*/
protected array $payloadAttributes = ['title', 'body'];
public function definition(): array
{
return [
'title' => fake()->sentence(),
'body' => fake()->paragraph(),
'user_id' => User::factory(),
'published_at' => now(),
];
}
}
$payload = Post::factory()->payload();
// ['title' => 'Lorem ipsum...', 'body' => 'Dolor sit amet...']
namespace App\Data;
class PostCreateData
{
public static function keys(): array
{
return ['title', 'body'];
}
}
$payload = Post::factory()->payload(PostCreateData::class);
// ['title' => 'Lorem ipsum...', 'body' => 'Dolor sit amet...']
class PostUpdateData
{
public ?string $title = null;
public ?string $body = null;
}
$payload = Post::factory()->payload(PostUpdateData::class);
// ['title' => '...', 'body' => '...']
it('rejects invalid post payloads', function (array $overrides, string $errorField): void {
$response = $this->postJson(
route('posts.store'),
Post::factory()->payload($overrides)
);
$response->assertStatus(422)->assertJsonValidationErrors([$errorField]);
})->with([
'missing title' => [['title' => ''], 'title'],
'missing body' => [['body' => ''], 'body'],
'title too long' => [['title' => str_repeat('a', 300)], 'title'],
]);