Tell me how to make a route in Laravel like this:
https://jsonplaceholder.typicode.com/comments?_page=3&_limit=2

Can I turn without _limit=2 and without ?_page=3&_limit=2

Code like I did:

 Route::get('/articles/_page={currentPage?}&_limit={limit?}', "Controller"); 

I did this: /articles?_page={currentPage?}&_limit={limit?} .
And in other different ways, I do not know how to declare this second part as not obligatory. parameter

When /api/articles... not addressed.

  • But why did you think that these are not different routes? - Anton Kucenko
  • I do not know, maybe different. But for some reason I am sure that this can be done flexibly through 1 route and the controller can be implemented - Nikita From

1 answer 1

The route for pagination of articles can be one, all the rest (page, limit) is captured via request() with mandatory validation:

 // routes\api.php Route::group(['prefix' => 'v1', 'namespace' => 'V1', 'middleware' => 'auth:api'], function() { Route::get('/articles', 'ArticlesController@index'); }); 

Write the scope for the model, you can put in the treit:

 public function scopeAdvancedFilter($query) { $data = $this->validateAdvancedFilter(request()->all()); return $query->paginate($data['limit']); } protected function validateAdvancedFilter(array $request) { $request['limit'] = $request['limit'] ?? 15; $validator = validator()->make($request, [ 'limit' => 'sometimes|required|integer|min:5', 'page' => 'sometimes|required|integer|min:1', ]); return $validator->validate(); } 

In the controller:

 namespace App\Http\Controllers\Api\V1; use Illuminate\Http\Response; ... /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $articles = Article::with([ 'categories:categories.id,categories.title,categories.slug', 'user:users.id,users.name', ]) ->advancedFilter(); $collection = ArticleResource::collection($articles); return $collection->response() ->setStatusCode(Response::HTTP_PARTIAL_CONTENT); } ... 
  • Well thank you. I will understand now. This answer is even better) - Nikita From
  • medium.com/@dinotedesco/… - Rustam Gimranov
  • Do not tell me one more thing, I get it like this: imgur.com/a/b3QCHbj . How to output without data [.. This is how I tried: ArticleResource :: withoutWrapping (); - useless. Index completely as in the answer - Nikita From
  • public static $wrap = null; written in ArticleResource public static $wrap = null; , BUT pagination will always be wrapped in data so that it is separate from the meta - Rustam Gimranov
  • In general, here is the specification - Rustam Gimranov