How to use Eloquent ORM without Laravel Framework
Setup Eloquent ORM with Core PHP Application
Laravel framework became a number one framework in php development it has lot of advantages.- Easy to run with homestead.
- Security
- Flexibility,
- documentation
- Real time support
If you already using laravel framework with your project then it’s good you can skip this post, but if you have a existing application, which is already in development phase and you won’t be able to convert it to laravel because of time limitations and still you wish to use
Eloquent ORM
for your future task from the project then this post is going to help you to install eloquent and use.Before following this tutorial you needs to have composer installed on your system which is going to help to pull in eloquent package.
Step 1: Installing Illuminate Database Component
Create project directory calleddemo
, if you are installing in existing application then just cd
in to you project directory with the terminal.Illuminate Database
component using composer:composer.json
file (if not exist) in your root directory with require dependancy, it is going to create vendor
folder with the required files and folders in it, don’t worry about it for now.if you open
composer.json
file it would look like this, version number may change according to the availability.Step 2: Setup autoload using classmap:
Setting up the autoload is important to have our namespace working, we are going to use here classmap, you can also you
psr-4
which is also good option.
Open up the composer.json file and following additional lines next to
require
:
You might thinking, what we are doing by adding autoload and
classmap
to the json
file?
We basically referencing the Model
directory to autoload, after adding those lines use following command to
dump and autoload your composer.
Step 3: Database connection with Eloquent ORM:
Eloquent ORM currently supports MySQL, Postgres, SQL Server, and SQLite, we can easily setup connection with any of those, I am going to use MySQL here for the demo.Step 4: Creating Eloquent ORM Model:
Let’s create our first Eloquent Model, create new directory calledModels
, here we will store our ORM models.Add new
Task.php
file within the Models
folder and use following code:$fillable
and many more.Before going to use this model, we need database table, to do than we will use
Capsule::schema()
.Create new file called
createTaskTable.php
use following code to create new schema for the table:To run using terminal type in following command:
Step 5: Using Eloquent ORM Model:
Before going to use ourTask
Model we have to update it for mass assignment variable, let’s do that now open the file and update it as showing below:testModel.php
file to access our Task
model and do some operations:Folder Structure: