Sreejith Sasidharan
Sreejith Sasidharan

Reputation: 1368

Laravel 5 - Many to many relations - Getting the pivot data

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

Answers (1)

The Alpha
The Alpha

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

Related Questions