Guest User

Untitled

a guest
Jun 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. When we create a blog, it belongs to a blog, but also a user. How to tidy things up.
  2.  
  3.  
  4.  
  5. ```php
  6. class PostsController extends Controller
  7. {
  8. public function store(Request $request, Topic $topic)
  9. {
  10. $topic->posts()->create([
  11. 'body' => 'Test body',
  12. 'user_id' => $request->user()->id
  13. ]);
  14. }
  15. }
  16. ```
  17.  
  18.  
  19. It works but the user is associated, but it makes more sense to use the following way
  20.  
  21. ```php
  22. class PostsController extends Controller
  23. {
  24. public function store(Request $request, Topic $topic)
  25. {
  26. $post = new Post($request->only(['body']));
  27. $post->user()->associate($request->user());
  28. $topic->posts->save($post):
  29. }
  30. }
  31. ```
Add Comment
Please, Sign In to add comment