laravel试图从控制器内部的模型中获取非对象的属性

时间:2018-07-09 03:28:48

标签: php laravel

因此,我正在尝试检查已通过身份验证的用户是否已经关注该用户,但是我收到此错误。

  

试图获取非对象的属性

     

如果($ followers-> user_id == auth()-> id()){                   返回true;               }

     

8“试图获取非对象的属性”   “ /Applications/MAMP/htdocs/elipost/app/MyFollow.php” 34

我不确定我是否在下面正确使用了此方法。

$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 (模型)

<?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;
    }


}

1 个答案:

答案 0 :(得分:3)

followedByMe错误地循环了一条记录。尝试以下更改:

public function followedByMe()
{
    return $this->follower->getKey() === auth()->id();
}

由于follower是一种belongsTo关系,因此它最多只会返回一条记录,而不会返回一个集合。

map函数还错误地在模型上使用数组访问。您不能在对象上使用['followedByMe']来访问属性,而需要像->中那样使用$myuser->followedByMe表示法。下面显示了如何使用地图功能:

$user = $users->map(function(User $myuser){
    return ['followedByMe' => $myuser->followers->count() == 0];
});

将返回类似于以下内容的数组:

[
    ['followedByMe' => true],
    ['followedByMe' => false],
    ['followedByMe' => true],
]