Browse

List all models

A controller with any of these Traits can list all models it has. The traits provide the index() method which a route can connect to for the listing.

<?php

Route::get('/tasks', 'TaskController@index');

Also, method trashedIndex() is available to list all models that were soft-deleted. It works the same way as the index() method.

<?php

Route::get('/tasks/deleted', 'TaskController@trashedIndex');

Pagination

By default, the list of models are paginated, returning 15 models per page. To change the number of models, pass in GET parameter length to hold the desired length.

curl http://example.com/api/tasks?length=30

The above request would return the first 30 tasks. To fetch subsequent pages, append parameter page to the request.

curl http://example.com/api/tasks?length=30&page=2

📘

Tip

To change the default pagination length, override method defaultPaginationLength() which returns an integer.

Sorting

Sorting is also allowed on the list of models and by default, parameter sort in the GET request string holds the sorting command.

The format of the command is `column1:direction1,column2:direction2,...'.

curl http://example.com/api/tasks?sort=id:asc,title:desc

📘

Note

You should certainly encode your url.

It's also possible to specify only a column name without the direction. In such a case, the direction defaults to asc.

The above request is the same as the one below.

curl http://example.com/api/tasks?sort=id,title:desc

📘

Tip

To change the default sort parameter name, override the sortParam() method and return the desired string parameter name.

Querying the list

The list of models can be queried to fetch models that match certain criteria.

By default, the query GET parameter should hold the string to search by.

📘

Tip

To change the default parameter name, override the searchQueryParam() method and return the desired parameter name.

For the query to work, you must override the searchModel($query) method

<?php

// ...

public function searchModel($query) {
  return Task::where('name', 'like', "%$query%");
}

The above returns a list of tasks where the name is like the given query string.

Perform action on fetched list before returning to client

Methods beforeIndexResponse() and beforeTrashedIndexResponse() are available to catch the data before it is returned.

<?php

// ...

public function beforeIndexResponse(&$data) {
  // do something on/with $data
}

public function beforeTrashedIndexResponse(&$data) {
  // do something on/with $data
}

📘

Tip

If either of the methods returns null, the fetched list is returned to the client. To send a different response, return the response from either of the methods.


Next