chrisgrim
6 months ago

Need Help pulling specific data from a Polymorphic Relationship

Posted 6 months ago by chrisgrim

0

I have successfully setup a Polymorphic relationship in Laravel. A user can favorite both events and categories. The issue I am having is using that information and pulling the events from it in my controller.

I have setup a method in my favorites controller where I am trying to display all the favorited events of a user. Use the code below I am able to see everything favorited by a specific user.

my favorite.php file

public function favorited()
    {
        return $this->morphTo();
    }

my event.php file

public function favorites() 
    {
        return $this->MorphMany(Favorite::class, 'favorited');
    }

my controller

  public function index(User $user)
    {   
        $favorites = Favorite::latest()->get();

        return view('favorites.index', compact('favorites'));
    }

this returns

[
{
"id": 20,
"user_id": 11,
"favorited_id": 3,
"favorited_type": "App\Event",
"created_at": "2019-03-28 00:29:07",
"updated_at": "2019-03-28 00:29:07"
},
{
"id": 2,
"user_id": 11,
"favorited_id": 1,
"favorited_type": "App\Event",
"created_at": "2019-03-21 21:51:56",
"updated_at": "2019-03-21 21:51:56"
},
{
"id": 3,
"user_id": 11,
"favorited_id": 2,
"favorited_type": "App\Event",
"created_at": "2019-03-21 21:51:56",
"updated_at": "2019-03-21 21:51:56"
}
]

This is exactly what I want however I am now stuck at the next step. How do I correlate the favorited_id with the event id so I can pass the event data for events 1, 2, and 3 to my blade file?

Thanks!

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