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

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

Configure Eloquent

Add the database settings to Slim’s settings array.

<?php
return [
    'settings' => [
        // Slim Settings
        'determineRouteBeforeAppMiddleware' => false,
        'displayErrorDetails' => true,
        'db' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'database',
            'username' => 'user',
            'password' => 'password',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ]
    ],
];
Figure 2: Settings array.

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

// Service factory for the ORM
$container['db'] = function ($container) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container['settings']['db']);

    $capsule->setAsGlobal();
    $capsule->bootEloquent();

    return $capsule;
};
Figure 3: Configure Eloquent.

Pass a controller an instance of your table

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

Query the table from a controller

<?php

namespace App;

use Slim\Views\Twig;
use Psr\Log\LoggerInterface;
use Illuminate\Database\Query\Builder;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class WidgetController
{
    private $view;
    private $logger;
    protected $table;

    public function __construct(
        Twig $view,
        LoggerInterface $logger,
        Builder $table
    ) {
        $this->view = $view;
        $this->logger = $logger;
        $this->table = $table;
    }

    public function __invoke(Request $request, Response $response, $args)
    {
        $widgets = $this->table->get();

        $this->view->render($response, 'app/index.twig', [
            'widgets' => $widgets
        ]);

        return $response;
    }
}
Figure 5: Sample controller querying the table.

Query the table with where

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

Query the table by id

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

More information

Eloquent Documentation