【问题标题】:Trying to get property 'firstname' of non-object Laravel 5.7试图获取非对象 Laravel 5.7 的属性“名字”
【发布时间】:2023-03-30 23:18:02
【问题描述】:

我有一个问题,为什么我的刀片视图中出现未定义的变量“尝试获取非对象的属性‘名字’(视图:C:\xampp\htdocs\focus\resources\views\assets\asset.刀片.php)"

asset.blade.php

    <tbody>
                        @foreach($assets as $asset)
                            <tr>
                                <td>{{ $asset->employee->firstname }} {{ $asset->$employee->lastname }}</td>
<!--this where the error came-->
                                <td>{{ $asset->employee->account->name }}</td>
                                <td>{{ $asset->employee->position }}</td>
                                <td>{{ $asset->workstation }}</td>
                                <td></td>
                                <td></td>
                                <td>{{ $asset->remarks }}</td>
                                <td>


                                </td>
                            </tr>
                    @endforeach
                    </tbody>

资产.php

public function employee()
{
   return $this->belongsTo('App\Employee');
}

Employee.php

public function asset()
{
    return $this->hasMany('App\Asset');
}

我真的不知道这个错误是从哪里来的

dd($assets) 的输出

【问题讨论】:

    标签: laravel-5.7


    【解决方案1】:

    尝试$asset-&gt;employee-&gt;x 而不是$asset-&gt;$employee-&gt;x

    注意$

    当您编写 $asset-&gt;$employee 时,它假定 $employee 存在,但实际上不存在,因此会出现错误。

    【讨论】:

    • 我编辑了问题先生,并将其更改为 $asset->employee->x,然后尝试获取非对象的属性
    • 你能编辑问题并在你的控制器中添加dd($assets);的输出吗?看起来您拥有与员工无关的资产?或者可能是没有帐户的员工对象。
    • 我在模型中声明了关系
    • 这并不意味着数据存在于您的模板中。如果 de 数据库中存在资产,但没有附加员工,那么您将永远无法显示 $asset-&gt;employee-&gt;account-&gt;name。您将收到"Trying to get property 'x' of non-object 错误。在您的情况下,您从数据库中获取的资产在模型中定义了一个关系,但它在您的数据库中不存在。 $asset-&gt;employee 不是 Employee 对象,而是 null。所以你得到了你试图获取非对象的属性firstname 的错误。
    • 但是我的资产表中有一个外键 emp_id
    猜你喜欢
    • 2019-12-26
    • 2019-12-13
    • 1970-01-01
    • 2021-06-04
    • 2015-09-22
    • 2017-03-20
    • 2014-03-25
    • 2015-01-25
    • 2014-06-23
    相关资源
    最近更新 更多