2

I am trying to get data from pivot table(I have a third column). but it returns empty array. When I do dd() I get this

Collection {#323 ▼
  #items: []
}

$a = new Subject();
$authorized_users = $a->users()->get(['auth_teacher']);

models

Subject

public function users()
{
    return $this->belongsToMany('App\User')->withPivot('auth_teacher')->withTimestamps();
}

User

public function subjects()
{
    return $this->belongsToMany('App\Subject')->withPivot('auth_teacher')->withTimestamps();
}   

EDIT: Wrongly written column name. I change it to correctly but the string is still empty

2
  • I can't understand why you're trying to fetch a subject_id from a Subject model, can you please elaborate your question properly! Commented Dec 6, 2016 at 13:36
  • here I corrected it(it isn't subject_id it was auth_teacher Commented Dec 6, 2016 at 13:47

2 Answers 2

3

Just use the pivot relationship on the model.

$a = Subject::find(1);
foreach ($a->users as $user) {
    echo $user->pivot->auth_teacher;
}

https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

In the documentation look for "Retrieving Intermediate Table Columns"

Sign up to request clarification or add additional context in comments.

1 Comment

No I'm trying to get third column from pivot table(there are keys and third custom boolean column. I need the third one). I know how to get specific users or subjects(i wrote wrong column name)
0

Try below code:

$a = new Subject();
$authorized_users = $a->users()->find(['subject_id']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.