Agil
Agil

Reputation: 396

3 relationships within each others for subscription

I have hashtags and users can subscribe them. here is what I did for subscription:

function hashtag(){
    return $this->belongsToMany('App\Hashtag');
}

And also there is user relationship in Subscription Model:

function user(){
    return $this->belongsToMany('App\User');
}

The user Model has subscribes which is supposed to give me the hashtags that the Authed user subscribes. Here it is:

function subscribes(){
    return $this->hasMany('App\Subscription');
}

Now with this code I tried to access the hashtags the Authed user subscribes here is the view code:

@foreach(Auth::user()->subscribes->hashtag as $tags)
    {{ $tags->name }}
@endforeach

What I think is that, laravel expects a relationship table here, called hashtag_subscription or something like that. Now I got a bit confused with these relationships. I highy prefer to get around this withput creating extra table, I feel like I can accomplish it without an extra table.

Tables are as following:user, hashtag, subscription
Models: Hashtag, Subscription, User

Upvotes: 0

Views: 25

Answers (1)

Nikola Gavric
Nikola Gavric

Reputation: 3543

You need to change your relationships first, because as I understood you one Subscription model has One-To-One relationship to both User and Hashtag:

function hashtag() {
    return $this->belongsTo('App\Hashtag');
}

function user() {
    return $this->belongsTo('App\User');
}

Then you can loop through user subscriptions and have access to both Hashtag and user to whom the initial user is subscribed to:

@foreach(Auth::user()->subscribes as $subs)
    {{ $subs->user->firstname }}
    {{ $subs->hashtag->name }}
@endforeach

Upvotes: 1

Related Questions