Tom Headifen
Tom Headifen

Reputation: 1996

How do I add a user_id to a polymorphic relationship?

I have a polymorphic relationship between Posts, Videos and Comments.

What I want to add is who made the relationship between the Posts/Comments or Videos/Comments. Essentially add a userId to the comments table.

Currently I have

user
    id - integer
    name - string

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string
    user_id - integer

I can not figure out how to use eloquent to achieve what I want. I have followed the docs and added the morph relationships as per the docs but I can't seem to find a way for the user_id to be saved into the comments table as well.

How do I use eloquent to also save the user_id each time the polymorphic relationship is created?

Upvotes: 1

Views: 635

Answers (3)

Casper
Casper

Reputation: 592

How do you create the Comment? If you do something like Comment::create(['user_id' => auth()->user->id]). Remeber to have added user_id to your fillable array on the Comment model.

Else you can use

$comment = new Comment();
$comment->user_id =  auth()->user->id;
$comment->save()
etc...

Upvotes: 0

Stoycho Trenchev
Stoycho Trenchev

Reputation: 555

In you controller for creating comments:

$newComment = new Comment;
...
$newComment->user_id = Auth::user()->id;
$newComment->save();

Upvotes: 0

user320487
user320487

Reputation:

You can use Model Events to set data on new records right before they are saved to the database. Within your Comment model, add the following method:

public static function boot() {
    parent::boot();
    static::creating(function($comment) {
        $comment->user_id = auth()->id();
    });
}

Upvotes: 1

Related Questions