【问题标题】:Trying to get the property of a non-object in laravel试图在laravel中获取非对象的属性
【发布时间】:2015-08-19 14:43:47
【问题描述】:

我有两张桌子:userstudent。来自user 的字段username 是一个外键,如student 中的login_id。我在每个模型中都创建了雄辩的关系,但是当我尝试访问 Auth::user()->student->id 时,它给了我:

试图获取非对象的属性。

学生模型:

public function user()
{
  return $this->belongsTo('user','login_id');
}

用户模型:

public function student(){
    return $this->hasOne('student')
}

ProfileController.php

<?php
class ProfileController extends BaseController
{
    public function showinfo()
    {
        if (Auth::check())
        {
            $user_id = Auth::user()->username;
            $student_id = Auth::user()->student->id;
        }
    }
}

当我尝试登录时出现上述错误。

【问题讨论】:

  • 不,现在我收到另一个错误:BadMethodCallException HELP 调用未定义的方法 Illuminate\Database\Query\Builder::student()

标签: php authentication laravel eloquent


【解决方案1】:

你应该先检查登录的用户是否有学生,所以我建议

$student = Auth::user()->student;
if($student) $student_id = $student->id;

【讨论】:

    【解决方案2】:
    $student_id = Auth::user()->student->id;
    

    如果它不包含值,那么你会得到那个错误。试试用isset,还是empty,看你喜欢什么。

    只有多对多关系才使用( )

    示例:

    $user_companies = Auth::user()->companies();
    
    foreach($user_companies as $company)
    

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 2015-09-22
      • 2017-03-20
      • 2014-03-25
      • 2015-01-25
      • 2014-06-23
      • 1970-01-01
      相关资源
      最近更新 更多