在 Laravel 5 中保存之前修改请求字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28995111/
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
Modify request field value before saving in Laravel 5
提问by SomethingElse
I'm building app using laravel 5. I have such code:
我正在使用 laravel 5 构建应用程序。我有这样的代码:
public function store(ArticlesRequest $request, Pages $page)
{
$parentSlug = Pages::getParentSlug($request->parent_id);
$slug = ($request->slug)? $request->slug:$request->generic_title;
$validSlug = $request->makeSlug($slug);
$request->slug = $validSlug;
$page->create($request->all());
}
I want to update some data before saving, like slug, in this case , but it's not saving a slug field, if I directly don't input from form field. How can I update $request containing element values? For example $request->slug = $validSlug; and it save my edited slug in DB. Thank you very much!
我想在保存之前更新一些数据,例如 slug,在这种情况下,但它不会保存 slug 字段,如果我不直接从表单字段输入。如何更新包含元素值的 $request?例如 $request->slug = $validSlug; 并将我编辑的 slug 保存在数据库中。非常感谢!
回答by jszobody
You can manage request values like this:
您可以像这样管理请求值:
$request->offsetSet('slug', $validSlug);
However I agree with the comment above, it would be far better to manage a default value inside your Pages model.
但是我同意上面的评论,最好在 Pages 模型中管理一个默认值。
UPDATE:I previously had two methods, one of this no longer works as of Laravel 5.1 (thanks @omarjebary). Updated answer.
更新:我以前有两种方法,其中一种从 Laravel 5.1 开始不再有效(感谢 @omarjebary)。更新了答案。