Querying and loading entities
In this recipe, we will use an entity query to find all published articles and return them as JSON. We will also allow specifying the sort order via a query parameter.
How to do it…
- Create an
index
method in theArticleController
controller in your module that will receive the incomingRequest
object:<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class ArticleController extends ControllerBase {
public function index(Request $request):
JsonResponse {
}
}
The request
object will be used to retrieve query parameters passed in the URL.
- From the request, get the sort query parameter, defaulting to
DESC
:public function index(Request $request):
JsonResponse {
$sort = $request->query->get('sort&apos...