4
votes

How would i make a single request to insert in multiple tables using laravel Eloquent ORM relationship .ie

Table 1 : users

  • id
  • name
  • email

Table 2 : posts

  • id
  • user_id
  • content

Table 3 : Image

  • id
  • user_id
  • post_id
  • image_name

relationship

  1. Table users id references user_id in other two tables .
  2. Table posts has One To Many relation with users.
  3. Table images has One To Many relation with users and post ie it can be shared with other users and on other posts.

So that when one makes a post insert ,it should insert the record in the tables with a single query.

1

1 Answers

2
votes

This is one way of doing it:

$post = (new Post)->fill($request->all()->toArray())->user()->associate(Auth::user())->save();

As for the image, the Post model should have a model event such as static::created to handle the image upload and manipulation.

Or to make more sense, a model event in the Post model should trigger another model event from the Image model.

->toArray() may be optional, I can't test it here where I'm now.