Reputation: 2415
I have a User model and a Friend Model. In User model I have
public function friends(){
return $this->hasMany('App\FacebookModels\Friend' ,'user_id');
}
and in Friend model I have
public function user(){
return $this->belongsTo('App\User' , 'user_id');
}
I want to retrieve user's followers and this is what I am trying
public function listFollowers($id,$name){
//user_id = 1 and there are two rows in table friends for user_id 1
$user_id = $_SERVER['REQUEST_URI'];
$user_id = preg_replace("/[^0-9]/","",$user_id);
$followers = Friend::where('user_id',$user_id)->get();
foreach($followers->user as $user){
echo $user->name;
}
}
but I get the following error.
ErrorException in FacebookPagesController.php line 65:
Undefined property: Illuminate\Database\Eloquent\Collection::$user
Line number 65
is
foreach($followers->user as $user)
but when I change the get()
to first()
I get the following error
ErrorException in FacebookPagesController.php line 66:
Trying to get property of non-object
line number 66 is
echo $user->name;
However, this works with first()
echo $followers->user->name;
I am not able to understand the difference of this and why this is not working. If you can explain it that would be great for most of the people.
This is my friends table
Schema::create('friends', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('follower')->unsinged();
$table->timestamps();
});
and this is users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
Upvotes: 1
Views: 1396
Reputation: 366
first()
returns a model instance while get()
returns a collection of models.
So, if you want to use first()
you should use the getAttribute
method to get properties/attributes from your $user
.
Example:
$name = $user->getAttribute('name');
Upvotes: 2