How to use Corcel in Laravel to CRUD Wordpress Data

How to use Corcel in Laravel to CRUD Wordpress Data

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.

Originally published by Ivica Jangelovski at https://adevait.com

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.

Table Of Contents

  • What is Corcel?
  • Why choose Corcel over the WP REST API?
  • Installation and configuration
  • Code Samples
  • Corcel and ACF
  • Summary

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, cptname and othercpt 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. 

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

PHP with Laravel for beginners - Become a Master in Laravel

Projects in Laravel: Learn Laravel Building 10 Projects

Laravel for RESTful: Build Your RESTful API with Laravel

Fullstack Web Development With Laravel and Vue.js

Laravel 5.8 Tutorial for Beginners

Laravel 5.8 Ajax CRUD tutorial using Datatable JS

Laravel 5.8 Tutorial from Scratch for Beginners

Upgrading Laravel To 6.0 From 5.8

Laravel 6 Release New Features and Upgrade


Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Web Development Services

Web Development Services

As one of the best Web Application Development Company, it provides a fine quality mobile app development service at an affordable price. Especially, it encourage start-ups that have unique ideas, by offering a more competitive price

HireFullStackDeveloperIndia is rated as one of the top Web Application Development Company in India by various industry magazines and review sites. They have a right blend of award-winning designers, expert programmers and Google certified digital marketers which make them a unique one-stop solution for hundreds of our clients, spread across all countries.

A Good website reflects not only your business but also it is one of the main factors why a potential customer would convert into Client. A good website design helps increase traffic driving leads to grow business. The best web design company create a custom design for each corporate website so as to help them meet their business goals.

Get Quote: https://hirefullstackdeveloperindia.com/get-a-quote/

Hire Web Development Company in Chicago, USA

Hire Web Development Company in Chicago, USA

When you plan to develop a website, then you look forward to getting a complete solution, and hiring a Web Development Company in Chicago is the best result for this need.

Do you wonder what a full-stack developer is?

Let’s understand it further with this post…

A full stack developer is the one who apprehends the complete web development process and can fit with his expertise on any level of the development process.

However, finding a highly qualified full-stack developer is a tad tricky part of the business, as you need to understand and adopt the right technical expertise to initiate your web project.

If you are worried of picking the wrong resource, which could only hamper your business revenue goal through the website development then you need to consider the right approach suggested in this post, which can further help you hire full stack developer for your specific business needs.

What Does All Full Stack Developer do?

When it comes to web application development, then there is a different set of development, like for frontend and backend. They can be bifurcated into two basic divisions; one who builds the interfaces and rest who builds software engines behind it.

A full stack web developer can perform all these aspects, ranging from databases, front-end (client side) to server-side scripts. These developers have the capability of coding and even designing to a certain extent, also they can manage the complete project.

Full Stack Developers Are Responsible For:

  • Code programs and applications
  • Coordinate other developers and team members
  • Troubleshoot issues
  • Outline testing techniques for web apps
  • Manage web development

Technical expertise of a full-stack developer involves:

  • JavaScript
  • HTML
  • PHP
  • CSS
  • Angular
  • MySQL
  • Ruby
  • MongoDB
  • Node
  • Apache, etc.

Hiring a Full Stack programmer from HireFullStackDeveloperIndia is a lucrative deal, as we have a strong brood of highly experienced developers, who understand every bit of technology and the new market trends, and accordingly, update their knowledge bank.

Our development procedure involves a flexible assignation of different expertise of technologies and has catered our development services to many renowned brands globally.

Our team of full-stack developers is well-equipped with the complete knowledge of front-end and back-end technologies, which together offer a great solution. Our team holds the expertise to handle and manage the entire development and implementation process, whether it is for a website, web app or mobile app.

We are the master of many different technologies and have comprehensive knowledge about pertinent technologies consisting of MEAN stack, front end, back end, UI, server infrastructure, etc.

This is the sole reason, we are picked by a maximum number of businesses across the globe, needless to say, and we are competent enough to accomplish the entire development process based on the requirements of the esteemed clientele.

So without any further delay, simply get in touch with us, and help your business to scale higher…

You can hire the extremely talented and experienced team of full stack developer to form us at the most reasonable cost of $12-$18 hr and mark a change in your business with an effective web solution.