RESTful API - an array to the Laravel 5 collection

I'm having problems with the array returned with DB::select() . I heavily use skip and take in Collections for the eloquent models in my API. Unfortunately, DB :: select returns an array, which obviously does not work with skip and take. How can I convert arrays to a collection that can use these methods?

I tried

 \Illuminate\Support\Collection::make(DB::select(...)); 

This does not work as I expected, as it wraps the entire array in the collection, rather than individual results.

Is it possible to convert a return from DB::select to a "native" collection that can use the skip and take methods?

Update

I also tried:

 $query = \Illuminate\Support\Collection::make(DB::table('survey_responses')->join('people', 'people.id', '=', 'survey_responses.recipient_id')->select('survey_responses.id', 'survey_responses.response', 'survey_responses.score', 'people.name', 'people.email')->get()); 

What else is telling me:

 FatalErrorException in QueryHelper.php line 36: Call to a member function skip() on array 

Greetings

+6
source share
2 answers

For anyone who has such a problem in Laravel, I found out working with the following solution:

  $query = DB::table('survey_responses')->join('people', 'people.id', '=', 'survey_responses.recipient_id') ->select('survey_responses.id', 'survey_responses.response', 'survey_responses.score', 'people.name', 'people.email'); if(isset($tags)){ foreach($tags as $tag){ $query->orWhere('survey_responses.response', 'like', '%'.$tag.'%'); } }; // We apply the pagination headers on the complete result set - before any limiting $headers = \HeaderHelper::generatePaginationHeader($page, $query, 'response', $limit, $tags); // Now limit and create 'pages' based on passed params $query->offset( (isset($page) ? $page - 1 * (isset($limit) ? $limit : env('RESULTS_PER_PAGE', 30)) : 1) ) ->take( (isset($limit) ? $limit : env('RESULTS_PER_PAGE', 30)) ); 

Basically, I didn’t know that you could run queries almost step by step, which allowed me to generate page fragments before , limiting the returned data.

+2
source

I would try:

 $queryResult = DB::table('...')->get(); $collection = collect($queryResult); 

If the query result is an array, the collection is populated with your results. See the official documentation for the collection. Laravel5 Collections

+11
source

Source: https://habr.com/ru/post/986132/


All Articles