【问题标题】:Trying to get property 'name' of non-object laravel 8 and livewire试图获取非对象 laravel 8 和 livewire 的属性“名称”
【发布时间】:2021-07-29 13:28:33
【问题描述】:

当我尝试在我的电子商务项目中编辑产品时遇到错误。我找不到我做错的地方。当我尝试编辑产品时,它给了我错误。我是 laravel 8 的初学者。我找不到在哪里寻找,因为它显示了声明的变量列表。

我的课程文件

<?php

namespace App\Http\Livewire\Admin;

use Livewire\Component;
use App\Models\Category;
use App\Models\Product;
use illuminate\Support\Str;
use Livewire\WithFileUploads;
use Carbon\Carbon; 

class AdminEditProductComponent extends Component
{
    
    public $name;
    public $slug;
    public $short_description;
    public $description;
    public $regular_price;
    public $sale_price;
    public $SKU;
    public $stock_status;
    public $featured;
    public $quantity;
    public $image;
    public $category_id;
    public $newimage;
    public $product_id;
    use WithFileUploads;

    public function mount($product_slug) 
    {
        $product = Product::where('slug',$product_slug)->first();
        $this->name = $product->name;
        $this->slug = $product->slug;
        $this->short_description = $product->short_description;
        $this->description = $product->description;
        $this->regular_price = $product->regular_price;
        $this->sale_price = $product->sale_price;
        $this->SKU = $product->SKU;
        $this->stock_status = $product->stock_status;
        $this->featured = $product->featured;
        $this->quantity = $product->quantity;
        $this->image = $product->image;
        $this->category_id = $product->category_id;
        $this->product_id = $product->id;

    }
   

【问题讨论】:

    标签: php laravel laravel-8 laravel-livewire


    【解决方案1】:

    您确定$product 不是null?如果以某种方式传递了错误的 slug,或者如果根本没有带有 slug 的产品 $products 将是 null 并且您会得到异常。

    您可以通过使用Log::info($product) 记录$product 来检查这一点。

    在任何情况下,您都应该检查是否找到了产品。

    【讨论】:

      【解决方案2】:

      yes.query 返回数组或对象?如果你把它转储出来,你可能会发现它是一个数组,你需要的只是一个数组访问([])而不是对象访问(->)。 产品不为空,我找到了答案。我将 -> 更改为 [] 并且它起作用了。

      $product = Product::where('slug',$product_slug)->first();
          $this->name = $product['name'];
          $this->slug = $product['slug'];
          $this->short_description = $product['short_description'];
          $this->description = $product['description'];
          $this->regular_price = $product['regular_price'];
          $this->sale_price = $product['sale_price'];
          $this->SKU = $product['SKU'];
          $this->stock_status = $product['stock_status'];
          $this->featured = $product['featured'];
          $this->quantity = $product['quantity'];
          $this->image = $product['image'];
          $this->category_id = $product['category_id'];
          $this->product_id = $product['id'];
      

      【讨论】:

        猜你喜欢
        • 2021-06-04
        • 2021-06-05
        • 2019-12-13
        • 2020-09-28
        • 1970-01-01
        • 2021-09-03
        • 2019-05-23
        • 2019-07-11
        • 1970-01-01
        相关资源
        最近更新 更多