Laravel Tutorial:
Rest API Call

Posted in Laravel on 20 December 2020

To build a Laravel application that pulls posts from a REST API and displays them on a WordPress website, the process involves a few main steps: creating the Laravel application, fetching the posts from the REST API, preparing the data for WordPress, and integrating the data into your WordPress site. Here’s a structured approach to achieving this.

1. Setting up the Laravel Application

First, you need to set up a Laravel application. If you haven’t done this before, you can install Laravel using Composer. Run the following command:

composer create-project --prefer-dist laravel/laravel blog

This will create a basic Laravel application in a folder named blog. You can navigate into the directory and set up your environment by configuring the .env file. Set your database and other required configurations if needed.

2. Creating the API Call in Laravel

Laravel provides a clean way to make HTTP requests using its Http client, which is built on top of Guzzle. To fetch posts from an external REST API, you can create a controller that handles the API request.

First, generate a controller:

php artisan make:controller PostController

Inside PostController, you can create a method that fetches the posts from the REST API:

use Illuminate\Support\Facades\Http;

class PostController extends Controller
{
    public function fetchPosts()
    {
        // Make a GET request to the REST API
        $response = Http::get('https://api.example.com/posts');
        
        // Handle the response, assuming the posts are in JSON format
        $posts = $response->json();

        // Return the posts to be used in WordPress or another view
        return view('posts.index', ['posts' => $posts]);
    }
}

This example assumes the API endpoint is https://api.example.com/posts and that it returns a JSON response. You can adjust this URL based on the actual API you are working with.

3. Preparing the Data for WordPress

To display the fetched posts on a WordPress site, you need to decide how to pass the data from Laravel to WordPress. There are a few possible approaches:

Option 1) Rendering in a View and Embedding in WordPress

One approach is to render the posts within a Laravel view and then embed that view in WordPress using an iframe or AJAX request.

Create a Blade view in resources/views/posts/index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Posts</title>
</head>
<body>
    <h1>Posts from the API</h1>
    <ul>
        @foreach($posts as $post)
            <li></li>
        @endforeach
    </ul>
</body>
</html>

You can then create a WordPress page or widget that loads this view using an iframe. In your WordPress template, you can embed it as follows:

<iframe src="https://your-laravel-app.com/posts" width="100%" height="600"></iframe>

Option 2) API-to-API Integration Between Laravel and WordPress

Alternatively, you can have the Laravel application serve an API endpoint, and WordPress can make an HTTP request to this endpoint to fetch the data.

In Laravel, you can create an API route in routes/api.php:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'fetchPosts']);

This would expose the posts as an API endpoint, which you can fetch from WordPress using the WordPress HTTP API or custom PHP code.

In WordPress, you can use the following to make a request:

$api_url = 'https://your-laravel-app.com/api/posts';
$response = wp_remote_get($api_url);

if (is_wp_error($response)) {
    return 'Unable to retrieve posts';
}

$body = wp_remote_retrieve_body($response);
$posts = json_decode($body, true);

// Loop through the posts and display them
if ($posts) {
    foreach ($posts as $post) {
        echo '<h2>' . esc_html($post['title']) . '</h2>';
    }
}

4. Displaying the Posts in WordPress

If you chose the iframe approach, the Laravel app will render the posts directly within WordPress. On the other hand, if you opted for the API-to-API method, the data will be fetched in JSON format, decoded, and displayed using a custom WordPress template or shortcode.

5. Security and Performance Considerations

Ensure that any data sent between your Laravel application and WordPress site is secure. This can involve using HTTPS for both applications and possibly adding authentication to your API requests if the data is sensitive or requires access control.

You should also consider caching the data either on the Laravel or WordPress side, particularly if the API you are fetching data from has rate limits or if you want to reduce the load on your systems.

By following this approach, you will have a Laravel application that successfully pulls posts from a REST API and displays them on your WordPress website, either by rendering through an iframe or fetching the data via API and integrating it directly into your WordPress templates.

Related Laravel Posts

September 2024

Combining Laravel with WordPress

Combining Laravel with WordPress offers a unique and powerful approach to web development, blending the strengths of both platforms to create highly efficient, flexible, and... Continue reading

December 2022

Quick Start Guide for Laravel on a PHP Server

Laravel is a powerful and popular PHP framework designed to make web development easier and more efficient. This quick start guide will help you set... Continue reading

October 2021

What is Laravel?

Laravel is an open-source web application framework written in PHP, designed to make the development process faster, easier, and more streamlined. It follows the **Model-View-Controller**... Continue reading

More Laravel Posts