acharmat
acharmat

Reputation: 125

how to CRUD using Polymorphic Relations in laravel?

I have 2 types of post : simple post and blog articles and I want to relate it to comments via Polymorphic Relations

this is my models :

// Comment Model 
public function commentable()
{
    return $this->morphTo();
}

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


//Article and Simple post Model 

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

public function comments()
{
    return $this->morphMany('App\Comment', 'commentable');
}

Ehat's the best way to use create comment and store the correct value of the Class name of each type in commentable_type and the id

    $comment = Auth::User()->comment();
    $comment->content = $request->input('content');
    $comment->commentable_id = $request->input(?);
    $comment->commentable_type = $request->input(?);
    $comment->save();

Upvotes: 0

Views: 1773

Answers (1)

yazfield
yazfield

Reputation: 1283

Preferably, you should create the Comment through the comentable Model (i.e: Post, SimplePost) check the docs:

$comment = new App\Comment(['content' => $request->input('content')]);
$post = Post::find($request->input('post_id'));
$post->comments()->save($comment);

Upvotes: 1

Related Questions