In this question the accepted answer to saving related models was:
public function store(Request $request) { $player->name = $request->input('name'); $player->lastname = $request->input('lastname'); $player->stats = [ 'position' => $request->input('stats.position'), 'profile' => $request->input('stats.profile'), ]; $player->save(); return response()->json($player); }
Whenever I try this I get an error:
Column not found: 1054 Unknown column ‘stats’ in ‘field list’
If I add stats to the guarded collection, it of course never comes in.
On my player object I have this:
public function stats(): HasMany { return $this->hasMany(Stat::class); }
So how can I have my stats come in, but elqoquent not attempt to use ‘stats’ as a column name in the insert?
Advertisement
Answer
Using the save()
method, you can create a new Player
object and save it, and then create a new Stat
object and save it as a Player
related stats()
:
$player = new Player $player->name = $request->input('name'); $player->lastname = $request->input('lastname'); $player->save(); $stat = new Stat([ 'position' => $request->input('stats.position'), 'profile' => $request->input('stats.profile'), ]); $player->stats()->save($stat);