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


Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

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]

Top Laravel Development Companies Reviews

Top Laravel Development Companies Reviews

Among the list of Best Laravel development companies, TopDevelopers has chosen the most acclaimed laravel developers for the visitors so as to make them avail the extremely wonderful service ever offered. The web development companies listed here...

Among the list of Best Laravel development companies, TopDevelopers has chosen the most acclaimed laravel developers for the visitors so as to make them avail the extremely wonderful service ever offered. The web development companies listed here have passed the stringent assessments carried out by TopDevelopers in order to get approved as top Laravel service providers. Get in touch with the most sought-after Laravel developers in the market for your assistance.

Here is the List of Best Laravel Development Companies.