Laravel saving mass assignment with a morphMany relation

北慕城南 提交于 2019-12-06 10:01:24

As often with SO questions, writing and formatting gave me some time to think..

$input = Input::all();
$contents = Input::get('content');
unset($input['content']);
$news = News::create($input);
foreach ($contents as $c) {
    $content = Content::create($c);
    $news->content()->save($content);
}
$news->save();

Works! But feels kinda hackish. Is there a more.. "Eloquent" way of mass assigning related models?

Edit: This probably is the generally correct course of action then - mass assignment won't handle relations, but at least I can mass assign each model individually.

I just need to juggle the input a bit, which I'll probably have to do anyway once validation gets added to the equation.

Edit2: Having lots of success moving the related model logic into that model, and keeping it simple, e.g:

$input = Input::all();
unset($input['content']);
$news = News::create($input);
$news = Content::updateAll($news, true);
$news->save();

for creating, and:

$input = Input::all();
unset($input['content']);
$news = News::find($id)->fill($input);
$news = Content::updateAll($news, false);
$news->save();

for updating.

The updateAll() method, for anyone interested:

public static function updateAll($model, $create = false) {
    $contents = Input::get('content');
    foreach ($contents as $k => $c) {
        // Save against parent model
        if ($create) {
            $content = Content::create($c);
        } else {
            $content = Content::find($k)->fill($c);             
        }
        $model->content()->save($content);
    }
    return $model;
}

Now I feel like I'm using full power!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!