如何显示 parent_id = laravel 中的值

How to show where parent_id = value in laravel

我有一个类别 table,它们有以下字段。

我想显示 parent_id =(例如)= 2 的类别,但我看到了这个错误。

ErrorException (E_ERROR)

Trying to get property of non-object (View: C:\xampp\htdocs\new\shopping\resources\views\Home\networks.blade.php) Previous exceptions

Trying to get property of non-object (0)

NetworkController.php

public function networks()
{
    $categories = Category::where('parent_id', 2)->first();
    return view('Home.networks', compact('categories'));
}

networks.blade.php

@foreach($categories as $category)
    <option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach

$categories = Category::where('parent_id', 2)->first();

只需将其替换为

$categories = Category::where('parent_id', 2)->get();

作为参考,请检查此 link the difference of find and get in Eloquent in Laravel