Eloquent with Slim

We can use a database ORM such as Eloquent to connect your SlimPHP application to a database. We need to setup the databse and Model in best possible way. We are using Lavravel Eloquent ORM which provides a beautiful, simple ActiveRecord implementation for working with your database. We can use Eloquent outside of Lavravel and can easily use in our Slim project. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Step 1: Define Database schema
Inside phpmyadmin create a database name slimDB and add new table called users. Add following field ID, Name, Email, Password, Created_at, update_at. Where ID is integer, auto increment and primary field. Define database as utf8_unicode_ci.

Step 2: Install illuminate/database
composer require illuminate/database

Step 3: Configure the databse
In bootstrap/app.php we have set up the database configuration and we need to a way to define eloquent within our Slim project.

<?php

session_start();

require __DIR__ . '/../vendor/autoload.php';
$app = new \Slim\App([ 
    'settings' => [
        'displayErrorDetails' => true,
        'db' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'tamoslim1',
            'username' => 'root',
            'password' => 'tamo1959',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ]
        ],
]);
$container = $app->getContainer();
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();

$container['db'] = function ($container) use ($capsule) {
    return $capsule;
};
The capsule is way the Laravel let us to use it component outside of the Laravel. Now we can access our database . Now we need booted it globally, so we can use Model and we can access it via  through container within our controller.

Now test database or eloquent in our app/Controllers/homeController.php add this code.

<?php

namespace App\Controllers;

use Slim\Views\Twig as View;

class HomeController extends Controller {

    public function index($req, $res){
        $user = $this->db->table('users')->find(1);
        var_dump($user->email);
        die();

        return $this->view->render($res, 'home.twig');
    }
}