Slim4 Tutorial: 1 Eloquent database without Laravel

Slim4 Eloquent tanpa Laravel

Install database package/library Eloquent without Laravel can be applied in Slim4 to create Fashion Store APISlim4 is a PHP micro framework, while Eloquent is object-relational mapper (ORM) ibrary used in Laravel. Slim4 comes with a small file size that does not have a default database library. It can be paired with Laravel Eloquent. Even though, Slim4 comes with small file size, it can be used to create full-featured web appHowever, in this tutorial, we will discuss how to create PHP backend API. In this Slim4 Tutorial: 1 Eloquent database without Laravel , we will disccuss how to install and implement the Laravel Eloquent in Slim4.

Slim4 Installation

Slim4 installation is quite simple, some of the applications needed before installation is apache2, php7.4 and composer. Command used to installation it as follows:

mkdir fashion-store-slim4
cd fashion-store-slim4
composer require slim/slim:"4.*"
composer require slim/psr7

Directory structure after successful installation:

Slim4 struktur direktori Eloquent tanpa Laravel

Example name that will be used for database is fashion_store_db and for table will use user. Design for user table like below:

Table user Slim4 Eloquent tanpa Laravel

MySQL script to create a User table as follows:

CREATE TABLE IF NOT EXISTS `fashion_store_db`.`user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(100) NOT NULL,
  `password` VARCHAR(100) NULL,
  `name` VARCHAR(100) NULL,
  `level` INT NULL,
  `status` INT NULL,
  `created_at` DATETIME NULL,
  `updated_at` DATETIME NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC) VISIBLE)
ENGINE = InnoDB;

PHP Slim4 Tutorial: 1 Eloquent database without Laravel

There are many choices of packages that can be used as database connector in Slim4, one of popular packages is Eloquent Laravel. Eloquent itself is a standalone package which is can be installed without having full of Laravel. Installing Eloquent on Slim4 can be done by composer:

composer require illuminate/database:*

After composer installed required packages successfully, create files in config/settings.php and config/dependencies.php.

Settings Slim4 Eloquent tanpa Laravel

File settings.php file will be used to store application setting codes. Example code for settings:

<?php

return [
    'db' => [
        'driver' => 'mysql',
        'host' => '127.0.0.1',
        'database' => 'database',
        'username' => 'username',
        'password' => 'password',
        'charset' => 'utf8',
        'collation' => 'utf8_general_ci',
    ]
];

Before Eloquent database is used in on Slim4, first we need to initialize the database setting first. Initialization will be done in config/dependencies.php.

<?php

$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($settings['db']);
$capsule->bootEloquent();
$capsule->setAsGlobal();

After initializing the database setting, add codes composer.jsonto trigger the autoload function. The autoload function will call App namespace, it will used to accommodate the needed from application, for example Models namespace in models directory. The model file location is in src/Modelsdirectory. Add autoload in composer.json as follows:

{
    ...
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

Regenerate the files with the composer command:

composer dump-autoload

Create User model at src/Models/User.php

User model Slim4 Eloquent tanpa Laravel

Accessing the User model

By initialized Eloquent without Laravel in dependencies, we can be used it in Slim4User model will access directly to the database and we can use the Larevel's Eloquent syntax in Slim4. Next step is to extend the class from Eloquent to User Model, for example, the Models User class extends the Eloquent Model class. The $table attribute is used to indicate the name of the table used by the model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';
    protected $primaryKey = 'id';
}

Create files in public/index.php and public/.htaccess Directory structure will be like:

Route Slim4 Eloquent tanpa Laravel

We need to enable the rewrite module in apache2, because route function will not working well if it did not enabled. Rewrite module will remove the index.php from the address bar in the browser. Enabling the rewrite module using the terminal:

a2enmod rewrite

Add codes at .htaccess to rewrite the index.php file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Example route to get user data as follows:

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use App\Models\User;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();
$app->setBasePath('/fashion-store-slim4/public');

$settings = require __DIR__ . '/../config/settings.php';
require __DIR__ . '/../config/dependencies.php';

$app->get('/user', function (Request $request, Response $response) {
    $user = User::all();
    $data = json_encode($user);
    $response->getBody()->write($data);
    return $response
        ->withHeader('Content-Type', 'application/json')
        ->withStatus(200);
});

$app->run();

Application can be tested using Postman by localhost/fashion-store-slim4/public/user

Postman daftar user Slim4 Eloquent

Full code can be viewed at GithubA complete list Slim4 API tutorials can be viewed via link ini.

3 thoughts on “Slim4 Tutorial: 1 Database Eloquent tanpa Laravel

  1. Pingback: Slim4 Fashion Store API: 2 Register user dan validasi request – PerangkatLunakKu

  2. Pingback: Tutorial PHP Backend Slim4 - PerangkatLunakKu

  3. Pingback: Slim4 Tutorial API: 2 Validasi request - PerangkatLunakKu

Leave a Reply