Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anshulmishra's avatar

Save data with eloquent relations

I am trying to save data with eloquent relationship.

I have following three tables: User Table, Category Table and Post Table.

Post Table

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->string('heading');
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories');
            $table->foreign('user_id')->references('id')->on('users');
    });

Relations:

Category:

    public function posts() {
        return $this->hasMany('App\Post');
    }

Post:

public function user() {
        return $this->belongsTo('App\User');
    }

public function category() {
        return $this->belongsTo('App\Category');
    }

User:

public function posts($category) {
        return $this->hasMany('App\Post');
    }

My Problem is that, how can I save post just by passing the Heading in create function. I want to use the relationship. As an example I want to use this kind of code:

$data = ['heading' => $heading];
$user->posts()->category()->create($data);
0 likes
3 replies
pmall's avatar
$user->posts()->category()->create($data);

This is a nonsense because $user->posts() represent many posts. You have to select a specific post then $post->category()->create($data);

DaveSari's avatar

hey @anshulmishra , what you are asking is already solved on the documentation.. this is a small copy paste of what it says,i am hoping it will be of use to you. ( the link to it is : https://laravel.com/docs/5.3/eloquent-relationships )

Inserting & Updating Related Models

The Save Method

Eloquent provides convenient methods for adding new models to relationships. For example, perhaps you need to insert a new Comment for a Post model. Instead of manually setting the post_id attribute on the Comment, you may insert the Comment directly from the relationship's save method:

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);

$post->comments()->save($comment);

anshulmishra's avatar

@pmall I know this is a nonsense. I have mentioned this as example that what kind of code I am looking.

I know this is not the answer that is why I have posted the question here. I am looking for a batter solution for this kind of relationship.

@DaveSari thanks for your answer, but the problem is that I want to play with the three relations.

I need to create a new post for a user in a particular category. For that I want to use the relationships so that I can create the post without passing the user_id and category_id in the create function.

Please or to participate in this conversation.