mardi 13 février 2018

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();



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire