Reputation: 99
I'm trying to store the following incoming data into the DB, and it is successfully stored except one thing.
As I type : $request->user()->posts()->save($answer);
, everything is saved fine except the post_id
.
And if I replace it with : $post->answers()->save($answer);
, everything is saved fine except the user_id
.
How do I edit the save() method to save both ?
Code from the controller :
public function postAnswer(Request $request, $post_id)
{
$post = Post::where('id', $post_id)->first();
$body = $request['body'];
$pros = $request['pros'];
$cons = $request['cons'];
$answer = new Answer();
$answer->body = $body;
$answer->pros = $pros;
$answer->cons = $cons;
$post->answers()->save($answer);
Upvotes: 0
Views: 54
Reputation: 13620
You're trying to save two relationships at one time. AFAIK, that won't work.
You'll need to save the post to the user first, then save the answer to the post.
$request->user()->posts()->save($post);
$post->answers()->save($answer);
UPDATE
OP needs the user_id
saved within the answers
table, so we need to save that relationship as well. With the two lines of code above, $answer
doesn't know anything about the user, just the parent $post
-- so we have to explicitly tell $answer
that it belongs to the user
:
$request->user()->answers()->save($answer);
Upvotes: 1
Reputation:
You may have to add this to your models:
Post.php:
protected $fillable = [
...
'post_id',
...
];
Or the necessary fields, good luck.
Upvotes: 0