在 Laravel 中将请求输入值从空字符串更改为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38745580/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:14:51  来源:igfitidea点击:

Change request input values from empty string to null in Laravel

databaselaravelhttprequestjquery-select2

提问by ira

In my controller I receive an Illuminate\Http\RequestRequest that contains some data with values equal to an empty string:

在我的控制器中,我收到一个Illuminate\Http\Request请求,其中包含一些值等于空字符串的数据:

dd($request->input())

//output
array:5 [▼
  "_token" => "K43q88mR5zQRqVPAuYX5IWtQ1khQ24JTsuxl8mz4"
  "param1" => "1"
  "param2" => "2"
  "param3" => ""
  "param4" => ""
]

(basically that happens when the user had made no selections in the create form BUT due to frontend restrictions see here, I am not able to change the form of the Requestso that to exclude the empty string values from being sent to the server)

基本上,当用户在创建表单中没有选择但由于前端限制见here我无法更改请求的形式以便排除发送到服务器的空字符串值时会发生这种情况

The request input data is used to attach a relationships to models. For example:

请求输入数据用于将关系附加到模型。例如:

$book->authors()->attach($request->input('param1'));

The problem is that when the input value is equal to the empty string ""the above line throws a QueryException, since it tries to add a foreign key equal to ""to the pivot table.

问题是当输入值等于空字符串时"",上面的行抛出 a QueryException,因为它试图添加一个等于""数据透视表的外键。

On the other hand, I noticed that if the value is nullinstead of "", the attach()method is not executed and, thus, does not throws an Exception, neither updates the database, which is exactly the behavior I want, when the user made no selection in the input form.

另一方面,我注意到如果值是null而不是""attach()则不会执行该方法,因此不会抛出异常,也不会更新数据库,这正是我想要的行为,当用户没有在输入表单。

My question is how can I change the request values from ""to null?My first thought was to make a helper function that iterates over the request input array and replace "" with null and use it in the controller BUT it does not seems like a good idea for me, because this would not prevent possible unwanted validation errors, when using Form Request Validation.

我的问题是如何将请求值从 更改""null我的第一个想法是创建一个辅助函数来遍历请求输入数组并将 "" 替换为 null 并在控制器中使用它,但这对我来说似乎不是一个好主意,因为这不会阻止可能出现的不需要的验证错误,使用表单请求验证时。

Any ideas please ???

请问有什么想法吗???

Thank you in advance

先感谢您

回答by Jari Pekkala

NOTE: Laravel 5.4 now ships with this feature

注意:Laravel 5.4 现在附带此功能

https://laravel.com/docs/5.4/requests#input-trimming-and-normalization

https://laravel.com/docs/5.4/requests#input-trimming-and-normalization

For versions > 5.4 see answer below or just copy the official middlewares.

对于> 5.4 的版本,请参阅下面的答案或仅复制官方中间件。



HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.

HTTP 中间件提供了一种方便的机制来过滤进入应用程序的 HTTP 请求。

Make a middleware and assign it to the routes or controller's methods you want it to take place.

制作一个中间件并将其分配给您希望它发生的路由或控制器的方法。

Example:

例子:

class SanitizeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach ($request->input() as $key => $value) {
            if (empty($value)) {
                $request->request->set($key, null);
            }
        }

        return $next($request);
    }
}
Route::post('/users', function (Request $request) {

    dd($request->input());

})->middleware(SanitizeMiddleware::class);

回答by Wouter Van Damme

Can't you just check before you add an item to your pivot table?

您不能在将项目添加到数据透视表之前进行检查吗?

if(!empty($request->input('paramX'))){
    $book->authors()->attach($request->input('paramX'));
}