Step by step guide to display wordpress posts in Laravel 5

2024-03-28 08:25:18 Aveenesh Laravel

Fetching WordPress posts in Laravel

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 and display WordPress posts in our Laravel website pages.

Step 1 : Configure multiple database in Laravel 5.8

In this step we will see how to configure multiple database in Laravel 5.8. In order to configure two or more databases in laravel 5.8, 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.

 'wordpress_db' => [
      'driver' => 'mysql',
      'host' => env('DB_HOST', '127.0.0.1'),
      'port' => env('DB_PORT', '3306'),
      'database' => env('DB_DATABASE', 'forge'),
      'username' => env('DB_USERNAME', 'forge'),
      'password' => env('DB_PASSWORD', ''),
      'unix_socket' => env('DB_SOCKET', ''),
      'charset' => 'utf8mb4',
      'collation' => 'utf8mb4_unicode_ci',
      'prefix' => 'wp_',
      'strict' => true,
      'engine' => null,
    ],

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".

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{
  protected $connection = 'wordpress_db';   
  protected $table = 'posts';
  protected $primaryKey = 'ID';
} 

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.

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{

  protected $connection = 'wordpress_db';   
  protected $table = 'posts';
  protected $primaryKey = 'ID';
  // adding a global scoope in yoour post model
  protected static function boot()
  {
    parent::boot();

    static::addGlobalScope('post_type', function (Builder $builder) {
      $builder->where('post_type','post');
       
    });
  }

} 

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


//fetching single post by id
$post= \App\Post::find(1);
//Fetching all publish post
$posts=\App\Post::where('post_status','publish');


This post is submitted by one of our members. You may submit a new post here.

Related Tricks