Query WordPress from Laravel with Corcel β€” No HTTP Overhead

πŸ“– 2 minutes read

Instead of using WordPress REST API from Laravel (HTTP overhead), use the Corcel package (jgrossi/corcel) to query WordPress tables directly via Eloquent. Both applications share the same MySQL database.

Why This Matters

Eliminates HTTP overhead between Laravel and WordPress. Direct database access is 10-50x faster than REST API calls. Enables real-time data access with zero sync lag.

The Setup

1. Install Corcel

composer require jgrossi/corcel

2. Add a separate database connection in config/database.php

'connections' => [
    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST'),
        'database' => env('DB_DATABASE'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'prefix' => '',  // Laravel tables have no prefix
    ],
    
    'wordpress' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST'),
        'database' => env('DB_DATABASE'),  // Same database!
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'prefix' => 'wp_',  // WordPress tables use wp_ prefix
    ],
],

3. Use Corcel models

use Corcel\Model\Post;
use Corcel\Model\User;

// Query WordPress posts
$posts = Post::type('product')
    ->status('publish')
    ->taxonomy('category', 'featured')
    ->get();

// Access custom fields (ACF)
$price = $post->meta->price;
$sku = $post->meta->sku;

// Query users
$wpUsers = User::all();

Division of Labor

  • WordPress: Content management, ACF fields, admin UI
  • Laravel: API endpoints, business logic, scheduled tasks
  • Shared MySQL: Single source of truth, zero sync lag

Advanced: Custom OAuth Guard with Corcel

// Direct Corcel query - no HTTP!
class WpOAuthGuard implements Guard
{
    public function user()
    {
        $token = request()->bearerToken();
        
        // Direct database access via Corcel connection
        $tokenData = DB::connection('wordpress')
            ->table('oauth_tokens')
            ->where('access_token', $token)
            ->where('expires', '>', time())
            ->first();
            
        if (!$tokenData) return null;
        
        return User::find($tokenData->user_id);
    }
}

The payoff: WordPress handles content management (what it’s good at), Laravel handles API/logic (what it’s good at), and Corcel makes them work together at database speed.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *