Laravel - Foreach循环试图获取非对象的属性

时间:2018-05-03 11:11:06

标签: php laravel foreach eloquent

我有一个带

的数据库表

id | name | url | 1 | Bike | bike| 2 | Auto | auto|

我想从表中获取所有名称以使用foreach循环查看。但它返回

  

尝试获取非对象的属性

控制器

public function category($url, request $id)
{
    $cat = Category::where('url', $url)->firstorfail();
    return view ('view', compact('category'));  
}

模型

class Category extends Model
{
    protected $fillable = ['name', 'url'];
}

查看

@foreach($category as $cat)
    {{ $cat->name }}
    //{{ $cat['name] }} does not return anything.
@endforeach

//{{ $cat->name }} returns only one category name

我看到了enter link description here,我无法解决它。

3 个答案:

答案 0 :(得分:0)

$cat = Category::where('url', $url)->firstorfail();这只返回一个集合,而不是集合数组。如果要返回所有值,请使用get()

$category = Category::where('url', $url)->get();
return view ('view', compact('category')); 

答案 1 :(得分:0)

如果您想显示1个类别,您应该:

<强>控制器

public function category($url, request $id)
{
    $category = Category::where('url', $url)->firstorfail();
    return view ('view', compact('category'));  //sends 1 entity to the view
}

<强>模型

class Category extends Model
 {
      protected $fillable = ['name', 'url'];
 }

查看

  {{-- Removed the foreach becaus you have 1 entity sent from the controller --}}
  {{ $category->name }}

答案 2 :(得分:0)

public function category($url, request $id)
{
$cat = Category::where('url', $url)->firstorfail();
return view ('view')->with('category',$cat);  
}