2 years ago

Need help with my polymorphic models

Posted 2 years ago by p0t4t0

Hello all

I have a polymorphic relationship set up with my Post and Comment models with Upvotes. Everything is fine except for I can't associate which user upvoted a Post or Comment.

here is my Upvotes table

public function up()
        Schema::create('upvotes', function (Blueprint $table) {

my Comment model

public function upvotes()
      return $this->morphMany('App\Upvote', 'upvoteable');

my Post model

public function upvotes()
      return $this->morphMany('App\Upvote', 'upvoteable');


Route::post('/post/{id}/upvote', '[email protected]')->name('post.upvote');

or I could probably get away with

Route::post('/post/upvote', '[email protected]')->name('post.upvote');

since I was after all going to do the upvoting via AJAX...

and lastly my PostUpvoteController

public function upvote(Request $request)
      $post= Post::findOrFail($request->id);
      $upvote = new Upvote;

      $post->upvotes()->save($upvote); // this is the part I can't figure out

      return response()->json([
        'upvoted' => // should return true or false depending on whether the user has already upvoted the post or not

$post->upvotes()->save($upvote) I can't figure out how to pass the $post->user->id into this save method. Should I be adding a user_id column to my Upvotes table so I can associate each upvote to a user? If so, how can I persist the $post->user->id into said column?

Please sign in or create an account to participate in this conversation.