由於我們想防範使用我們API的使用者傳入惡意的參數或傳入我們預期中型態的參數,我們需要做好Request validation的防護
$ sail artisan make:request CreatePostRequest
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\PostService;
use App\Http\Requests\CreatePostRequest;
use Illuminate\Http\JsonResponse;
class PostController extends Controller
{
protected $service;
public function __construct(PostService $service)
{
$this->service = $service;
}
/**
* 建立文章
* @param CreatePostRequest $request
* @return JsonResponse
*/
public function create(CreatePostRequest $request): JsonResponse
{
$result = $this->service->create($request->all());
return response()->json($result);
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreatePostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|string|unique:posts',
'content' => 'required|string',
];
}
}
required可以替換為:
其它:
return [
'title' => 'required|string|unique:posts|max:10|min:2',
];
return [
'user_id' => 'required|integer|exists:user_id',
];
return [
'sort' => [
'required',
'string',
Rule::in(['asc', 'desc'])
],
];
return [
'sort' => [
'required|string|in:asc,desc',
],
];
return [
'start_at' => [
'required',
'date'
],
'end_at' => [
'required',
'date',
'after:start_at'
],
]
'email' => 'email:rfc,dns'