我有带字段的示例对象
name => John
surname => Dow
job => engineer
以及带有占位符的输出表单。有些需要,有些不需要。
检查是否需要它并用空字段显示错误的最佳实践是什么?
最佳答案
实际上,有多种方法可以在controller方法内部实现这一点,或者为我使用laravels请求类我更喜欢使用请求类
下面我将列举两个例子
在控制器方法内部验证
public function test(Request $request){
if($request->filled('name){
/*filled will check that name is set on the current
request and not empty*/
//Do your logic here
}
}
第二种方法是在控制器中使用验证器facade
use Validator;
class TestController{
public function test(Request $request){
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
/*continue with your logic here if the request failed on
validator test Laravel will automatically redirect back
with errors*/
}
}
第三条路我个人最喜欢的
可以使用此命令生成请求类
php artisan make:request AddBookRequest
它将在“app/http/requests/addbookrequest”下生成请求类,在任何生成的请求类中,您将发现两个方法authorize()和rules()
在authorized方法中,您必须返回truthy或falsy值,这将检测发出请求的当前用户是否有权在rules方法中触发此请求,您在验证程序中所做的与在第二种方式中所做的几乎相同检查示例
public function authorize(){
return true;
}
public function rules(){
return [
'title' => 'required|string',
'author_id' => 'required|integer'
];
}
然后在控制器中,您就可以使用这样生成的请求
use App\Http\Requests\AddBookRequest;
public function store(AddBookRequest $request){
/* do your logic here since we uses a request class if it fails
then redirect back with errors will be automatically returned*/
}
希望这有助于您在
https://laravel.com/docs/5.6/validation
关于php - 如何检查对象中的必填字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50784859/