Using Eloquent with Slim

You can use a database ORM such as Eloquent to connect your SlimPHP application to a database.

Adding Eloquent to your application

  1. composer require illuminate/database "~5.1"
Figure 1: Add Eloquent to your application.

Configure Eloquent

Add the database settings to Slim’s settings array.

  1. <?php
  2. return [
  3. 'settings' => [
  4. // Slim Settings
  5. 'determineRouteBeforeAppMiddleware' => false,
  6. 'displayErrorDetails' => true,
  7. 'db' => [
  8. 'driver' => 'mysql',
  9. 'host' => 'localhost',
  10. 'database' => 'database',
  11. 'username' => 'user',
  12. 'password' => 'password',
  13. 'charset' => 'utf8',
  14. 'collation' => 'utf8_unicode_ci',
  15. 'prefix' => '',
  16. ]
  17. ],
  18. ];
Figure 2: Settings array.

In your dependencies.php or wherever you add your Service Factories:

  1. // Service factory for the ORM
  2. $container['db'] = function ($container) {
  3. $capsule = new \Illuminate\Database\Capsule\Manager;
  4. $capsule->addConnection($container['settings']['db']);
  5. $capsule->setAsGlobal();
  6. $capsule->bootEloquent();
  7. return $capsule;
  8. };
Figure 3: Configure Eloquent.

Pass a controller an instance of your table

  1. $container[App\WidgetController::class] = function ($c) {
  2. $view = $c->get('view');
  3. $logger = $c->get('logger');
  4. $table = $c->get('db')->table('table_name');
  5. return new \App\WidgetController($view, $logger, $table);
  6. };
Figure 4: Pass table object into a controller.

Query the table from a controller

  1. <?php
  2. namespace App;
  3. use Slim\Views\Twig;
  4. use Psr\Log\LoggerInterface;
  5. use Illuminate\Database\Query\Builder;
  6. use Psr\Http\Message\ServerRequestInterface as Request;
  7. use Psr\Http\Message\ResponseInterface as Response;
  8. class WidgetController
  9. {
  10. private $view;
  11. private $logger;
  12. protected $table;
  13. public function __construct(
  14. Twig $view,
  15. LoggerInterface $logger,
  16. Builder $table
  17. ) {
  18. $this->view = $view;
  19. $this->logger = $logger;
  20. $this->table = $table;
  21. }
  22. public function __invoke(Request $request, Response $response, $args)
  23. {
  24. $widgets = $this->table->get();
  25. $this->view->render($response, 'app/index.twig', [
  26. 'widgets' => $widgets
  27. ]);
  28. return $response;
  29. }
  30. }
Figure 5: Sample controller querying the table.

Query the table with where

  1. ...
  2. $records = $this->table->where('name', 'like', '%foo%')->get();
  3. ...
Figure 6: Query searching for names matching foo.

Query the table by id

  1. ...
  2. $record = $this->table->find(1);
  3. ...
Figure 7: Selecting a row based on id.

More information

Eloquent Documentation