Hanie Asemi
Hanie Asemi

Reputation: 1500

get all objects from collection in laravel

I'm Using Ajax in laravel for create sideBar filter Search,filter products with grades.User Select some checkbox And Send them with this ajax code:

 $(document).ready(function (event) {
    $('#Filter_Result').click(function (event) {
        var grades = [];
        $('input[id="grade"]:checked').each(function (index, elem) {
            grades.push($(elem).val());
        });
        $.ajax({
            url: '/Products/Filter',
            type: 'get',
            data:{
                grades : grades,
            },
            dataType : 'html'
        })
            .done(function (response)
        {
            console.log(response);
            $('#Products').html(response);
        });
    });
});

And My tables are productgrades with product_id and grade_name columns and products table,My Controller here:

if ($request->price =="" && is_null($request->subjects))
    {
        for ($i = 1; $i<= sizeof($request->grades); $i++) {
           $product_id= Productgrade::where('grade_name',$request->grades[$i- 
           1])->pluck('product_id');
           for($j=1;$j<=sizeof($product_id);$j++)
           {
              $arr[] = Product::where('id',$product_id[$j-1]);
           }
        }
    }
    $products = collect($arr);
    return view('Products.Main', [
        'products' => $products,  
    ]);

And In Main.blade.php I'm Trying to get products attribute such this code:

@foreach($products as $product)
{{$product->id}}
@endforeach

But I Give this Error:

Property [id] does not exist on this collection instance.

How I Can Solved this problem?

Upvotes: 0

Views: 989

Answers (2)

Jeremy Layson
Jeremy Layson

Reputation: 93

I think you're just creating a Collection of QueryBuilders.

In this part:

$arr[] = Product::where('id',$product_id[$j-1]);

This part generates a QueryBuilder, and you just create a collection of it. Try changing it to this:

$arr[] = Product::where('id',$product_id[$j-1])->get();

But if you want to get the products with a certain grade_name then try this:

Product::with(['product_grade' => function($query) use ($value) {
    $query->where('grade_name', $value);
}]);

(This is considering that you have set-up the relationship in your Model)

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35357

You're not actually executing the query. You are just creating a query builder instance, you have to run first() to get the first result or get() to get a collection from the query builder.

$arr[] = Product::where('id',$product_id[$j-1])->first();

Although, if you already have an array of product ids, why don't you just run one query to get a collection of the products?

$products = Product::whereIn('id', $product_id)->get();

Upvotes: 1

Related Questions