mardi 28 mars 2017

Laravel BelongsToMany Yielding Nothing

I'm trying to get the output of a belongstoMany relationship between users and sections database, which are tied to User and Section model, respectively.

User model has this method:

public function section()
    {
        return $this->belongsToMany('App\Models\Section','user_section')->withTimestamps();
    }

Section model has this method:

public function user()
    {
        return $this->belongsToMany('App\Models\User','user_section')->withTimestamps();
    }

My user_section table looks like this:

+----+---------+------------+------------+------------+
| id | user_id | section_id | created_at | updated_at |
+----+---------+------------+------------+------------+
|  1 |       1 |          1 | NULL       | NULL       |
|  2 |       2 |          1 | NULL       | NULL       |
+----+---------+------------+------------+------------+
2 rows in set (0.00 sec)

So why when I do this in the business logic:

$user = User::where("id",Auth::user()->id)->first(); //user with id of 1 in my case
return json_encode($user->section());

Do I get {} as output?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire