【问题标题】:Trying to get property 'image' of non-object试图获取非对象的属性“图像”
【发布时间】:2020-07-09 07:23:27
【问题描述】:

在控制器中

public function index()
{
    $profile = Profile::where('user_id', auth()->user()->id)->first();
    return view('profile', compact('profile'));
}

在刀片视图中

 <div class="card mb-5">
      <img class="card-img-top" src="{{ asset('images/'.$profile->image ? $profile->image : "" ) }}"
        alt="Profile User">
      <div class="card-body">
        <h5 class="card-title">{{Auth::user() ? Auth::user()->name :""}}</h5>
        <p class="card-text">{{Auth::user() ?Auth::user()->email :""}}.</p>
      </div>
      <ul class="list-group list-group-flush">
        <li class="list-group-item">{{$profile ? $profile->gender :"Belum Di isi"}}</li>
        <li class="list-group-item">{{$profile ? $profile->phone :"Belum Di isi"}}</li>
        <li class="list-group-item">{{$profile ? $profile->address :"Belum Di isi"}}</li>
      </ul>
    </div>

但是上面的代码抛出一个错误 Trying to get property of non-object。 如何修复这些错误,使图像再次运行而不会出现错误

【问题讨论】:

  • 显示 $profile 的 dd(),在你的控制器中添加 dd($profile) 。它会给出同样的错误吗?
  • 当dd($profile)结果为null时
  • 它显示该错误,因为您的 $profile 对象为空。在访问其属性之前,您应该先检查它。你应该试试这个$profile ? $profile-&gt;image : ""
  • 我认为数据不存在,这就是您收到此错误的原因。如果是这样,则将 first() 更改为 firstOrFail 如果不存在数据,它将引发 404 错误。 $profile = Profile::where('user_id', auth()-&gt;user()-id)-&gt;firstOrFail();
  • 我试过了还是报错

标签: php laravel laravel-7


【解决方案1】:

抛出错误是因为您的 $profile 变量不是对象,它可以是 arraynull。尝试dd($profile) 以确保您正在传递一个对象

如果您要传递一个对象,那么如果您要传递一个对象,请尝试像这样更改您的代码

  <img class="card-img-top" src="{{ asset('images/' . $profile ? $profile->image : "" )}}"/>

如果你传递一个数组,或者像下面这样

 <img class="card-img-top" src="{{ asset('images/' . isset($profile['image'] ? $profile['image'] : "" )}}"/>

【讨论】:

  • 当我使用 isset 属性时,会出现这样的错误 = 不能在表达式的结果上使用 isset()(您可以改用“null !== expression”)
【解决方案2】:

在使用身份验证之前进行身份验证检查。
使用firstOrFail而不是first,如果得到空值会抛出404错误:

use Illuminate\Support\Facades\Auth;

public function index()
{
    if (Auth::check())
    {
        $profile = Profile::where('user_id', Auth::id())->firstOrFail();
        return view('profile', compact('profile'));
     } else {
        return "You are not logged in";
    }
}

【讨论】:

    【解决方案3】:

    就我而言!每次在我的代码中发生此错误时,这是​​因为 $item-&gt;image 不存在于我的集合实例中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      相关资源
      最近更新 更多