diff --git a/README.md b/README.md index 408a63f..5f5d63e 100644 --- a/README.md +++ b/README.md @@ -33,3 +33,18 @@ Test method `test_simple_validation_rules()`. --- +## Task 2. Array Validation. + +Imagine your form has fields as an array: + +``` + + +``` + +In `app/Http/Controllers/ProfileController.php` file, the `update()` method need validation rules: profile[name] and profile[email] fields should be required. + +Test method `test_array_validation()`. + +--- + diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php new file mode 100644 index 0000000..bb6bab3 --- /dev/null +++ b/app/Http/Controllers/ProfileController.php @@ -0,0 +1,22 @@ +validate([ + // TASK: imagine that in the Blade the fields are + // + // + // Write validation rules, so both name and email are required + ]); + + auth()->user()->update($request->profile ?? []); + + return 'Success'; + } +} diff --git a/routes/web.php b/routes/web.php index 0e282ed..74900d4 100644 --- a/routes/web.php +++ b/routes/web.php @@ -14,6 +14,7 @@ use Illuminate\Support\Facades\Route; */ Route::post('posts', [\App\Http\Controllers\PostController::class, 'store']); +Route::post('profile', [\App\Http\Controllers\ProfileController::class, 'update'])->middleware('auth'); Route::get('/', function () { return view('welcome'); diff --git a/tests/Feature/ValidationTest.php b/tests/Feature/ValidationTest.php index aab4c9c..3a9c647 100644 --- a/tests/Feature/ValidationTest.php +++ b/tests/Feature/ValidationTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature; +use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; @@ -23,4 +24,22 @@ class ValidationTest extends TestCase $response = $this->post('posts', ['title' => 'Some title']); $response->assertSessionHasErrors('title')->assertStatus(302); } + + public function test_array_validation() + { + $user = User::factory()->create(); + + // Post without name and email should fail + $response = $this->actingAs($user)->post('profile'); + $response->assertStatus(302); + + // Post with name and email should succeed + $response = $this->actingAs($user)->post('profile', [ + 'profile' => [ + 'name' => 'Some name', + 'email' => 'some@email.com' + ] + ]); + $response->assertStatus(200); + } }