Reputation: 1368
Hi I have the following database struture
User
has two type of users Artist
and Fans
and has two tables artists
and fans
to store the unique data
User model
public function artist()
{
return $this->hasOne('App\Artist');
}
public function fans()
{
return $this->hasOne('App\Fan');
}
There will be multiple Fans for Artists so I have created a pivot table to store the relations
Artist model
public function fans() {
return $this->belongsToMany('App\Fan');
}
Fan Model
public function artist() {
return $this->belongsToMany('App\Artist');
}
pivot table schema
Schema::create('artist_fan', function(Blueprint $table)
{
$table->increments('id');
$table->integer('artist_id')->unsigned();
$table->integer('fan_id')->unsigned();
//
});
I have used the following code but result is an empty Collection
$user = auth()->user();
dd($user->artist->fans);
output
Collection {#263 ▼
#items: []
}
Please help me to retrieve the fans of the current logged in Artist. Also doing CRUD operations to the pivot table.
Upvotes: 2
Views: 423
Reputation: 146191
You may try this:
$artists = \App\Artist::has('fans') // Artists who has fans
->with('fans') // load fans
->where('user_id', auth()->user()->id) // Where artist.user_id = logged in user id
->get(); // Get all artists
if($artists->count())
{
$fans = $artists->fans; // Get fans
}
Upvotes: 2