Skip to main content

Drupal 8: How to fetch or insert data from/to the database

This is a basic example on how to use the Drupal Core Database Connection Namespace in a custom Controller.

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

class JsonApiController extends ControllerBase {

  protected $database;

  public function __construct(Connection $database) {
    $this->database = $database;

  public static function create(ContainerInterface $container) {
    return new static(
  public function index() {
   $query = $db->select('sound_data', 'sd'); 
   $query->fields('noise', ['high', 'medium', 'low']);
   $data = $query->execute();
  public function importer() {
    $data = Json::decode($dataJson);