Table of Contents
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
Apart from the above features Laravel comes up with Eloquent ORM Powerful Database component, it is used to handle all database related operations.
If you already using Laravel framework with your project then it’s good you can skip this post, but if you have an 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 need 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 called `demo`, if you are installing in existing application then just `cd` into you project directory with the terminal.
mkdir demo cd demo
Pull `Illuminate Database` component using composer:
composer require illuminate/database
It will create `composer.json` file (if not exist) in your root directory with require dependency, it is going to create `vendor` folder with the required files and folders in it, don’t worry about it for now.
Using version ^5.2 for illuminate/database ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) - Installing symfony/polyfill-mbstring (v1.2.0) Loading from cache ..... Writing lock file Generating autoload files
Make sure you get above message.
if you open `composer.json` file it would look like this, version number may change according to the availability.
{ "require": { "illuminate/database": "^5.2" } }
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`:
{ "require": { "illuminate/database": "^5.2" }, "autoload":{ "classmap": [ "Models" ] } }
You might think, 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.
composer dump-autoload -o
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.
<?php use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule(); $capsule->addConnection([ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'orm_test', 'username' => 'homestead', 'password' => 'secret', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ]); $capsule->setAsGlobal(); $capsule->bootEloquent();
Step 4: Creating Eloquent ORM Model:
Let’s create our first Eloquent Model, create new directory called `Models`, here we will store our ORM models.
Add new `Task.php` file within the `Models` folder and use following code:
<?php use Illuminate\Database\Eloquent\Model as Eloquent; class Task extends Eloquent { }
We can use all available options ‘$table’, ‘$primaryKey’ or mass assignment array called `$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:
<?php use Illuminate\Database\Capsule\Manager as Capsule; // load composer autoload require __DIR__ .'/vendor/autoload.php'; // boot database require __DIR__ . '/database.php'; // create table Capsule::schema()->create('tasks', function ($table) { $table->increments('id'); $table->string('title'); $table->string('body'); $table->timestamps(); }); echo 'Table created successfully!';
It is exactly like database migration in Laravel, try to run this file using terminal or with browser:
To run using terminal type in following command:
php createTaskTable.php
It should show success message.
Step 5: Using Eloquent ORM Model:
Before going to use our `Task` Model we have to update it for mass assignment variable, let’s do that now open the file and update it as showing below:
<?php use Illuminate\Database\Eloquent\Model as Eloquent; class Task extends Eloquent { protected $fillable = [ 'title', 'body' ]; }
Add `testModel.php` file to access our `Task` model and do some operations:
<?php // load composer autoload require __DIR__ .'/vendor/autoload.php'; // boot database require __DIR__ . '/database.php'; // create new task Task::create([ 'title' => 'Task 1', 'body' => 'Lorem ipsum' ]); // get all the records from the table dd(Task::all()->toArray());
Use following command to run file:
php testModel.php
it should show following output:
array(1) { [0]=> array(5) { ["id"]=> int(1) ["title"]=> string(6) "Task 1" ["body"]=> string(11) "Lorem ipsum" ["created_at"]=> string(19) "2016-07-22 08:56:56" ["updated_at"]=> string(19) "2016-07-22 08:56:56" } }
If you see new record is created and listed that means your good to go and use Laravel Eloquent ORM in your project.
Folder Structure:
Tnanks for lesson! How can i use Capsule ORM with cache (memcached)?
check out https://packagist.org/packages/laravel/database for migration support along with eloquent