Leo
Leo

Reputation: 7420

How to get the pluck results as a collection in Laravel

So I am working on a RESTApi with Laravel.

I am trying to get all the products that the buyer has bought. The thing is that buyer and products they are related through transactions table. Now the code below I am getting the results needed back since I am using Laravel eagerloading to get transactions with their products like so:

     /**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index(Buyer $buyer)
{

    $products = $buyer->transactions()->with('product')->get()->pluck('products');



    return $this->showAll($products);
}

The thing here is that I have a trait that is being called on my base ApiController that trait has a method showAll() to return/display a json response of the request. The showAll() method expects a collection to be returned. While I am sending a property of a collection instead.

My question:
How do I get back the products after eagerloading as collections instead of property ?

Upvotes: 1

Views: 1294

Answers (1)

HasilT
HasilT

Reputation: 2609

You could use the collect()helper function to convert your $products array to collection.

Refer more on the doc https://laravel.com/docs/5.5/collections#introduction

Upvotes: 3

Related Questions