Skip to content
Advertisement

laravel – unable to get data outside foreach

dump($data) outside the foreach loop gives me only 1 data where as dump($data) inside the foreach shows all arrays of rows of data . How can i get all rows of data outside the foreach too?

        $skillId = $request->skillId;
        if (CourseFiles::where('skillId', $skillId)->exists()) {

            $courseId = CourseFiles::where('skillId', $skillId)->get(['courseId']);
            foreach ($courseId as $row) {

                $id = Course::find($row);
                $data = [];
                $data['courseDisplayName'] = $id[0]['courseDisplayName'];
                $data['courseInfo'] = $id[0]['courseUniqueName'];
                $data['paidStatus'] = $id[0]['paid_status'];
                $data['coursePatternsId'] = $id[0]['course_patterns_id'];

                $fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
                $id = Uploads::find($fileId);

                $data['filePath'] = $id[0]['FilePath'];
                $contentTypeID = $id[0]['FileType'];

                $id = ContentTypes::find($contentTypeID);
                $data['file_height'] = $id[0]['height'];
                $data['file_width'] = $id[0]['width'];
                dump($data);  
            }

//dump($data);

            if ($data) {
                return response()->json([
                    'message' => 'Fetched Data successfully',
                    'data' => $data,
                    'statusCode' => 200,
                    'status' => 'success'
                ], 200);
            }
  }

EDIT:

$response[]=$data;
$response->paginate(5);

Error: Call to a member function paginate() on array

Advertisement

Answer

In Controller add new function for it

$data = $this->paginate($myArray);

After that crate that function for pagination

public function paginate($items, $perPage = 5, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }

return that $data in response

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement