mirror of
https://github.com/10h30/Test-Laravel-Validation.git
synced 2026-06-05 15:07:56 +09:00
Task 2 - array validation
This commit is contained in:
@@ -33,3 +33,18 @@ Test method `test_simple_validation_rules()`.
|
||||
|
||||
---
|
||||
|
||||
## Task 2. Array Validation.
|
||||
|
||||
Imagine your form has fields as an array:
|
||||
|
||||
```
|
||||
<input name="profile[name]" ... />
|
||||
<input name="profile[email]" ... />
|
||||
```
|
||||
|
||||
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()`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
public function update(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
// TASK: imagine that in the Blade the fields are
|
||||
// <input name="profile[name]" ... />
|
||||
// <input name="profile[email]" ... />
|
||||
// Write validation rules, so both name and email are required
|
||||
]);
|
||||
|
||||
auth()->user()->update($request->profile ?? []);
|
||||
|
||||
return 'Success';
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user