Modify request field value before saving in Larave

2019-04-14 20:23发布

I'm building app using laravel 5. I have such code:

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!

1条回答
贪生不怕死
2楼-- · 2019-04-14 21:09

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.

UPDATE: I previously had two methods, one of this no longer works as of Laravel 5.1 (thanks @omarjebary). Updated answer.

查看更多
登录 后发表回答