Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

Fetch pivot data laravel

class User extends Eloquent
{
    public function Account() { return $this->hasOne('Account', 'user_id'); }
    public function AccountRoles() { return $this->belongsToMany('Role', 'account_role')->withPivot('account_id')->withTimestamps(); }
    public function Roles() { return $this->belongsToMany('Role', 'role_user')->withTimestamps(); }
}
    
class Account extends Eloquent
{
    public function User() { return $this->belongsTo('User', 'user_id'); }
    public function AccountRoles() { return $this->belongsToMany('Role', 'account_role')->withPivot('user_id')->withTimestamps(); }
}
    
class AccountRole extends Eloquent
{
    public function Account() { return $this->belongsTo('Account', 'account_id'); }
}


////////////////////////////////////////////////////////////////////////

$user = User::find(1);

foreach($user->AccountRoles as $account_role)
{
    echo 'Account ID: ' . $account_role->pivot->account_id . '<br/>'; // Correctly spits out the account_id
    echo 'Role: ' . $account_role->role_name . '<br/>'; // correctly spits out the role name
}
Source by laravel.io #
 
PREVIOUS NEXT
Tagged: #Fetch #pivot #data #laravel
ADD COMMENT
Topic
Name
5+3 =