Tim
Tim

Reputation: 7056

Laravel saving polymorphic model by request

I have a polymorphic relationship for Likes which can "like" both Videos and Posts. I am using an API endpoint to store the like.

However my LikeController looks like this

public function store(StoreLikeRequest $request)
{
    $video = Video::find($request->video);
    $result = (new StoreVideoLikeAction($video, $request))->handle();
    return $result;
}

My route is /api/like/store/

How can I change this function so that the StoreLikeRequest knows what Model (Post or Video) it is referring to automatically from my endpoint so that I can save it in the database? i.e. If I post a field called "post_ID" or "video_ID", or would a better option be to send an "id" field and a "type" (model) field to resolve this problem?

Or would I have to have multiple endpoints, i.e. /api/video/{video}/like? The same problem with this is that I would still need to work out what model we are currently using/saving in the StoreLikeRequest.

Ultimately, I wanted to avoid having a big if/switch statement based on what 'model type' is being sent in and I wondered if there is a simple 'laravel' way of achieving this.

Upvotes: 0

Views: 532

Answers (1)

MP-programming
MP-programming

Reputation: 86

This should help you understand the best way to do it:

https://laravel.com/docs/8.x/eloquent-relationships#one-to-many-polymorphic-relations

Upvotes: 1

Related Questions