Jamie Jamie - 2 months ago 17
PHP Question

Laravel relation

This is my relation:

App\Square\Topics\Topic::find(1)->subscriptions()->get();


And I receive this back:

>>> App\Square\Topics\Topic::find(1)->subscriptions()->get();
=> Illuminate\Database\Eloquent\Collection {#786
all: [
App\Square\Subscriptions\Subscription {#787
id: 1,
user_id: 1,
subscription_id: 1,
subscription_type: "App\Square\Topics\Topic",
created_at: "2016-10-03 16:08:31",
updated_at: "2016-10-03 16:08:31",
},
],
}


How would I get the user(s) of this relation?

Answer

To get the User of Subscriptions you may define this method in Subscription Model:

public function user()
{
    return $this->belongsTo(User::class);
}

This will allow you to call user as an attribute of a subscription object.

So, then you can write a foreach to get each user of the related subscriptions, like this:

$subscriptions = App\Square\Topics\Topic::find(1)->subscriptions()->get();
foreach ($subscriptions as $subscription) {
    $u = $subscription->user;
}

Hope this helps!