This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

Using Eloquent ORM with Slim

Updated on June 3, 2021

4 Min Read
using-eloquent-orm-with-slim

Previously, I wrote a very comprehensive tutorial on using twig templating with Slim micro framework. In that tutorial, I created an MVC type architecture to render views from controllers. In this article, I will use the MVC structure of the previous article and connect & use Eloquent ORM with Slim

Eloquent ORM is the default database driver for Laravel and can be used independently with any PHP framework such as Slim. Eloquent ORM throws objects of table data and you need to create class instances to catch them. In this article, I will use ORM in the controller class.

A Recap Of Directory Structure

The project’s directory structure will resemble the structure I created in the previous article. I will use four main folders, app, bootstrap, public, and vendor.

In the app folder, I have the Controller and Models folders, which contain two controllers and model files to render and fetch MySQL data. The bootstrap folder contains app.php which contains the logic of the application. The public folder will run the Slim application publically, and the vendor folder contains the dependencies that are automatically installed with the Slim framework. Following is the complete picture of the structure:

Installing Slim & Eloquent

At this point, I assume that you have already signed up with Cloudways and have launched your PHP application on its Web Hosting for PHP. Now installing Slim and Eloquent is easy!

To install Slim and Eloquent, move to the project folder and run the following Composer (comes pre-installed on the Cloudways Platform) commands:

For Slim:

composer require Slim/Slim “^3.0”

For Eloquent:

composer require illuminate/database

The next step is to create a database in MySQL.

Create Database and Tables

I will start by creating a simple database with the name “slim” and a table “users”. At this stage, use the following SQL query:

CREATE TABLE `users` (

 `id` int(11) NOT NULL,

 `name` varchar(250) NOT NULL,

 `email` varchar(250) NOT NULL,

 `password` varchar(250) NOT NULL,

 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

 `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'

) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--

-- Dumping data for table `users`

--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `created_at`, `updated_at`) VALUES

(1, 'shahroze nawaz', '[email protected]', '', '2017-08-06 11:47:24', '0000-00-00 00:00:00'),

(2, 'Pere Hospital', '[email protected]', '', '2017-08-06 16:43:12', '0000-00-00 00:00:00'),

(3, 'jane doe', '[email protected]', 'iamstupid', '2017-08-06 17:06:57', '2017-08-06 17:06:57'),
ALTER TABLE `users`

 ADD PRIMARY KEY (`id`);
ALTER TABLE `users`

 MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

This query will create a simple table with demo records in the database.

Create Eloquent Connection

Now it’s time to create Eloquent connection in app.php file, which is my base file for initiating the application. Simply pass the config setting object to slim instance and pass it to global container after booting the connection. Note that, I have already created app.php in the previous article.

<?php
session_start();
//autoload dependenciesrequire __DIR__ . '/../vendor/autoload.php';
//pass eloquent connection to slim settings object

$app = new \Slim\App([

       'settings' => [

           'displayErrorDetails' => true,

            'db' => [

               'driver' => 'mysql',

               'host' => 'localhost',

               'database' => 'slim',

               'username' => 'root',

               'password' => '',

               'charset' => 'utf8',

               'collation' => 'utf8_unicode_ci',
       ]
       ],
]);
//get all container items

$container = $app->getContainer();
//boot eloquent connection

$capsule = new \Illuminate\Database\Capsule\Manager;

$capsule->addConnection($container['settings']['db']);

$capsule->setAsGlobal();

$capsule->bootEloquent();
//pass the connection to global container (created in previous article)

$container['db'] = function ($container) use ($capsule){

   return $capsule;

};

$container['HomeController'] = function ($container) {
   return new \App\Controllers\HomeController($container);

};
require __DIR__ . '/../app/routes.php';
?>

Create Models & Define Fillables

The next step is the creation of a model for running Eloquent queries from HomeController. Here, I will define fillable items which are simply the data that need to be filled and inserted in the database. Fillables are enabled by default in Eloquent, so you must declare them in the model. Create a User model and paste the following code in it:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model{
   protected $table = 'users';
   protected $fillable = ['name','email','password'];
}

?>

If you need to understand namespaces, I have already created the namespace in the previous tutorial that you could revisit.

Create Queries in HomeController

The User model should now be ready in the User.php file. Now it’s time to create a query in the index method of HomeController class:

<?php

namespace App\Controllers;
use App\Models\User;

class HomeController extends Controller

{

   public function index($request, $response)

   {
       $create = User::create([

           'name' => 'jane doe',

           'email' => '[email protected]',

           'password' => 'iamstupid',

       ]);
var_dump($create);

   }

}
?>

The last thing is to define the route to run the app. Open route.php file and add the following code:

<?php

$app->get('/create', 'HomeController:index');

?>

So whenever user hits your_app_url/public/create the above database record will be created.
Now add one more method to get all data and show some properties in browser

public function getall($request, $response)

   {

       $users = $this->container->db->table('users')->get();

       foreach ($users as $user){

           echo $user->name . "</br>";

           echo $user->email . "</br>";

       }
   }

Next add the new route for this method in routes.php

$app->get('/get', 'HomeController:getall');

 

Following GIF illustrates how the basic app creates and shows the records with Eloquent:

Conclusion

As you could see, using Eloquent with Slim is really easy. In this article I’ve demonstrated how you can configure and use Eloquent with the Slim framework. For reference, you may also want to visit the article I wrote that elaborates the configuration of Eloquent with the Silex framework.

If you have any queries and questions do leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now