Blagoh
Blagoh

Reputation: 1235

Doing ->save to multiple relations

I am using Laravel 5.5.13.

I have a model called Thumb. This thumb is related to two things in a many-to-one relationship: Player and Comment.

I currently do things like this:

public function store(Request $request, Entity $entity, Player $player)
{
    $thumb = new Thumb($request->all());
    $thumb->player_id = $player->id;
    $entity->thumbs()->save($thumb);
    return response()->json($thumb, 201);
}

We see how I have to set $thumb->player_id AND I don't have to set the entity_id because I am doing $entity->thumbs()->save

Is there a way to do $entityAndPlayer->thumbs()->save? Or is the way I did it above the recommend way?

Upvotes: 0

Views: 524

Answers (2)

Andre Gusmao
Andre Gusmao

Reputation: 224

You can't save multiple relationships at once but, for many to one associations you can use the method associate() (Laravel docs) to save using the belongs to part of the relationship, for example:

public function store(Request $request, Entity $entity, Player $player)
{
    $thumb = new Thumb($request->all());
    $thumb = $thumb->save();

    $thumb->player()->associate($player);
    $thumb->entity()->associate($entity);

    return response()->json($thumb, 201);
}

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You cannot use relationships to set 2 foreign columns so they way you showed is the correct one. However you can make it a bit cleaner in my opinion.

Into Thumb model you could add:

public function setPlayer(Player $player) 
{
     $this->player_id = $player->id;
}

and then instead of:

$thumb->player_id = $player->id;

you could use:

$thumb->setPlayer($player);

Or you could add create setPlayerAttribute method and finally instead of:

$thumb = new Thumb($request->all());
$thumb->player_id = $player->id;

use just:

$thumb = new Thumb($request->all() + ['player' => $player]);

Upvotes: 1

Related Questions