Laravel’s Eloquent ORM isn’t likely the first one you think of when using Zend Expressive. You likely think of Zend\Db or Doctrine. But, with a little bit of work, it’s possible to use Eloquent with Expressive. Today’s tutorial shows you how - step-by-step.
When working with Zend Expressive, if you were to choose a database layer for your application, I guess that the first two names to come to mind would be either Zend\Db or Doctrine. But what about Laravel’s ORM: Eloquent?
That’s right, Eloquent!
I’ve been getting to know Laravel a bit better recently, primarily for the comparison I wrote about it and Zend Expressive not that long ago.
The tutorial was exceptionally well received. So I thought I’d dig a bit further, and see if I could use Eloquent instead of my standard Zend\Db. It turns out, with a bit of work, you can do it!
In today’s tutorial, I’m going to step you through how to make it available, using a project based off of the Zend Expressive Skeleton Installer.
Installing Eloquent
Actually, when it’s not used with Laravel, it’s not called Eloquent. Well in the repository’s not called that at least. It’s called Laravel-Database. Built on top of the illuminate/database
package, in the words of the repository README, it:
Provides full Laravel database functionality for your non-Laravel projects adds Migration, Seeding and Artisan support to Illuminate Database.
To make it available, from the terminal, in the root of your project, run the following commands:
composer require laravel/database
When Composer’s done, you’re be ready to go.
Database Configuration
The first thing we need to do is to create a configuration to our database. To do that, in config/autoload
create a new file, called eloquent.global.php
. In there, add the following configuration, adjusted for your database setup:
return [
'eloquent' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'homestead',
'username' => 'homestead',
'password' => 'secret',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
]
];
You can see that we’re setting all of the relevant configuration options, required to connect to a local MySQL database.
Note: In case you’re wondering, I’m running my local copy of this application inside the Laravel Homestead VM. It’s a handy VM setup that provides services and a stock configuration where you can get started right away.
Making Eloquent Available to Zend Expressive
Next, we need to make Eloquent available, so that we can use it to connect to our MySQL database. To do that, we need to add the following lines to public/index.php
, after require 'vendor/autoload.php’;
.
use Illuminate\Database\Capsule\Manager;
/** @var \Interop\Container\ContainerInterface $container */
$container = require 'config/container.php';
$capsule = new Manager();
$capsule->addConnection($container->get('config')['eloquent']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
What this does is to make the Eloquent connection manager globally available, using the configuration which we provided in the last section.
Now, whether you think that having it globally available is a good thing or not, I’ll leave for another time. For right now, we can now move on and create a model class.
Creating a Database Model
This section is not going to take a lot to complete. Firstly, create a new directory, under src/App
, called Model
. In there, create a new file, called Capital.php
.
I’m assuming here, that in your database you already have a table called capitals
, which has the following schema:
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| population | bigint(20) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+------------+------------------+------+-----+---------+----------------+
You can see that it has five columns:
- An auto_increment column, called
id
name
which stores the capital’s name
population
which stores the capital’s population
created_at
which stores the created date
updated_at
which stores when it was updated
To work with that, Capital.php
will have to look as follows:
namespace App\Model;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class Capital extends EloquentModel
{
}
You can see that it is a standard Eloquent Model class. I’ve only aliased Eloquent\Model
, to avoid a namespace clash. With that done, we’re ready to use it.
Creating a Record
Now, we need to put it to use and create our first capital. To do so, in src/App/Action/HomePageAction.php
, at the bottom of the __invoke()
method, add the following code and feel free to change the values of the respective properties to a capital of your choice.
$capital = new \App\Model\Capital();
$capital->name = 'Brisbane';
$capital->population = 1500000;
$capital->save();
You can see that I’m going to add Brisbane, my favorite capital and set the population to be 1.5 million people. If you’re not familiar with Eloquent, the Model class implements PHP’s magic __get and __set methods.
Given that we don’t need to declare the properties specifically. With the properties set, we can then call save()
and the record will be persisted to the database on the next page request.
Retrieving All Records
With a record in the database, let’s now retrieve all records and render them in the template. To do so, replace the code above which sets name and population, and the call to save()
, and add the following.
$data['capitals'] = $capital::all();
This makes use of the static all()
method to retrieve all records from the capitals table, storing them in a template variable, aptly called capitals
.
As the Capitals are now available in the template, we only need render them. To do so, here’s a code snippet, which you can use in templates/app/home-page.pthml
to render the data in a table.
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Population</th>
</tr>
<tr>
<?php foreach ($this->capitals as $capital) : ?>
<td><?php print $capital->name; ?></td>
<td><?php print $capital->population; ?></td>
<?php endforeach; ?>
</tr>
</table>
Where’s Artisan, Migrations, and Database Seeding?
You’d likely expect if you’re familiar with Eloquent and Laravel, that these three would be included, right? Well, despite the fact that Artisan is available in Laravel-Database, I’ve yet to be able to get it to work properly.
This is mainly due to how the repository is structured. But I’d suggest, with a little further work, it should be pretty straight-forward. But there is a solution, which I’ll cover in a little bit.
When I’ve gotten it sorted, I’ll either update this tutorial or create a supplementary one to complete the series.
Conclusion (tl;dr)
And that’s how to use Laravel’s Eloquent ORM, instead of another, such as Zend\Db or Doctrine, with Zend Expressive. Admittedly, it isn’t the most eloquent, pardon the pun, of setups. But it does work.
Join the discussion
comments powered by Disqus