laravel试图从控制器内的模型获取非对象的属性
So im trying to check if an authenticated user is already following the user, however im getting this error.
Trying to get property of non-object
if ($followers->user_id == auth()->id()){ return true; }
8 "Trying to get property of non-object" "/Applications/MAMP/htdocs/elipost/app/MyFollow.php" 34
I'm not sure if im using this method below properly.
$query->where('user_id', auth()->user()->id);
UserController.php
public function getProfile($user)
{
$users = User::with(['posts.likes' => function($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}, 'follow','follow.follower'])
->with(['followers' => function($query) {
$query->with('follow.followedByMe');
$query->where('user_id', auth()->user()->id);
}])->where('name','=', $user)->get();
$user = $users->map(function(User $myuser){
$myuser['followedByMe'] = $myuser->followers->count() == 0 ? false : true;
// $myuser['followedByMe'] = $myuser->followers->count() == 0 ? false : true;
dd($owl = $myuser['followedByMe']);
return $myuser;
});
User.php
public function follow()
{
return $this->hasMany('App\MyFollow');
}
MyFollow(model)
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
class MyFollow extends Model
{
use SoftDeletes, CanFollow, CanBeFollowed;
protected $fillable = [
'user_id',
'followable_id'
];
public $timestamps = false;
protected $table = 'followables';
public function follower()
{
return $this->belongsTo('App\User', 'followable_id');
}
public function followedByMe()
{
foreach($this->follower as $followers) {
if ($followers->user_id == auth()->id()){
return true;
}
}
return false;
}
}
followedByMe
is incorrectly looping a single record. Try the following changes:
public function followedByMe()
{
return $this->follower->getKey() === auth()->id();
}
Since follower
is a belongsTo
relationship, it will only return at most one record, not a collection.
The map
function is also incorrectly using array access on a model. You cannot use ['followedByMe']
on an object, to access a property you need to use ->
notation as in $myuser->followedByMe
. The following shows how to use the map function:
$user = $users->map(function(User $myuser){
return ['followedByMe' => $myuser->followers->count() == 0];
});
Which would return an array similar to:
[
['followedByMe' => true],
['followedByMe' => false],
['followedByMe' => true],
]