检查 POST 请求的字段是否为空的 Laravel 方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49486117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the Laravel way to check if the POST Request has a field left empty?
提问by Eazy Sam
The requirement was to update user roles. The role can be empty(left blank), one, or more than one as provided in the form field roles[]
.
要求是更新用户角色。角色可以为空(留空)、一个或多个,如表单字段中提供的roles[]
。
Here is the view form:
这是视图形式:
@foreach ($roles as $role)
<div class="checkbox">
<label><input name="roles[]" type="checkbox" value="{{$role->id}}" {{ $user->roles->contains($role->id) ? 'checked' : '' }}>{{$role->name}}</label>
</div>
@endforeach
The condition inside UserController::update()is:
UserController::update() 中的条件是:
if ($request->roles) {
// update user roles
}
Everything works fine except for one case. Sometimes the user has to stay without any role.
除了一种情况外,一切正常。有时用户不得不留下任何角色。
if($request->roles)
, isset($request->roles)
, and !empty($request->roles)
.. are all giving the same old fashioned reply(null
, ''
, true/flase
).
if($request->roles)
, isset($request->roles)
, 和!empty($request->roles)
.. 都给出了相同的老式回复( null
, ''
, true/flase
)。
Case: when there is one or more role(s) assigned:
案例:当分配了一个或多个角色时:
+request: ParameterBag {#41 ▼
#parameters: array:6 [▼
"_method" => "PUT"
"_token" => "a8oIPQFBMbhjanikX8v83qeOcfRE0N4UKTcTQDig"
"name" => "New User Name"
"email" => "[email protected]"
"password" => ""
"roles" => array:2 [▼
0 => "2"
1 => "3"
]
]
}
Case: when there no role assigned OR need to remove(detach) the previously assigned role:
案例:当没有分配角色或需要删除(分离)先前分配的角色时:
+request: ParameterBag {#41 ▼
#parameters: array:5 [▼
"_method" => "PUT"
"_token" => "a8oIPQFBMbhjanikX8v83qeOcfRE0N4UKTcTQDig"
"name" => "New User Name"
"email" => "[email protected]"
"password" => ""
]
}
So the question (requirement) is:
所以问题(要求)是:
How to differentiate when the field value of an HTML Post form has been submitted as empty(unchecked here) or if there was no such a field in the view form?Is there an eloquent* way in Laravel to find/list the form fileds from the Request
object?
如何区分 HTML Post 表单的字段值何时提交为空(此处未选中)或视图表单中是否没有这样的字段?Laravel 中是否有一种雄辩的* 方式来查找/列出Request
对象中的表单文件?
[PS: Trying another hidden field or do some frontend jQuery will not be appreciated]
[PS: 尝试另一个隐藏字段或做一些前端 jQuery 将不受欢迎]
采纳答案by Wreigh
You will need to identify this problem in the design of your application.
您将需要在应用程序设计中识别此问题。
How to differentiate when the field value of an HTML Post form has been submitted as empty(unchecked here) or if there was no such a field in the view form? Is there an eloquent* way in Laravel to find/list the form fileds from the Request object?
如何区分 HTML Post 表单的字段值何时提交为空(此处未选中)或视图表单中是否没有这样的字段?Laravel 中是否有一种雄辩的* 方式来查找/列出来自 Request 对象的表单?
When does that form should not have a roles[]
field? You should have a marker that will tell your application that this form doesn't have a roles[]
field.
该表单何时不应有roles[]
字段?您应该有一个标记来告诉您的应用程序此表单没有roles[]
字段。
Something like, when this form is used when an ordinary user is updating his/her profile, he/she will not be able to update his/her roles.
例如,当普通用户更新他/她的个人资料时使用此表单时,他/她将无法更新他/她的角色。
Because your problem is indeed the default behavior of forms, as answered in this question: Submit an HTML form with empty checkboxes
因为您的问题确实是表单的默认行为,如本问题所回答:Submit an HTML form with empty checkboxes
So there will be a different process for forms which DO NOT HAVEhave a roles field and different process for forms which DO HAVEa roles field.
于是就有了这形成了不同的过程不必有其形成的作用领域和不同的工艺确实有一个角色字段。
To add to your implementation, you can retrieve the roles field like this:
要添加到您的实现中,您可以像这样检索角色字段:
$roles = $request->input('roles', []);
After which you can just use sync
to the relationship method of your model.
之后,您可以使用sync
模型的关系方法。
$user->roles()->sync($roles);
回答by Asur
You can use the laravel request methods has()
or filled()
, has
checks if the parameter is present and filled
checks it's present andfilled:
您可以使用 laravel 请求方法has()
或filled()
,has
检查参数是否存在并filled
检查它是否存在和填充:
if ($request->has('roles')) {
//
}
or
或者
if ($request->filled('roles')) {
//
}
Check Laravel documentationfor further details on retrieving input from the request object.
查看Laravel 文档以获取有关从请求对象检索输入的更多详细信息。
EDIT
编辑
Since you are using Laravel 5.2 the following rules apply:
由于您使用的是 Laravel 5.2,因此适用以下规则:
- The
has()
method checks the parameter is present andfilled. - The
exists()
method checks the parameted is present.
- 该
has()
方法检查参数是否存在并填充。 - 该
exists()
方法检查参数是否存在。
Check the codeon the repo for more information.
查看repo 上的代码以获取更多信息。
回答by ka_lin
For this you have validations, seems that you need the roles
field to be required
and exists
(to map to a certain table)
为此,您有验证,似乎您需要该roles
字段为required
和exists
(映射到某个表)
You just need to make the validator via artisan command and inject it in the controller method, check out the docs.
您只需要通过 artisan 命令制作验证器并将其注入控制器方法中,查看文档。
ex:
php artisan make:request MyCustomRequest
Then you should have a request file under: App\Http\Requests
You need to set the validation rules as described above:
例如:
php artisan make:request MyCustomRequest
然后你应该有一个请求文件:App\Http\Requests
你需要设置验证规则,如上所述:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyCustomRequest 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 [
'rules' =>'required|exists:tour_roles_table,id'
];
}
}
Then you can use inject it in your desired method:
然后你可以在你想要的方法中使用它:
class UserController extends Controller {
[...]
public function update(MyCustomRequest $req)
{
[...]
//at this point validation was successfull, by default Laravel will redirect back with error messages, which can be customized in your request object
}
[...]
}
回答by Just L
try if(empty())
试试如果(空())
$check = request::get('roles');
if(empty($checkbox)){
//if checkbox have a empty value do ...
}else{
//if checkbox have not empty value do ..
}
for more information click http://php.net/manual/en/function.empty.php