【问题标题】:Trying to get property of non-object Laravel 5.3, profile.blade.php.试图获取非对象 Laravel 5.3 profile.blade.php 的属性。
【发布时间】:2017-05-01 18:13:04
【问题描述】:

我正在尝试显示已登录的用户个人资料信息,我有两个表,一个是消息,另一个是用户,当用户登录时,它会看到他\她的个人资料,但是有一个错误。

profile.blade:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                Name
            </th>
            <th>
                Email
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach($users as $usr)
        <tr>
            <td>
                {{$usr->name}}
            </td>
            <td>
                {{$usr->email}}
            </td>
        </tr>
        @endforeach
    </tbody>

控制器:

public function GetUserInfo($id){
    $user = DB::table('users')
        ->join('messages', 'messages.user_id', '=', 'users.id')
        ->where('users.id', '=', $id)
        ->get();
    if($user->count()){
        $user = $user->first();
        return view('profile')->with('users',$user);
    }
}

型号:

    class Messages extends Model
{
    protected $table = 'messages';
    protected $fillable = [
        'message','user_id'
    ];

    public function user()
    {
        return $this->hasOne('App\User', 'id', 'user_id');
    }
}

【问题讨论】:

  • 刀片文件中的$users不应该是@foreach循环头部的$user吗?
  • 您的代码和问题陈述没有传达您的要求!!你能解释一下你想用它做什么吗!!!所以我可以建议你一个更好的方法来做到这一点。
  • 用户(id)的主键是消息(user_id)中的外键,消息的一个控制器我通过关系和连接从用户表中获取用户信息。

标签: php laravel-5


【解决方案1】:

以这种方式向视图传递数据时,users 应该是一个数组。

像这样改变你的控制器:

public function GetUserInfo($id){
    $user = DB::table('users')
        ->join('messages', 'messages.user_id', '=', 'users.id')
        ->where('users.id', '=', $id)
        ->get()->toArray();
    if($user->count()){
        $user = $user->first();
        return view('profile')->with('users',$user);
    }
}

以及您的个人资料刀片视图:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                Name
            </th>
            <th>
                Email
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach($users as $usr)
        <tr>
            <td>
                {{$usr['name']}}
            </td>
            <td>
                {{$usr['email']}}
            </td>
        </tr>
        @endforeach
    </tbody>

【讨论】:

    【解决方案2】:

        if($user->count()){
            $user = $user->first();
            return view('profile')->with('users',$user);
        }
    

    first() 在查询中被调用,但 $user 在进入 if 语句时已经作为 Laravel 集合存在。它应该以对象或数组的形式存在,您可以这样访问它。像

    if($user->count()){
            $user = $user[0]; /*OR*/
            $user = $user->0; 
            return view('profile')->with('users',$user);
    }
    

    我不记得哪个是正确的方法。 print_r($user) 之前看看它的样子。

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 2017-03-20
      相关资源
      最近更新 更多