Step by step guide to display wordpress posts in Laravel 5.4

Sometimes we have two different databases in our application one for Laravel and other for WordPress to manage our website blog.In this post, we are going to see how to configure two databases in Laravel 5.4 and display WordPress posts in our Laravel website pages.

Configuring and using multiple databases in Laravel
Configuring and using multiple databases in Laravel

Step 1 : Configure multiple database in Laravel 5.4

In this step we will see how to configure multiple database in Laravel 5.4. In order to configure two or more databases in laravel 5.4, please open your config/database.php and add following code under mysql database configration array.

PS:Please change host,port,database,username,password and prefix values with yours.

Step 2 :Using wordpress database in your laravel Model

In models, Laravel provides a protected prooperty $connection to specify the coonnection you want to use in the specific model, by default it is configured to use default database.Too use wordpress database, please specify the connection name to “wordpress_db”.

Step 3 : Creating a parent scope in your model to display posts.

As you know WordPress keeps all types of posts in a single table named wp_posts, we have display or query only those rows where ‘post_type’ is ‘post’ , so we have created a global scope in our posts model to filter the records.

That’s it ,now simply add above model in your controller and fetch the post.