Laravel- Trying to get property 'name' of non-object

0

I am developing a product catalog system with Administration Panel in Laravel 5.5.

I've finished it and everything works, except that I can not filter my products.

When I do the function:

dd($products);

to verify if it does filtering, it works perfect, but when I see it, it gives me the error:

Trying to get property 'name' of non-object

I'm working with a local scope that is this:

In the Model Category.php

public function scopeFilterCategory($query, $name) {
    return $query->where('name', '=', $name);
}

In my view: store.blade.php

This is where I get the problem:

<div class="categ-buttons">
    @foreach($categories as $category)
        <ul>
            <a href="{{ route('product.filter.category', $category->name) }}">
                <li>{{ $category->name }}</li>
            </a>
        </ul>
    @endforeach
</div>

and my controller is this:

    public function filterCategory($name) {
    //dd($name);
    $categories = Category::FilterCategory($name)->first();
    $products = $categories->products;

    $products->each(function($products){
        $products->categories;
        $products->image;
    });

    return view('store.products', compact('products', 'categories'));

    //dd($products);
}

The Request of Category:

public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'name' => 'max:120|required|unique:categories',
    ];
}

}

    
asked by C. Vaz 01.11.2018 в 23:28
source

1 answer

0

Effectively you have the error in:

@foreach($categories as $category)
        ...
@endforeach
since you are trying to run $ categories as a Collection and $ categories is not, since you are doing the query with a first () here:
$categories = Category::FilterCategory($name)->first();

Solution: Change the query by:

$categories = Category::FilterCategory($name)->get();
    
answered by 02.11.2018 в 10:35