Laravel Quick start guide

Estimated duration: 10 minutes

This guide shows you how to connect Prepr to a Laravel project to get data from Prepr CMS. You'll learn how to make a simple blog with Laravel and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.

Blog site end result

Info


You can also watch the video for step-by-step instructions that are detailed in the guide below.

This video was created using AI avatars and voices to ensure a consistent look and feel. The use of AI matches our culture of using innovative technologies.

Prerequisites

You need to have the following setup before you connect your Laravel project to Prepr.

Step 1: Create a new Laravel project

Before creating your first Laravel project, you should ensure that your local machine has PHP and Composer installed. If you are developing on macOS, PHP and Composer can be installed via Homebrew. In addition, we recommend installing Node and NPM. If you want to learn more about how to install Laravel for your system, check out the Laravel docs.

This guide is based on Laravel 10. The instructions below will guide you on how to create an empty Laravel project for your blog app. If you have an existing Laravel 10 project then you can skip this step.

  1. Open a terminal and execute the following command to create a new Laravel project called prepr-laravel:
composer create-project laravel/laravel prepr-laravel
  1. When the project is successfully created, go to the prepr-laravel folder, the root directory of the project, and run the project with the following commands in the terminal:
cd prepr-laravel
php artisan serve
  1. You should now be able to view your app on your localhost, for example, http://localhost:8000/.

  2. Open your Laravel project with your preferred code editor.

  3. Go to the resources/views subfolder and replace the code in the welcome.blade.php file with the following code to display your blog:

<!-- ./resources/views/welcome.blade.php -->

<div>
    <h1>My blog site</h1>
</div>

You should now see something like the image below on your localhost.

view component

Step 2: Install the Laravel GraphQL SDK

The Laravel GraphQL SDK is an integration tool that helps to retrieve Prepr CMS data with GraphQL. The instructions below show you how to install the Laravel GraphQL SDK so that you can execute GraphQL queries to request data from the Prepr API.

  1. Execute the following command in the terminal:
composer require preprio/laravel-graphql-sdk
  1. Update the services.php file in the config folder to add the Prepr endpoint service:
<!-- ./config/services.php  -->
 
<?php

return [
  
/*
 Include the Prepr endpoint service
*/
    'prepr' => [
        'endpoint' => env('PREPR_ENDPOINT'),

        /*
          Optional timeout settings
        */
        'timeout' => env('PREPR_TIMEOUT'),
        'connect_timeout' => env('PREPR_CONNECT_TIMEOUT')
    ]
];
  1. Go to the .env file in the root directory of your project and set the Prepr endpoint variable with the config below.
# ./.env

PREPR_ENDPOINT=<YOUR-PREPR-API-URL>

# Optional variables for custom timeout values, Default Laravel defaults are 30 and 10 
PREPR_TIMEOUT=<YOUR-TIMEOUT-IN-SECONDS>
PREPR_CONNECT_TIMEOUT=<YOUR-CONNECT-TIMEOUT-IN-SECONDS>
  1. Replace the placeholder value <YOUR-PREPR-API-URL> with the API URL from a Prepr access token. Get this URL by logging into your Prepr account:

    a. Go to Settings > Access tokens to view all the access tokens.

    b. Copy the API URL value from the GraphQL Production access token to only retrieve published content items on your site.

    access token list

Note

Use the GraphQL Production API URL to request published content items for your live app and use the GraphQL Preview value to make a preview of unpublished content items for your content editors.

Now refresh the app in your browser, if your app runs without errors, then the setup above was done correctly. The next step is to fetch content from Prepr using the installed GraphQL SDK.

Step 3: Fetch multiple articles

Now that the Laravel GraphQL SDK is installed and connected to Prepr, fetch the blog articles from Prepr.

Add a GraphQL query

In the app folder, create a queries subfolder. In this folder, create a file named get-articles.graphql and add the following query to this file to retrieve all articles:

# ./app/queries/get-articles.graphql

query {
  Articles {
    items {
      _id
      _slug
      title
    }
  }
}

Tip

You can create and test GraphQL queries using the Apollo explorer from Prepr. Open the API Explorer from the Article content item page in Prepr or the access token page.

If you’re using preloaded demo data in your Prepr CMS environment as mentioned above in the Prerequisites section, you should have a few published articles as shown in the below image. The query will retrieve the ID, Slug, and Title of each article.

demo articles

In the next step, we'll fetch and process the query response.

Fetch data

Now that the query has been added, fetch the articles from Prepr to display them in the app.

  1. Create a controller to construct the page for the fetched data by executing the following command:
php artisan make:controller BlogController
  1. Go to the subfolder App/Http/Controllers and replace the content in the BlogController.php file with the following code to call the query and construct the page:
<?php

namespace App\Http\Controllers;

// Include the Http classes to call the query
use Illuminate\Support\Facades\Http;

class BlogController extends Controller
{
    // This function gets the query response and returns a view of the list of articles
    public function index()
    {
       $response = Http::prepr([

        // Call the query
           'query' => 'get-articles'
       ]);

       // Construct a view from the pages folder
       return view('pages.index', [

          //Assign the 'articles' to query response
          'articles' => data_get($response->json(), 'data.Articles'),
       ]);
    }
}

When you refresh the app in your browser, you still see the welcome page that you previously updated. This is because you need to create a route to your BlogController.

Create a route

To get the Laravel app to display your page, you need to create a route to this page. In Laravel, you can register web routes for your application in the web.php file in the routes folder. Replace the config in the web.php file with the code below to add the route to your main page that will show a list of articles:

<!-- ./routes/web.php -->

<?php

use Illuminate\Support\Facades\Route;

// Include the BlogController class
use App\Http\Controllers\BlogController;

// Add a route to the BlogController function
Route::get('/', [BlogController::class, 'index']);

Now when you refresh the app in your browser, you see an error like the image below.

no view error

This is because you don't have a view defined for the layout of the page yet. In the next step, you'll create the view to resolve this error and display the list of articles.

Create a view

Go to the resources/views subfolder and create a new folder called pages. Move the welcome.blade.php that you updated previously to this folder and rename it to index.blade.php. Add the following code to display the data retrieved from the query:

<!-- ./resources/views/pages/index.blade.php -->

<div>
  <h1>My blog site</h1>
   
    <!-- Check if any articles are retrieved -->
    @if(data_get($articles,'items'))
        <ul>

          <!-- Loop through each of the retrieved articles -->
          @foreach(data_get($articles,'items') as $article)
            <li>

              <!-- Display the title value -->
              {{ data_get($article,'title') }}
            </li>
          @endforeach
        </ul>
    @endif
</div>

Now when you refresh the app in the browser, you see the list of articles like the image below.

articles on site

Step 4: Fetch individual articles

Now that you have the list of articles, add links to them. When a visitor clicks on a link, your app should open a detailed article page automatically. The instructions below show you how to add the links and routing from the main page to the detailed page and how to fetch the article details based on the slug of the article that was clicked.

Go to the resources/views/pages subfolder and add a link to the index.blade.php file with the code below to make the article titles clickable.

 <!-- ./resources/views/pages/index.blade.php -->

<div>
   <h1>My blog site</h1>
   @if(data_get($articles,'items'))
       <ul>
           @foreach(data_get($articles,'items') as $article)
               <li>
               
                <!-- 
                  Create a link for each article title
                  to a URL that includes the retrieved slug 
                -->
                <a href="{{ url(data_get($article,'_slug')) }}">{{ data_get($article,'title') }}</a>

               </li>
           @endforeach
       </ul>
   @endif
</div>

When you refresh the app in your browser, you can see that each article has its own link. When you click on the link, a new page opens with the slug in the URL, but a Page 404 error is displayed. Continue with the next step to fetch the article details and resolve this issue.

Fetch article details

Add another query to fetch a specific article by its slug and make this page visible when clicking on an article.

  1. Go to the app/queries subfolder and create a file called get-article-by-slug.graphql. Add the following query to this file to query a specific article by its slug:
# ./app/queries/get-article-by-slug.graphql

query ($slug: String) {
   Article (slug: $slug) {
     _id
     title
     content {
       __typename
       ... on Text {
         body
         text
       }
       ... on Assets {
         items {
           url
         }
       }
     }
   }
}

Now that the query is added, fetch the individual article by its slug. Fetch the article title and the article content.

Note

  1. Add another function to the BlogController.php as shown below to fetch the article details.
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;


class BlogController extends Controller
{
   public function index()
   {
       $response = Http::prepr([
           'query' => 'get-articles'
       ]);

      /* 
        Optional: Output query response to the console 
        (Will appear in the browser)
       */
       dump($response->json());

       return view('pages.index', [
           'articles' => data_get($response->json(), 'data.Articles'),
       ]);
    }

    /*
      This function gets the query response and 
      returns a view of an article's details
    */
   public function show(string $slug)
   {
       $response = Http::prepr([
           'query' => 'get-article-by-slug',
           'variables' => [
               'slug' => $slug,
           ]
       ]);

       if(data_get($response->json(), 'data.Article')) {
           return view('pages.show', [
               'article' => data_get($response->json(), 'data.Article'),
           ]);
       }
       abort(404);
   }
}

Now that the controller includes a function to fetch the article details, add the route to this article detail page.

  1. Add a route for the article detail page by updating the web.php file in the routes folder.
<!-- ./routes/web.php -->

<?php

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

Route::get('/', [BlogController::class, 'index']);

/**  
 * Add a route that directs to the detailed page
 */
Route::get('/{slug}', [BlogController::class, 'show']);

Once again, when you click on an article, you get an error because the view is missing. Add the view next and resolve this error.

  1. Go to the resources/views/pages subfolder and create a new file show.blade.php to set up the layout for page with the following code:
<!-- ./resources/views/pages/show.blade.php -->

<div>
   <h1>{{ data_get($article,'title') }}</h1>

    <!-- Check if article details are retrieved -->
    @if(data_get($article,'content'))

         <!-- Loop through each of the content types in the article -->
        @foreach(data_get($article,'content') as $content)

            <!-- Display an image -->
            @if(data_get($content,'__typename') === 'Assets')
               <div class="my-10">
                   <img src="{{ data_get($content,'items.0.url') }}" width="300" height="250"/>
               </div>
            @endif

            <!-- Display the text -->
            @if(data_get($content,'__typename') === 'Text')
               <div>
                   {!! data_get($content,'body') !!}
               </div>
            @endif
        @endforeach
    @endif
</div>

Now when you click on an article, you see a detailed article page like in the image below.

Article end result

All done

Congratulations! You have successfully connected a Laravel project to Prepr for a simple Blog app.

Next steps

To learn more on how to expand your project, check out the following resources: