I have two migration tables and two models
1)User. 2)Subscription.
in subscriptions Model i write one method called user() which has hasMany
relationship and in Users model it will contain subscriptions() method which have belongs()
relationship.
in user table id acts as an primary key and in subscription table sub_id acts as a foriegn key,for example if the user subscribed to any subscription the user id will store in the sub_id in the subscription table upto this it's working fine.
$is_subscription=Subscription::where('sub_id',$user->id)->value('sub_id');
from the above code i am able to get the value but now what i want is is there any better way to write the query based on models ,please help me to write this one..
CodePudding user response:
According to your descriptions, I believe this is what you have:
class User extends Model
{
public function subscriptions()
{
return $this->hasMany(Subscription::class);
}
}
class Subscription extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
So you want to check whether an user has any subscriptions. You can do one of the followings:
$user->subscriptions()->exists();
// Or
$user->subscriptions->isNotEmpty();
CodePudding user response:
You can use pluck()
method:
$is_subscription=Subscription::where('sub_id',$user->id)->pluck('sub_id');
You can find details on the methods that are available for collection using the Laravel Documentation