현재 유효성 검사.

현재 유효성 검사.

<aside> 🧑‍💻

$reqeuset->validate()는 기본적인 유효성 검사 요청 객체단계

**Spring**으로 따지면 DTO단계의 유효성 검사.

Validation - Laravel 10.x - The PHP Framework For Web Artisans

서비스나 핸들러 단계의 유효성 검사가 필요한 것 같다.

</aside>

store 함수 수정


세부적인

public function store(Request $req)
{
    try {
        $req->validate([
            'text' => 'required|string|min:2|max:50|unique:todos,text'], [
            'text.required' => '내용을 입력해주세요!',
            'text.min' => '2자 이상 50자 이하여야 합니다!',
            'text.max' => '2자 이상 50자 이하여야 합니다!',
            'text.unique' => '중복된 내용입니다!',
        ]);

        Todo::create([
            'text' => $req->text,
            'completed' => false,
        ]);
        return redirect('/');
    } catch (Exception $e) {
        return redirect()->back()
            ->with('error', $e->getMessage());
    }
}
@if(session('error'))
    <script>
        alert('{{ session('error') }}');
    </script>
@endif

<aside> 🧑‍💻

try -catch, Exception을 이용하고, 각 예외처리마다 Message설정하여 뷰에 전달. alret창 띄우기

image.png

image.png

</aside>

Validator 파사드를 사용해 유효성 검사

Form Request 클래스 만들기

1. 생성 명령어

php artisan make:request TodoRequest

2. TodoFormRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class TodoFormRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'text' => [
                'required',
                'string',
                'min:2',
                'max:50',
                'unique:todos,text,' . ($this->route('id') ?? ''),
            ],
        ];
    }

    public function messages()
    {
        return [
            'text.required' => '내용을 입력해주세요!',
            'text.min' => '2자 이상 50자 이하여야 합니다!',
            'text.max' => '2자 이상 50자 이하여야 합니다!',
            'text.unique' => '중복된 내용입니다!',
        ];
    }
}

<aside> 🧑‍💻

이렇게 분리해서 관리할 수 있다.

</aside>