Skip to content

Instantly share code, notes, and snippets.

@jgrossi
Last active March 19, 2024 11:05
Show Gist options
  • Save jgrossi/1e9858c24e216112556e to your computer and use it in GitHub Desktop.
Save jgrossi/1e9858c24e216112556e to your computer and use it in GitHub Desktop.
How to use Eloquent (from Laravel) inside Wordpress
<?php // File location: /wp-content/themes/my-theme/src/Models/
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Car extends Eloquent
{
protected $table = 'cars';
protected $primaryId = 'id';
}
{
"require": {
"illuminate/database": "~5.0.0"
},
"autoload": {
"psr-4": {
"App\\": "wp-content/themes/my-theme/src/"
}
},
}
<?php // File location: /wp-content/themes/your-theme/
require __DIR__.'/../../../vendor/autoload.php'; // include composer inside Wordpress
/*
* Configure Eloquent (called Capsule when used alone)
*/
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
$capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher(new \Illuminate\Container\Container));
$capsule->setAsGlobal();
$capsule->bootEloquent();
// other code in functions.php here
<?php // File location: /wp-content/themes/my-theme/
$cars = App/Models/Car::all(); ?>
<!-- HTML or PHP code -->
<?php foreach ($cars as $car): ?>
<h1><?php echo $car->model_name ?></h1>
<?php endforeach; ?>
<!-- HTML or PHP code -->
@tareq1988
Copy link

I haven't updated the tareq1988/wp-eloquent because Eloquent is very slow. It takes a while to generate a query, let alone query the database. Also, Eloquent is used alongside of Laravel, which supports the latest PHP version all the time. But for WordPress plugins that's not the case. We have to support even PHP 5.6, which makes it a nightmare to keep up with the original package. That's why it didn't make sense to update the library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment