Search code examples
phplaraveleloquentpivot-tablelaravel-5.3

How to find all id pivot from pivot table? (laravel 5.3)


I have a pivot table. The name is users_banks table. The table have field id, user_id, bank_id, status, account_name and account_number

Now, the pivot have 3 records

I display contain from pivot table using code like this :

$user_id = auth()->user()->id;
$user = $this->user_repository->find($user_id);

$account = array();
foreach($user->banks as $bank) {
    $account[] = $bank;
}

dd($account);

The result display all record in the form of array. There exist value of field user_id, bank_id, status etc. But I don't find value of id

How can I find id from pivot table?


Solution

  • If the relationship is defined correctly you can use:

    $bank->pivot->id
    

    but make sure the user belongsToMany(Bank::class) and the bank belongsToMany(User::class) or else it wont work.