How to Use Eloquent in Slim Framework

The Eloquent ORM makes it incredibly easy to interact with a database. Today we’ll look at how we can use Eloquent to interact with our database inside your Slim Framework.

The Eloquent ORM provides an ActiveRecord implementation to work with your database. This means that each model you create corresponds to a table in your database.

How to install Slim Framework

Run the below-mentioned composer command, it will do all the heavy lifting for you,

Replace [my-app-name] with the desired project name for your new application. The above command will create a project using Slim-Skeleton application and it has below show directory structure.

Now You can run it with PHP’s built-in web server or you can point your browser to full URL.

So after gone through the above steps, if you point your browser to http://locahost:8080/, you should have following output in the browser –

Adding Eloquent to your application

Now that we have over application ready, let’s install Eloquent with the composer:

You should run above command from the root of your project and it will pull the eloquent library and its dependency to vendor directory.

Configure Eloquent

After downloading Eloquent you have to configure it so that our application will know about it. Open your src/settings.php file and add database settings array, and update it with your configurations

Now instantiate the capsule manager and boot Eloquent in publc/index.php file.

How to use Eloquent

Lets create a folder to hold eloquent models,for example app/models at root of your project.

Now open your composer.json file and update it with below ps4 autoload options,

Now run composer dump-autoload command from project root to update autoload reference files.

All set lets create a sample Model,Album.php with following content:

Now, let’s look at an example Album model, which we will use to retrieve and store information from our albums database table.

By convention, the “snake case”, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Album model stores records in the albums table.

if you want to mention table name manually, you can do that with $table property on the model class.

To know more about available options visit –

Let’s use this model and pull data from database, open our src/route.php file and define albums route as shown below

If everything goes well, if you head over to the browser with http://localhost:8080/albums, you will get json response.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets. Protection Status