Laravel: Validation の使い方

<ol>

<li>プロジェクトの作成</li>

```bash
laravel new validation
```

<li>routes/web.php の編集</li>

```php:routes/web.php
（省略）
（最後に加える）
Route::get('register','App\Http\Controllers\RegisterController@index');
Route::post('register','App\Http\Controllers\RegisterController@post');
```

<li>Controller の作成</li>

```bash
php artisan make:controller RegisterController
```

>app/Http/Controllers/RegisterController.php が出来ます。

<li>Route の確認</li>

```bash
php artisan route:list
```

```text
$ php artisan route:list

  GET|HEAD   / ............................................................... 
  POST       _ignition/execute-solution ignition.executeSolution › Spatie\Lar…
  GET|HEAD   _ignition/health-check ignition.healthCheck › Spatie\LaravelIgni…
  POST       _ignition/update-config ignition.updateConfig › Spatie\LaravelIg…
  GET|HEAD   api/user ........................................................ 
  GET|HEAD   register ............................... RegisterController@index
  POST       register ................................ RegisterController@post
  GET|HEAD   sanctum/csrf-cookie sanctum.csrf-cookie › Laravel\Sanctum › Csrf…

                                                            Showing [8] routes
```

<li>app/Http/Controllers/RegisterController.php  の編集</li>

```php:app/Http/Controllers/RegisterController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RegisterController extends Controller
{
	  public function index(Request $request)
	  {
		  error_log('*** RegisterController index ***');

		  error_log(var_export($request->data,true));

    return view('register.index',['msg'=>'フォームを入力:']);
    //
	  }

	  public function post(Request $request)
	  {
		  $validate_rule = [
			  'name' => 'required',
			  'mail' => 'required|email',
			  'password' => 'required|min:1|max:50',
			  'password_confirmation' => 'required|min:1|max:50',
			  'age' => 'numeric|between:0,150',
		  ];
		  $this->validate($request, $validate_rule);
		  return view('register.index',['msg'=>'正しく入力されました。!']);
	  }
}
```

<li>resources/views/register/index.blade.php の作成</li>

```bash
mkdir resources/views/register
```

```php:resources/views/register/index.blade.php
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>バリデーション</title>
</head>
<body>
<h2>バリデーション</h2>
@section('content')
<p>{{$msg}}</p>
@if (count($errors) > 0)
<div>
	<ul>
		@foreach ($errors->all() as $error)
			<li>{{ $error }}</li>
		@endforeach
	</ul>
</div>
@endif
<table>
<form action="/register" method="post">
{{ csrf_field() }}
<tr><th>利用者名: </th><td><input type="text" name="name"
	value="{{old('name')}}"</td></tr>
<tr><th>メールアドレス: </th><td><input type="text" name="mail"
	value="{{old('mail')}}"</td></tr>
<tr><th>password: </th><td><input type="text" name="password"
	value="{{old('password')}}"</td></tr>
<tr><th>password(確認): </th><td><input type="text" name="password_confirmation"
	value="{{old('password_confirmation')}}"</td></tr>
<tr><th>利用可能端末数: </th><td><input type="text" name="age"
	value="{{old('age')}}"</td></tr>
<tr><th></th><td><input type="submit"
	value="send"></td></tr>
</form>
</table>	
	@show
<p>Dec/29/2023</p>
</body>
</html>
```

<li>サーバーの起動</li>

```bash
php artisan serve
```

<li>ブラウザーで、　http://localhost:8000/register　にアクセス</li>

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/98798d01-5f05-75f1-50d9-6b50d4b1c39a.png)


エラーがあった時の表示

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/0fe6cde8-e1b1-5f30-9167-c2472873db08.png)

</ol>

## PHPUnitテスト

こちらのページを参考にしました。
[PHPUnitテストでPOST送信テスト](https://mutimutisan.com/phpunit-test)

<ol>

<li>tests/Feature/ExampleTest.php を編集</li>

```php:tests/Feature/ExampleTest.php
<?php

namespace Tests\Feature;

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

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function test_example()
    {
	$response = $this->get('/')->assertStatus(200);
	$response = $this->get('/register')->assertOk();
	$response = $this->get('/hoge')->assertStatus(404);
	$response = $this->get('/register')
		 ->assertStatus(200)
		 ->assertSeeText('利用者名')
		 ->assertSee("メールアドレス")
		 ->assertSee('form');
    }

	public function testPostTest()
	{
	$response = $this->post('/register' ,[
	'name' => 'test',
	'mail' => 'test555@gmail.com',
	'password' => '11111111',
	'password_confirmation' => '11111111',
	]);

	$response->assertStatus(200);

}
}
```

<li>テストを実行</li>

```bash
vendor/bin/phpunit
```

```text
$ vendor/bin/phpunit 
PHPUnit 10.5.5 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.2.10-2ubuntu1
Configuration: /home/uchida/tmp/dec29/validation/phpunit.xml

.*** RegisterController index ***
NULL
*** RegisterController index ***
NULL
..                                                                 3 / 3 (100%)

Time: 00:00.123, Memory: 26.00 MB

OK (3 tests, 9 assertions)
```

</ol>

## 確認したバージョン

```text
$ php --version
PHP 8.2.10-2ubuntu1 (cli) (built: Sep  5 2023 14:37:47) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.10-2ubuntu1, Copyright (c), by Zend Technologies

$ php artisan --version
Laravel Framework 10.39.0
```