Using Corcel in Laravel to CRUD Wordpress Data

Ivica Jangelovski

Ivica Jangelovski

Experienced Software Engineer, WordPress Engineer

Laravel and Wordpress are with no doubt the most recognized open-source projects in the PHP community. The first one gives developers complete freedom and flexibility like no other framework before. The second one is the most widely used CMS across the internet, covering more than 34% of all existing websites. Yes, it’s true, at least that’s what the WordPress core people are saying on the official site. WordPress is also highly customizable, allowing developers to extend its functionality by leveraging the Wordpress developer APIs. Both of them are the “representatives” of the PHP language in its community nowadays.

As a developer, you may find yourself in a situation where you want to make use of the data coming from your WordPress blog. And that's where Corcel comes to the stage.

What is Corcel?

What is Corcel?

Corcel is a standalone PHP package which aims to allow developers to easily fetch, manipulate or communicate (doing CRUD operations) with the data from your WordPress blog.

The codebase of Corcel consists of a collection of PHP classes built on top of Eloquent ORM (from Laravel framework), that provides a fluent interface to connect and get data directly from a WordPress database.

Why choose Corcel over the WP REST API?

Good question. And the answer is the efficiency and speed that Corcel provides. It's simple. This package communicates directly with the WordPress database to give all it needs, while the REST API is calling WP and WP is calling the database (duplicating actions unnecessary). And that's not very likely to be efficient enough. Someone already raised that question so you can read more on this question on this GitHub issue. But let's go and try it.

Installation and configuration

As I said above, Corcel can be used as a standalone package on every PHP project, but the following examples are only for a Laravel installation. For more details about including Corcel in your other (not Laravel) PHP project, you can read the documentation on GitHub (the package repository has very clean and well-written documentation along with some usage examples).

Install with composer

The installation is pretty straightforward using the well-known composer. Run the following command from your terminal in order to install Corcel as a dependency:

composer require jgrossi/corcel

Now that we have Corcel added as dependency let's do the configuration work.

Configuration

Open your config/app.php file and include the CorcelServiceProvider at the bottom of the providers list:

'providers' => [
    Corcel\Laravel\CorcelServiceProvider::class,
]

Next step is to run the following artisan command from your terminal:

php artisan vendor:publish --provider="Corcel\Laravel\CorcelServiceProvider"

This will create the config/corcel.php configuration file in your config directory. We’ll get back to it later (after the main database config).

Database configuration

Open the main database configuration file config/database.php. Here you already have the connections array. In order to configure the params for the WordPress database that we'll be using, you’ll need to add one more element to it like this:

'corcel' => [ // You can name this connection name as you wish  
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'wordpress_database',
        'username'  => 'root',
        'password'  => 'root',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => 'wp_',
        'strict'    => false,
        'engine'    => null,
],

Now go back to the config/corcel.php file and add the name of the connection that you just created to the connection element (in our case it’s named corcel) and that's all (regarding the configuration of course)! Now let's see some usage examples from Corcel.

Code Samples

Corcel has few predefined models for the Posts, Pages, Meta, and all other entities. But you can extend those very easily. I'll provide a few examples of using Corcel to fetch Posts and Metadata.

Posts

Create a model called Post.php and at the top of it use the Corcel core Post model:

use Corcel\Model\Post as Corcel;

Get a specific post by ID:

Post::find($id);

Get the latest posts from the post types post, cpt_name and other_cpt that are assigned to the taxonomies category and category2:

Post::status('publish')
            ->whereIn('post_type', ['post', 'cpt_name', 'other_cpt'])
            ->whereHas('taxonomies', function ($query) {
                $query->whereIn('taxonomy',['category', 'category2']);
            })
            ->newest()
            ->get();

A method inside the model that returns the URL of the post featured image with the size that's given as parameter:

public function getPostThumbnailUrl($size = '')
{
    if ($this->thumbnail !== null && $this->thumbnail->size($size) !== null) {
       return $this->thumbnail->size($size)['url'];
    }

    return '';
 }

Metadata

According to the Codex, the post metadata is the "administrative" information you provide to viewers about each post. This information usually includes the author of the post, when it was written (or posted), and how the author categorized that particular post. Of course, this is only by default. Developers usually extend this data to fit their needs. One example of using the custom metadata is leveraged by YoastSEO - a plugin that helps you optimize your post SEO scores. It adds a unique meta description for each post in the <head> tag. One way to fetch this data to your post view in Laravel is to create a method in the Post model:

public function getYoastDescription()
    {
        return array_key_exists('_yoast_wpseo_metadesc', $this->getMetasAttribute()) ? $this->getMetasAttribute()['_yoast_wpseo_metadesc'] : '';
    }

As you can see this method is already using some methods that are written in the Corcel's core. We are just using them to make things cleaner in our view:

@section('metaDescription', $post->getYoastDescription())

The above will print the <meta> tag with the content attribute filled with the value that returned our method.

Corcel and ACF

There is also a way to get data from the ACF (Advanced custom fields) plugin. This plugin is essentially storing data as Metadata but in a more convenient way. In order to use it, you'll have to install it as a standalone package because it's not included in the main one that I wrote above. For more details check the repo for this package and you'll find the instructions there.

Summary

So far we have covered some ways of using Corcel. But there are many other examples that you can make use of that can be found in the official documentation on GitHub. We saw why you should use Corcel over WP REST API to fetch data into Laravel and how that benefits you.


Ivica Jangelovski

Experienced Software Engineer, WordPress Engineer