【问题标题】:Trying to get property 'id' of non-object error (Asset management system)试图获取非对象错误的属性“id”(资产管理系统)
【发布时间】:2020-01-22 05:57:27
【问题描述】:

除了创建功能外,我的整个项目都可以正常运行。当我以普通用户身份登录时,我可以毫无问题地查看衣服的索引。但是以管理员身份登录时,我只能在第一次创建新衣服时查看索引(普通用户无权访问)。

在第一次之后,第二次添加新衣服时,会弹出此错误,我正在尝试解决这个问题。我刚刚开始使用 Laravel。

这是我在控制器上的索引函数中的代码:

$clothe = Clothe::all();

return view('clothes.index')->with('clothe',$clothe)->with('brand',Brand::all())->with('stock',Stock::all());

品牌与品牌型号有关,即服装品牌,而库存是与两种数据有关的库存型号,“可用”和“不可用”(请注意,仅当我登录时才有效以普通用户身份登录,但当我以管理员身份创建第二件衣服时不会这样做)

在我的衣服索引刀片上,出于某种原因,它会将 $brand、$stock 和 $clothe 读取为非对象。

当管理员创建第二件衣服时,数据确实被存储了,因为我在我的数据库中检查过,唯一的问题是显示它。

这是我的商店功能:

public function store(Request $request, Clothe $clothe, Stock $stock)
{
    $this->authorize('create',$clothe,$stock);
        $request->validate([
        'name' => 'required|string',
        'price' => 'required|numeric',
        'brand-id' => 'required|numeric',
        'stock-id' => 'required|numeric',
        'description' => 'required|string',
        'image' => 'required|image|max:5000'
    ]);

    $clothe = new Clothe;

    $clothe->name = $request->input('name');
    $clothe->price = $request->input('price');
    $clothe->brand_id = $request->input('brand-id');
    $clothe->stock_id = $request->input('stock-id');
    $clothe->status_id = 1;
    $clothe->description = $request->input('description');
    $clothe->image = $request->image->store('public');

    $clothe->save();

    return redirect(route('clothes.index'));
}

这是我的创建函数

public function create(Clothe $clothe)
{
    $this->authorize('create',$clothe);
    $brand = Brand::all();
    $stock = Stock::all();
    return view('clothes.create')->with('brand',$brand)->with('stock',$stock);
}

【问题讨论】:

  • 你在哪里打电话? Myabe 向我们展示了索引本身和创建刀片。
  • flareapp.io/share/dmkjlD53 这是完整错误堆栈的链接,索引代码在那里
  • 奇怪的是错误是关于 id 但在第 46 行没有 id 的链接上。你知道对 id 的哪些调用是关于什么的吗?

标签: php laravel laravel-blade


【解决方案1】:

我不知道你为什么这样做

行:34

@foreach($clothe as $clothe)

我不知道这是否是导致 PHP 有时将“$clothes”视为集合而不是实例的原因,因为您使用的是相同的变量名,它应该是:

@foreach($clothes as $clothe) 
OR
@foreach($clothe as $singleclothe)

$clothe->stock->id 需要 $clothe->stock()->id 取决于关系,因为您只能在雄辩的关系或返回关系实例的函数上调用它,否则您需要使用 ( )。

【讨论】:

  • 神圣 &%$#​​ 非常感谢它的工作!我不敢相信命名有什么效果:(
猜你喜欢
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2019-04-30
相关资源
最近更新 更多