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
indexmethod in theArticleControllercontroller in your module that will receive the incomingRequestobject:<?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...