【问题标题】:How to Solve "Trying to get property of non-object" in Laravel?如何解决 Laravel 中“试图获取非对象的属性”?
【发布时间】:2019-03-11 03:42:22
【问题描述】:

如果我的代码返回 null,那么它会生成此错误。如果代码返回一些数据,那么它工作正常。

控制器

$profile_data= DB::table('partner_prefence')
    ->select('*')
    ->where('profile_id',$profile_id)
    ->first();

return view('partner_prefence',['profile_data' =>  $profile_data]);

视图/刀片

@php($rel_status = explode(',', $profile_data->p_marital_status))

如果$profile->p_marital_status 有值,则没有问题。只有当它的值为空时才会出现错误。

【问题讨论】:

  • 如果你使用firstOrFail()而不是first(),它甚至会在进入视图之前抛出一个错误,你可以根据需要捕获和处理。
  • 我正在使用 first(),我应该使用 firstorfail() 吗?
  • You don't have to... 它们本质上都做同样的事情,但如果没有返回结果,firstOrFail() 会抛出错误。您可以使用try ... catch 来处理它,或者如果您坚持使用first(),只需在将其传递给视图之前检查if($profile_data)。最终,如果该数据为 null,则由您决定该怎么做
  • 我认为您应该遵循提供的答案,因为我认为您的视图应该显示是否找到profile_data

标签: laravel laravel-5 laravel-blade laravel-helper


【解决方案1】:

使用optional() https://laravel.com/docs/5.8/helpers#method-optional

如果给定对象为 null,属性和方法将返回 null 而不会导致错误。

{!! old('name', optional($user)->name) !!}

【讨论】:

    【解决方案2】:

    根据条目是否对要呈现的页面至关重要,您可以在控制器中执行检查。

    $profile_data = DB::table('partner_prefence')
    ->select('*')
    ->where('profile_id',$profile_id)
    ->firstOrFail()
    

    或者允许空值传递给视图并进行三元检查。

    $profile_data ? $profile_data->p_marital_status : '';
    

    参考资料:

    Ternary Operator

    Retrieving Single Models

    【讨论】:

      【解决方案3】:

      首先需要检查 $profile_data 是否为空或有一些数据。 步骤 2:检查 $profile_data 对象具有名为 p_material_status 的属性。 Step3:如果以上两个都成立,那么尝试炸开数据,否则返回一些错误信息,尽量不炸开数据会更好。

      <?php
      
      $data = (($profile_data != null) && property_exists($profile_data->p_marital_status)) ? $profile_data->p_marital_status : null)
      if($data){
      $rel_status = explode(',', $data);
      }else{
          // Something else
      }
      
      ?>
      

      【讨论】:

      • 发布答案时,请务必解释发生了什么以及为什么这会回答问题;并非所有用户都能够推断出这些信息,简短的解释会有很长的路要走。
      【解决方案4】:

      只需在这样的句子上使用isset()!= null

      @php($rel_status = $profile_data ? explode(',', $profile_data->p_marital_status?: '')) : [];
      

      【讨论】:

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