I have 2 table I want to post with a single form and create a comment at the same time. How can I do this in Laravel?
Posts table
| id | title | slug |
|---|---|---|
| 1 | Hello world | hello-world |
| 2 | O hi | o-hi |
Comments table
| id | post_id | body |
|---|---|---|
| 1 | 1 | Lorem ipsum |
| 2 | 2 | Lorem ipsum |
| 3 | 2 | Lorem ipsum second same post |
CodePudding user response:
I assume that you form looks like a post title input and post content input.
So in your Controller when you receive your Request containing the values of your form you can do something like the following :
$title = $request->title;
$body = $request->body;
// This line will only work if you imported your Eloquent model (use App\Models\Posts as an example)
$post = new Post;
$post->body = $body;
// For the slug just manipulate the string in order to have the desired output and do the same
$post->slug = $slug;
$post->save();
// Now get the id
$post_id = $post->id;
$comment = new Comment;
$comment->post_id = $post_id;
$comment->body = $body;
$comment->save();
