0
votes

I have a database table with

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

I want to fetch the all names from the table to view with foreach loop. But it returns

Trying to get property of non-object

Controller

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

Model

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

View

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

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

I saw enter link description here, I couldn't solve it.

3
You are getting 1 model via firstorfail but in the view you are iterating ... either remove the foreach or pass an array of Categoryka_lin
I tried replacing firstorfail with get(), still no success. If I tried $cat->all(). Its Call to a member function all() on boolean. It is the issue?universal
get is used when specifing a where clause with/or sorting. If you want to display 1 item remove the foreach in the template. If you want multiple then pass to the view the arrayka_lin

3 Answers

1
votes

$cat = Category::where('url', $url)->firstorfail(); this only return one collection, not array of collection. If you want to return all the values then use get():

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

If you want to display 1 category you should have:

Controller

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

Model

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

View

  {{-- Removed the foreach becaus you have 1 entity sent from the controller --}}
  {{ $category->name }}
0
votes
public function category($url, request $id)
{
$cat = Category::where('url', $url)->firstorfail();
return view ('view')->with('category',$cat);  
}