Getting Started with Contentful and Laravel

This tutorial will show you how to setup the Content Delivery API in your Laravel application and how to access your content inside the framework.

Requirements

The Contentful Laravel integrations requires at least PHP 5.5.9 and Laravel 5. PHP 7 is supported.

Installation

The easiest way to install the Laravel integration is is to use Composer. If you've downloaded composer.phar, the integration can be installed by executing:

php composer.phar require contentful/laravel

Enable the Service Provider

Next you need to enable the Service Provider by adding it to config/app.php:

<?php
return [
    'providers' => [
        // ...
        Contentful\Laravel\ContentfulServiceProvider::class,
        // ...
    ]
];

Configuration

Before the Contentful SDK can be configured, the necessary config files have to be published. To do so execute the following command:

php artisan vendor:publish  --provider="Contentful\Laravel\ContentfulServiceProvider"

This will add a file called contentful.php to your /config folder.

Now open that file and fill in your space ID and API key.

<?php
return [
  'delivery.space' => 'cfexampleapi',
  'delivery.token' => 'b4c0n73n7fu1'
];

To use the Preview API instead of the Content Delivery API, simply add 'delivery.preview' => true:

<?php
return [
  'delivery.space' => 'cfexampleapi',
  'delivery.token' => 'e5e8d4c5c122cf28fc1af3ff77d28bef78a3952957f15067bbc29f2f0dde0b50',
  'delivery.preview' => true
];

Using Contentful

You now have a service for the class Contentful\Delivery\Client available. A small controller displaying an entry based on an ID in the URL could look like this:

<?php

use Illuminate\Routing\Controller as BaseController;
use Contentful\Delivery\Client as DeliveryClient;

class DefaultController extends Controller
{
    /**
     * @var DeliveryClient
     */
    private $client;

    public function __construct(DeliveryClient $client)
    {
        $this->client = $client;
    }

    public function entryAction($id)
    {
        $entry = $this->client->getEntry($id);

        if (!$entry) {
            abort(404);
        }

        return view('entry', [
            'entry' => $entry
        ]);
    }
}

To discover how to use the Contentful client, check out the getting started with Contentful and PHP tutorial.

Conclusion

Now you should be familiar with the basics of how to use Contentful in a Laravel application. You can find the integration on GitHub and Packagist. To get a deeper understanding, read some of our other PHP tutorials. If you find a bug, or have an idea how to further integrate with Laravel, please open an issue on GitHub.