14、Laravel 11 表单数据验证
我们完成了所有的功能,但是把最为重要的东西忽略了,那就是数据验证。本篇文章我们使用两种方式对数据进行验证。
控制器验证数据
1、添加验证
app/Http/Controllers/PostController.php
...
public function store(Request $request)
{
// 表单数据验证
$request->validate([
'title' => ['required'],
'text' => ['required'],
'category_id' => ['required'],
]);
Post::create([
'title' => $request->input('title'),
'text' => $request->input('text'),
'category_id' => $request->input('category_id'),
]);
return redirect()->route('posts.index');
}
2、显示错误信息
resources/views/posts/create.blade.php
...
<div class="p-6 text-gray-900">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</div>
...
Form Request 验证
1、创建验证
$ php artisan make:request StoreCategoryRequest
编写验证规则
app/Http/Requests/StoreCategoryRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreCategoryRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => ['required'],
];
}
}
2、使用验证
app/Http/Controllers/CategoryController.php
use App\Http\Requests\StoreCategoryRequest;
...
public function store(StoreCategoryRequest $request)
{
Category::create([
'name' => $request->input('name'),
]);
return redirect()->route('categories.index');
}
3、显示错误信息
resources/views/categories/edit.blade.php
...
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</div>
...
请登录后再评论