I'm learning laravel, but i've ran into a problem and i can't seem to get it right. I have two models :
Model 'Group' :
Schema::create('groups', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('name')->unique();
$table->text('description')->nullable();
$table->string('picture')->nullable();
$table->timestamps();
});
and model 'User' :
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password');
$table->timestamp('email_verified_at')->nullable();
$table->timestamps();
$table->rememberToken();
});
These models should have a many-to-many relationship, so i've created a pivot table named 'group_user' :
Schema::create('group_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('group_id')->unsigned();
$table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
Next i defined the many-to-many relationship :
In the 'Group' model :
public function members()
{
return $this->belongsToMany('App\User', 'group_user', 'group_id', 'user_id')->withTimestamps();
}
In the 'User' model :
public function groups() {
return $this->belongsToMany('App\Group', 'group_user', 'user_id', 'group_id')->withTimestamps();
}
In my database i have a pivot record, that links group 1 to user 1 :
+----+----------+---------+------------+------------+
| id | group_id | user_id | created_at | updated_at |
+----+----------+---------+------------+------------+
| 1 | 1 | 1 | NULL | NULL |
+----+----------+---------+------------+------------+
So far so good, but when i try to print the members of group 1 :
@foreach($group->members() as $user)
<p>{{ $user->first_name }}</p>
@endforeach
i get this error :
Trying to get property 'first_name' of non-object
When i print the user object like this
@foreach($group->members() as $user)
<p>{{ $user }}</p>
@endforeach
I get the result 1, which is the user_id of the member. Can anyone point out where i messed up? Been looking at it for hours, but i just can't see it. Thanks in advance!
$group->membersinstead of$group->members(). You are calling the relationship query, not the relationship Collection result - Christophe Hubert$group->membersand$group->members()->get()is. :) - D. Petrov$group->members()doesn't return an ID (it looks like an ID, but that's a false positive), it returns aBuilderinstance. And runningforeach({Builder} as $user)returnsfalse(ortrueI guess?), andfalsedoesn't have an attribute->first_name(hence the error).$group->members(without the()) is aCollection, which is compatible with aforeach(). - Tim Lewis