devonblzx / wp-eloquent
Eloquent ORM for WordPress, updated fork from tareq1988/wp-eloquent
dev-master
2017-01-18 21:11 UTC
Requires
- illuminate/database: 5.0.*
- illuminate/pagination: 5.0.*
This package is not auto-updated.
Last update: 2025-05-10 23:27:38 UTC
README
This is a library package to use Laravel's Eloquent ORM with WordPress.
This is an updated fork from tareq1988/wp-eloquent that I intend to maintain and enhance.
Package Installation
To install this package, edit your composer.json
file:
{ "require": { "devonblzx/wp-eloquent": "dev-master" } }
Now run:
$ composer install
Usage Example
Basic Usage
$db = \WeDevs\ORM\Eloquent\Database::instance(); var_dump( $db->table('users')->find(1) ); var_dump( $db->select('SELECT * FROM wp_users WHERE id = ?', [1]) ); var_dump( $db->table('users')->where('user_login', 'john')->first() ); // OR with DB facade use \WeDevs\ORM\Eloquent\Facades\DB; var_dump( DB::table('users')->find(1) ); var_dump( DB::select('SELECT * FROM wp_users WHERE id = ?', [1]) ); var_dump( DB::table('users')->where('user_login', 'john')->first() );
Retrieving All Rows From A Table
$users = $db->table('users')->get(); foreach ($users as $user) { var_dump($user->display_name); }
Here users
is the table name without prefix. The prefix will be applied automatically.
Other Examples
Writing a Model
use \WeDevs\ORM\Eloquent\Model as Model; class Employee extends Model { } var_dump( Employee::all()->toArray() ); // gets all employees var_dump( Employee::find(1) ); // find employee with ID 1
The class name Employee
will be translated into PREFIX_employees
table to run queries. But as usual, you can override the table name.
In-built Models for WordPress
- Post
- Comment
- Post Meta
- User
- User Meta
use WeDevs\ORM\WP\Post as Post; var_dump( Post::all() ); //returns only posts with WordPress post_type "post"
Filter Post
by post_status
and post_type
use WeDevs\ORM\WP\Post as Post; var_dump(Post::type('page')->get()->toArray()); // get pages var_dump(Post::status('publish')->get()->toArray()); // get posts with publish status var_dump(Post::type('page')->status('publish')->get()->toArray()); // get pages with publish status
How it Works
- Eloquent is mainly used here as the query builder
- WPDB is used to run queries built by Eloquent
- Hence, we have the benfit to use plugins like
debug-bar
orquery-monitor
to get SQL query reporting. - It doesn't create any extra MySQL connection
Minimum Requirement
- PHP 5.3.0
- WordPress 3.6+