-
routes/api.php
Open in GitHubuse App\Http\Controllers\Api\CategoryController; Route::group(['middleware' => 'cors'], function(){ // Route::get('categories', [CategoryController::class, 'listCategory']); // });
-
app/Http/Controllers/Api/CategoryController.php
Open in GitHubuse Illuminate\Http\Request; use App\Models\Category; use App\Transformers\ListCategory\CategoryTransformers as ListCategoryTransformers; class CategoryController extends ApiController { public function listCategory(Request $request, $limit = 20, $offset = 0) { $limit = $request->get('limit', $limit); $offset = $request->get('offset', $offset); $category = Category::orderBy('id', 'asc'); $categoriesCount = $category->get()->count(); $listCategory = fractal($category->skip($offset)->take($limit)->get(), new ListCategoryTransformers); return $this->respondSuccessWithPagination($listCategory, $categoriesCount); } // }
-
app/Transformers/ListCategory/CategoryTransformers.php
Open in GitHubuse League\Fractal\TransformerAbstract; use App\Models\Category; class CategoryTransformers extends TransformerAbstract { public function transform(Category $category) { return [ 'id' => $category->id, 'title' => $category->title, 'slug' => $category->slug, 'created_at' => $category->created_at, 'updated_at' => $category->updated_at, 'total_posts' =>$category->post->count() ]; } }