WordPress is a powerful platform, but when it comes to custom database queries, the $wpdb class often leaves much to be desired. While $wpdb is suitable for straightforward queries, managing complex database operations across multiple tables can quickly become cumbersome and error-prone.
Enter Eloquent, the ORM (Object-Relational Mapper) developed by Laravel, which simplifies database interactions while still allowing the flexibility of raw SQL when needed. In this article, we’ll explore how to set up Eloquent within a WordPress plugin, leveraging its capabilities to build efficient and maintainable database-driven plugins.
Let’s dive in!
Prerequisites
Before we start, ensure you have the following:
- A working WordPress installation.
- Composer installed globally or locally on your machine. If you’re unfamiliar with Composer, it’s a dependency manager for PHP. Visit Composer’s official page to download and learn more.
Step 1: Set Up the Plugin Directory
Navigate to your WordPress plugins directory:
cd wp-content/plugins
Create a folder for your plugin. For this guide, we’ll call it eloquent-plugin
:
mkdir eloquent-plugin && cd eloquent-plugin
Next, initialize the plugin by creating a main file named eloquent-plugin.php
:
<?php
/*
Plugin Name: Eloquent Plugin Example
Plugin URI: https://example.com
Description: A WordPress plugin utilizing Eloquent ORM.
Version: 1.0.0
Author: Your Name
Author URI: https://yourwebsite.com
License: GPL2
*/
if (!defined('ABSPATH')) exit;
// Define constants
if (!defined('ELOQUENT_PLUGIN_DIR')) {
define('ELOQUENT_PLUGIN_DIR', plugin_dir_path(__FILE__));
}
// Include the autoloader and initialize the plugin
require_once ELOQUENT_PLUGIN_DIR . 'core/init.php';
Step 2: Install and Configure Eloquent
Install the Eloquent package using Composer:
composer require illuminate/database
Your plugin folder should now include a vendor
directory, along with composer.json
and composer.lock
files. Update composer.json
to configure autoloading:
{
"require": {
"illuminate/database": "^10.0"
},
"autoload": {
"psr-4": {
"App\\Models\\": "app/Models",
"App\\Controllers\\": "app/Controllers"
}
}
}
Run the following command to regenerate the autoload files:
composer dump-autoload
Create the necessary folder structure:
mkdir -p app/Models app/Controllers core
Step 3: Connect Eloquent to the WordPress Database
Create a file named core/init.php
and configure the Eloquent database connection:
<?php
require_once ELOQUENT_PLUGIN_DIR . '/vendor/autoload.php';
use Illuminate\Database\Capsule\Manager as Capsule;
// Initialize Eloquent
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => DB_HOST,
'database' => DB_NAME,
'username' => DB_USER,
'password' => DB_PASSWORD,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => $wpdb->prefix,
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
// Autoload additional core files
require_once ELOQUENT_PLUGIN_DIR . 'core/helpers.php';
Step 4: Create a Model
Define your database model in the app/Models
directory. For example, let’s create a model for a clients
table:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
protected $table = 'clients';
public $timestamps = false;
protected $fillable = [
'name', 'email', 'phone', 'purchased_service'
];
}
Step 5: Register a Custom Database Table
Create a file named core/create_db_tables.php
to register a custom database table during plugin activation:
<?php
function create_client_table()
{
global $wpdb;
$table_name = $wpdb->prefix . 'clients';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
phone varchar(15),
purchased_service varchar(255),
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__, 'create_client_table');
Step 6: Create a Controller
Define controller logic in app/Controllers
. For example, create an ActionController
for AJAX requests:
<?php
namespace App\Controllers;
use App\Models\Client;
class ActionController
{
public function create()
{
$client = Client::create([
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
'purchased_service' => $_POST['purchased_service']
]);
wp_send_json_success($client);
}
public function delete()
{
$client = Client::find($_POST['id']);
$client->delete();
wp_send_json_success();
}
}
Register the AJAX actions in core/init.php
:
$actionController = new App\Controllers\ActionController;
add_action('wp_ajax_create_client', [$actionController, 'create']);
add_action('wp_ajax_delete_client', [$actionController, 'delete']);
Step 7: Create a Shortcode
Add a shortcode to display the client list. Define it in core/helpers.php
:
<?php
function load_view($view, $data = [])
{
extract($data);
include ELOQUENT_PLUGIN_DIR . "views/{$view}.php";
}
add_shortcode('eloquent_clients', function () {
$clients = App\Models\Client::all();
load_view('clients', ['clients' => $clients]);
});
Create the views/clients.php
file:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Service</th>
</tr>
</thead>
<tbody>
<?php foreach ($clients as $client): ?>
<tr>
<td><?= $client->name ?></td>
<td><?= $client->email ?></td>
<td><?= $client->phone ?></td>
<td><?= $client->purchased_service ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Conclusion
By integrating Eloquent into WordPress, you can enjoy the power of Laravel’s ORM while still leveraging WordPress’s ecosystem. This setup is especially useful for custom plugins requiring complex database interactions.
However, remember that this approach introduces additional database connections, which can be problematic if multiple plugins adopt similar strategies. Use it wisely for bespoke projects or tightly controlled environments.
Leave a Reply