尝试获取非对象 laravel 8 和 livewire 的 属性 'name'

Trying to get property 'name' of non-object laravel 8 and livewire

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

我的class文件

<?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;

    }
   

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

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

无论如何,您应该检查是否找到该产品。

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'];