Laravel Relationships: Inserting & Updating Related Models

The Save Method

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);

$post->comments()->save($comment);
$post = App\Post::find(1);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

Recursively Saving Models & Relationships

$post = App\Post::find(1);

$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';

$post->push();

The Create Method

$post = App\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);
$post = App\Post::find(1);

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

Belongs To Relationships

$account = App\Account::find(10);

$user->account()->associate($account);

$user->save();
$user->account()->dissociate();

$user->save();

Many To Many Relationships

Laravel Relationships: Inserting & Updating Related Models — Structure map

Clickable & Draggable!

Laravel Relationships: Inserting & Updating Related Models — Related pages: