Laravel and WordPress are two powerful platforms commonly used for web development and content management.
Laravel is a popular PHP framework that provides developers with a robust set of tools for building web applications, while WordPress, on the other hand, focuses more on content management and is commonly used for creating blogs and websites with simpler requirements.
Integrating both (Laravel WordPress) can help you streamline your web application development process by leveraging the WordPress backend for efficient management and a seamless workflow.
For instance, by integrating Laravel with WordPress, we can build an application that exports content directly from Google Docs to WordPress, eliminating the need for time-consuming manual transfers.
In this blog, we will discuss how to integrate Google Doc API with WordPress using Laravel, enabling us to retrieve documents from Google Docs and post them as blogs or posts in WordPress.
Nothing as Easy as Deploying Laravel Apps on Cloud
With Cloudways, you can run your PHP apps on managed cloud servers in just a few minutes.
Benefits of Integrating Laravel to WordPress
Integrating Laravel into WordPress can bring many benefits to your web development process. Below are some benefits of integrating Laravel into WordPress:
Improved Security
By integrating Laravel WordPress, developers can take advantage of Laravel’s security features and add an extra layer of protection to their websites.
Laravel has built-in security features such as CSRF protection, XSS protection, and encrypted password;. These security features are not available in WordPress by default and may require additional plugins or custom development to implement.
Furthermore, Laravel’s middleware feature can help protect against unauthorized access to certain parts of the website, such as the admin dashboard. Developers can use middleware to authenticate user access and enforce access controls, which can help prevent unauthorized access and protect sensitive data.
Customization
By integrating Laravel with WordPress, developers can leverage the strengths of both platforms and create custom WordPress plugins and themes that are highly customizable and tailored to meet specific business requirements.
Integration allow developers use Laravel’s blade templating engine to create custom WordPress templates that provide complete control over website layout and design. This feature can be particularly useful for building complex WordPress websites that require a high degree of customization.
Better API Integration
WordPress offers a REST API that allows developers to access and manipulate WordPress data through HTTP requests. However, the WordPress REST API has limitations, such as a limited set of endpoints and lack of support for custom data structures. Laravel, on the other hand, provides a robust API development framework that enables developers to create custom APIs with ease.
Integrating Laravel WordPress, developers can create custom API endpoints that provide access to WordPress data and functionality, such as custom post types, custom fields, and custom taxonomies. Developers can also use Laravel to create custom endpoints for interacting with third-party APIs, enabling WordPress websites to integrate with other web applications and services.
Easier Maintenance
WordPress websites can become complex and difficult to manage as they grow in size and complexity. Laravel, on the other hand, provides a structured and organized framework for managing website code and updates.
Integrating Laravel WordPress, developers can take advantage of Laravel’s modular architecture and use it to manage website code and updates. For example, developers can use Laravel to create custom WordPress plugins that are easier to manage and update, and that follow best practices for code organization and separation of concerns.
Laravel’s command-line interface (CLI) can be used to automate common website maintenance tasks. This can help reduce the time and effort required for website maintenance, and ensure that the website is running smoothly and efficiently.
Now that we’ve looked at some of the benefits of integrating Laravel and WordPress, let’s now quickly set up the environment for Laravel and WordPress integration.
Scale Your Website’s Success with Cloudways Autonomous
Integrate WordPress and Laravel effortlessly and ensure smooth operation with Cloudways Autonomous. Experience auto-scaling, top-tier security, and lightning-fast performance without the complexity of server management.
Setting up the Environment on Local Server
Setting up the environment for Laravel and WordPress integration involves a few steps
- Install XAMPP or WAMP Server: XAMPP and WAMP server are both widely used local servers
- Install WordPress
- Install Laravel by running the following command in your terminal or command prompt:
composer create-project --prefer-dist laravel/laravel project-name
This command will create a new Laravel project in a directory named ‘project-name’.
- Configure Laravel and WordPress: In order to integrate Laravel and WordPress, you need to configure Laravel to use the WordPress database.
- update the ‘config/database.php’ file in your Laravel project with the following code
'mysql' => [ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'wordpress_database_name', 'username' => 'wordpress_database_user', 'password' => 'wordpress_database_password', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],
- >integrate WordPress into Laravel by creating a route that points to the WordPress index.php file.
Route::get('/blog/{slug}', function ($slug) { define('WP_USE_THEMES', false); require('/path/to/wordpress/index.php'); });
- Replace ‘/path/to/wordpress/’ with the actual path to your WordPress installation.
- You can then access your WordPress site by visiting the URL ‘/blog/’ followed by the post slug.
That’s it! You’ve successfully set up the environment for Laravel and WordPress integration.
To get the best out of this Laravel and WordPress integration, you need to set up both of these applications on Cloudways. The platform provides an industry-leading Laravel hosting solution built on an amazing stack of tools, including Varnish, Redis, Memcache, and other features.
This is the configurations I’m going with:
- : 7.3 or higher
- : MySQL or MariaDB
- WordPress Plugin: Guzzle http package
- Memory: minimum of 256 MB of memory for optimal performance
Now that we’ve gotten that out of the way, it is time to integrate Laravel to Google Doc API.
Integrating Laravel to Google Doc API
Sign up with Google API
To integrate a Laravel application, sign in to your Google account first. Then, navigate to the Google Developers Console and create or select an existing project.
Now click ‘Continue’ and go to the credentials.
Choose Google drive API, select Web Server and check User Data.
Enter client ID name and enter Laravel route as redirect URLs. Enter your domain name instead of localhost address for production. Redirect URL will be used to redirect users back to your app after authentication. Create client ID and enter product name. Then, download JSON credentials file and save it.
Now, click on Enable API and Services from the dashboard.
Now, search for Google Drive and Google+ APIs and make sure both are enabled.
Next, install the Google API package.
composer require google/apiclient CONFIGURE GOOGLE SERVICE GOOGLE_APP_ID= GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= GOOGLE_REDIRECT_URL= GOOGLE_SCOPES="https://www.googleapis.com/auth/drive.readonly" GOOGLE_APPROVAL_PROMPT="force" GOOGLE_ACCESS_TYPE="offline"
Add these credentials to your .env file and add your APP_ID,CLIENT_ID,CLIENT_SECRET,REDIRECT_URL to your own credentials from the JSON file you have downloaded earlier.
Here, we are using the https://www.googleapis.com/auth/drive.readonly as a scope to get permission for reading Google Drive contents.
Now, create a Google class as App\Google.php:
<?php namespace App; class Google { public function client() { $client = new \Google_Client(); $client->setClientId(env('GOOGLE_CLIENT_ID')); $client->setClientSecret(env('GOOGLE_CLIENT_SECRET')); $client->setRedirectUri(env('GOOGLE_REDIRECT_URL')); $client->setScopes(explode(',', env('GOOGLE_SCOPES'))); $client->setApprovalPrompt(env('GOOGLE_APPROVAL_PROMPT')); $client->setAccessType(env('GOOGLE_ACCESS_TYPE')); return $client; } public function doc($client) { $doc = new \Google_Service_Docs($client); return $doc; } public function drive($client) { $drive = new \Google_Service_Drive($client); return $drive; } public function service($client) { $service = new \Google_Service_Books($client); return $service; } }
The code above establishes a connection with the Google client by passing the credentials from your .env file to the class. To get the Google Drive service, you have to pass in the client function which is also the credentials of the \Google_service_drive. It helps you to access files from your Google Drive and edit them as per the requirements. Likewise for the doc function which enable you to access the content of your documents file and allows you to change it as per needs.
Let’s get started with the Laravel core. First of all, we will create our controllers as defined below:
- php artisan make:controller AuthController;
- php artisan make:controller GoogleController;
The Authcontroller will handle our auth0 authentication and redirection, while the GoogleController will handle getting document content from drive API and posting it to WordPress API.
Let’s create our route from the routes\web.php:
Route::get('/login/google', 'AuthController@redirectToGoogleProvider'); Route::get('/login/google/callback', 'AuthController@handleProviderGoogleCallback'); Route::get('/post/blog', 'GoogleController@handlePost');
The /login/google/callback route is the redirect URL used when setting up a Google API.
Let’s start with the AuthController:
<?php namespace App\Http\Controllers; use App\Google; use Illuminate\Http\Request; class AuthController extends Controller { // public function index(){ return view('home'); } public function __construct(Google $google, Request $request) { $this->client = $google->client(); $this->drive = $google->drive($this->client); } public function redirectToGoogleProvider(GoogleDoc $googleDoc) { $client = $googleDoc->client(); $auth_url = $client->createAuthUrl(); return redirect($auth_url); } public function handleProviderGoogleCallback(Request $request) { if($request->has('code')){ $client = $this->client; $client->authenticate($request->input('code')); $token = $client->getAccessToken(); $request->session()->put('access_token',$token); return redirect('/home')->with('success','you have been authenticated'); }else{ $client=$googleDoc->client(); $auth_url = $client->createAuthUrl(); return redirect($auth_url); } } }
The ToGoogleProvider()
method requests for the user permission to manage the Drive data i.e by requesting the actual Google account.
The handleProviderGoogleCallback()
method allows us to get the token which has been passed from the redirectToGoogleProvider()
method. We can also use this method in sessions as access_token, to reduce repetitive actions for sending a request to the Google Drive API.
Before proceeding to our GoogleController which will handle our integration, we will first configure WordPress.
Configuring WordPress
As defined above in the prerequisites, we have already configured WordPress, and now we will download and install basic authentication plugin which will handle our authentication process.
Note: This plugin requires sending your username and password with every request, and should only be used for development and testing purposes i.e. not in a production environment. Other plugins like JSON Web Tokens etc can be used in production.
Coming back to our Laravel application, we need to install the Guzzlehttp package, which is quite handy for working with HTTP requests. A PHP HTTP client makes it easy to send and receive HTTP requests to integrate with web services.
Improve Your Laravel App Speed by 300%
Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.
Installing Guzzle
composer require guzzlehttp/guzzle:~6.0
Paste the following code to GoogleController:
GoogleController <?php namespace App\Http\Controllers; use App\Google; use GuzzleHttp\Client; use Illuminate\Http\Request; class GoogleController extends Controller { public function __construct(Google $google, Request $request) { $this->client = $google->client(); $this->drive = $google->drive($this->client); } public function handlePost(Request $request) { global $image_url; if ($request->session()->get('access_token')){ $client=$this->client; $client->setAccessToken($request->session()->get('access_token')); //getting document from drive that contain 'blog' $pageToken = NULL; $optParams = [ 'q'=>"name contains 'blog'", 'spaces'=>"drive", 'fields' =>"nextPageToken, files(id, name)", 'pageToken'=>$pageToken ]; $respon = $this->drive->files->listFiles($optParams)->getFiles(); foreach ($respon as $respons) { //getting the content of the documents $file = new \Google_Service_Docs($client); $document = $respons['id']; $doc = $file->documents->get($document); $contents = $doc->getBody()->getContent(); $datas = []; for ($i = 0; $i < count($contents); $i++) { if ($contents[$i]->getParagraph() == null) { continue; } $table = $contents[$i]->getParagraph()->getElements(); for ($j = 0; $j < count($table); $j++) { if ($table[$j]->getTextRun() == null) { goto image; } $cell = $table[$j]->getTextRun()->getContent(); array_push($datas, $cell); image: if ($table[$j]->getInlineObjectElement() == null) { continue; } $image_id = $table[$j]->getInlineObjectElement()->getInlineObjectId(); $url = $doc->getInlineObjects(); $image_url2 = "<img " . "src" . "=" . $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri . ">"; array_push($datas, $image_url2); $image_url = $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri; } } //connection to wordpress api $username = 'admin'; $password = 'admin'; $client = new Client([ 'base_uri' => 'http://localhost:8888/wordpress/wp-json/wp/v2/', 'headers' => [ 'Authorization' => 'Basic ' . base64_encode($username . ':' . $password), 'Accept' => 'application/json', 'Content-type' => 'application/json', 'Content-Disposition' => 'attachment', ] ]); // uploading featured image to wordpress media and getting id $name = $doc->getTitle() . '.' . 'jpg'; $responses = $client->post( 'media', [ 'multipart' => [ [ 'name' => 'file', 'contents' => file_get_contents($image_url), 'filename' => $name ], ] ]); $image_id_wp = json_decode($responses->getBody(), true); // uploading post to wordpress with featured image id $response = $client->post('posts', [ 'multipart' => [ [ 'name' => 'title', 'contents' => $doc->getTitle() ], [ 'name' => 'content', 'contents' => implode("", $datas) ], [ 'name' => 'featured_media', 'contents' => $image_id_wp['id'] ], ] ]); } return redirect('/home')->with('success','post has been created'); }else{ return redirect('/home')->with('error','you have not been authenticated'); } } }
The first thing is to get the access_token being put in session. Then, we will get our documents ID from Google Drive by passing the $optParams[]
to the listfiles()
method. The $optParams[]
specifies the type of file and directory we are trying to access, which in our case is any file that has ‘blog’ as part of its name in the root directory.
Note: You have to include ‘blog’ as part of the name on each document you are posting. You can still change the values of the $optParams[]
.
$pageToken = NULL; $optParams = [ 'q'=>"name contains 'blog'", 'spaces'=>"drive", 'fields' =>"nextPageToken, files(id, name)", 'pageToken'=>$pageToken ]; $respon = $this->drive->files->listFiles($optParams)->getFiles();
The next step is to loop through all the documents and getting their contents by passing the document ID to the get() method in the Google_service_Docs class.
Getting Content of the Document
The getContent()
method being called from the getBody()
method, displays the content of the document in an array i.e each line in your document is considered as an index of the getContent()
.
Looping through the getContent() array, we will get the getElements() method which is also an array().
Looping through the getElements()
will let us access the getTextRun()->getContent() that displays the value of the first paragraph in your document.
We will also try to get images ID from the document by using the getInlineObjectElement()
method from the getParagraph()->getElements() method. Then, we will pass the imageID as an index to the $doc->getInlineObjects() method to get the URL of the image.
Each line in your document is then pushed to the $data array, so that the content will look exactly the same as in the original document.
$file = new \Google_Service_Docs($client); $document = $respons['id']; $doc = $file->documents->get($document); $contents = $doc->getBody()->getContent(); $datas = []; for ($i = 0; $i < count($contents); $i++) { if ($contents[$i]->getParagraph() == null) { continue; } $table = $contents[$i]->getParagraph()->getElements(); for ($j = 0; $j < count($table); $j++) { if ($table[$j]->getTextRun() == null) { goto image; } $cell = $table[$j]->getTextRun()->getContent(); array_push($datas, $cell); image: if ($table[$j]->getInlineObjectElement() == null) { continue; } $image_id = $table[$j]->getInlineObjectElement()->getInlineObjectId(); $url = $doc->getInlineObjects(); $image_url2 = "<img " . "src" . "=" . $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri . ">"; array_push($datas, $image_url2); $image_url = $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri; } }
Connecting to WordPress API
Now, using the guzzlehttp package, we will setup the WordPress API URL authorization by passing the header array[], which will use our WordPress username and password encoded in base64.
//connection to wordpress api $username = 'admin'; $password = 'admin'; $client = new Client([ 'base_uri' => 'http://localhost:8888/wordpress/wp-json/wp/v2/', 'headers' => [ 'Authorization' => 'Basic ' . base64_encode($username . ':' . $password), 'Accept' => 'application/json', 'Content-type' => 'application/json', 'Content-Disposition' => 'attachment', ] ]);
Uploading the post’s featured image
Each WordPress post has a featured image that displays on the homepage. We will upload the featured image to our WordPress media using the WordPress API endpoint for the media.
Note: Based on this article, the last image on your document will be the featured image for the WordPress post.
Then, we will pass the $image_url variable being declared as global, to the file_get_contents method as the content of the post. Also the filename must be specified, having some image extension (jpg,png etc.).
// uploading featured image to wordpress media and getting id $name = $doc->getTitle() . '.' . 'jpg'; $responses = $client->post( 'media', [ 'multipart' => [ [ 'name' => 'file', 'contents' => file_get_contents($image_url), 'filename' => $name ], ] ]); $image_id_wp = json_decode($responses->getBody(), true);
It will return a JSON response, so that we can get the featured image ID and pass it together with the post.
Uploading your Post to WordPress
Finally, we will now upload our word document as a post in WordPress. We will pass the name of the document as the title of the post with the $getTitle()
method.
The content of the post will be the document that is being pushed to the $data[]. But we will have to pass in the $data[] to the implode()
, so as to convert it into a variable before uploading it to the post.
The featured image will be the featured image ID we got from the JSON response after uploading the image to the WordPress media.
// uploading post to wordpress with featured image id $response = $client->post('posts', [ 'multipart' => [ [ 'name' => 'title', 'contents' => $doc->getTitle() ], [ 'name' => 'content', 'contents' => implode("", $datas) ], [ 'name' => 'featured_media', 'contents' => $image_id_wp['id'] ], ] ]);
Routing in Laravel and WordPress Integration
In Laravel and WordPress integration, you can use Laravel’s routing system to define routes that point to WordPress pages. Here’s how you can set up routing in Laravel and WordPress integration:
- Open your Laravel project and navigate to the ‘routes/web.php’ file.
- Define a route for your WordPress page, like so:
Route::get('/blog/{slug}', function ($slug) { define('WP_USE_THEMES', false); require('/path/to/wordpress/index.php'); });
-
- In the callback function, we first define the ‘WP_USE_THEMES’ constant to false. This tells WordPress not to load the theme files.
<li”>We then require the ‘index.php’ file of your WordPress installation. This will bootstrap WordPress and allow you to access WordPress functions and data.
- Finally, you can use WordPress functions like ‘get_header()’ and ‘get_footer()’ to include the header and footer files of your WordPress theme.
Route::get('/blog/{slug}', function ($slug) { define('WP_USE_THEMES', false); require('/path/to/wordpress/index.php'); get_header(); // Your custom code here get_footer(); });
This code will include the header file of your WordPress theme before executing your custom code, and then include the footer file after your custom code.
That’s how you can set up routing in Laravel and WordPress integration.
Troubleshooting Common Issues During Integration
- Permalinks Not Working: If you have set up permalinks in WordPress, you might find that they don’t work when you integrate Laravel with WordPress. This is because WordPress and Laravel use different routing systems. To fix this issue, you can modify the .htaccess file in your WordPress root directory to include a rewrite rule that redirects all requests to your Laravel application.
- Session Issues: Laravel and WordPress both use session data, but they store it in different places. If you are trying to share session data between Laravel and WordPress, you might encounter issues. To solve this, you can use a package like laravel-wordpress-bridge that provides a simple interface for sharing session data between Laravel and WordPress.
- Authentication Error: If you are using the WordPress authentication system in your Laravel application, you might find that it doesn’t work as expected. This is because WordPress uses a different authentication system than Laravel. To fix this, you can create a custom authentication system that works with both Laravel and WordPress.
- Integration With WordPress Plugins: Some WordPress plugins might not work properly when integrated with Laravel. This is because the plugins might use WordPress-specific functions or rely on WordPress core functionality. To solve this, you can either find a Laravel equivalent for the plugin, or modify the plugin to work with Laravel.
- Performance Issues: Integrating Laravel and WordPress can result in performance issues, especially if you are using a shared hosting environment. To solve this, you can optimize your Laravel and WordPress applications for performance, and consider using a dedicated hosting environment.
Final Words
This brings us to the end of this article, which demonstrated in detail how to integrate Google Docs with WordPress using Laravel framework. Being a blogger or a content writer, it often seems quite tedious to manually copy and paste all the content from Google Docs to WordPress. It takes time, requires extra effort and sometimes gets mistaken for the actual content of the document.
That is why, this Laravel and WordPress integration article is meant for all those individuals who want to streamline their publishing work. It makes the writing and publishing process super easy and hassle free.
If you still have some queries or want to add your suggestions to this article, please feel free to write them in the comment section below.
Q) Can I use Laravel with WordPress?
A) Yes, you can use Laravel with WordPress. However, it requires a bit of customization and integration work to get them to work together seamlessly.
Q) Why WordPress is slower than Laravel?
A) WordPress is slower than Laravel due to its heavier reliance on plugins, which can increase page load times and cause performance issues, while Laravel’s lightweight framework and optimized codebase allow for faster and more efficient web development.
Q) Is Laravel better than WordPress?
A) Laravel and WordPress are both great tools, but they serve different purposes. Laravel is better for complex web applications, while WordPress is better for simple websites and blogs. Ultimately, the choice depends on your project’s requirements and goals.
Inshal Ali
Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.