Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Headless Drupal & Laravel | A blog concept in Laravel linked to a Drupal 8 REST API

Parent Feed: 

(Available as freelancer)

Joris Snoek

Business Consultant
/ Drupal Developer

Lately I have been hearing a lot about Laravel. This is a PHP framework to build web applications and that is quickly gaining popularity. I wanted to test it to keep up to date with this current technology. So I thought: I will build a concept in Laravel to see how it works and to compare it with Drupal 8.

My goals:

  • A static page in which the content is loaded from a local database.
  • Build a list of Blog items which is fed from a Drupal 8 RESTful API (which I had previously built for Node.js).

Overall content of this blog:

  1. Introduction to Laravel
  2. Laravel’s foundation
  3. Installing Laravel
  4. Routing in Laravel
  5. Laravel’s Migration: management of the database structure
  6. Eloquent ORM: query the database
  7. HTML templating in Laravel: Blade and Views
  8. Loading data from a RESTful Drupal 8 API

1. Introduction to Laravel

Required tools and knowledge

In order to participate you will need to have the following basic knowledge and tools:

  • PHP: intermediate knowledge
  • HTML/CSS basic knowledge
  • Good code editor (IDE), I am using PHPStorm
  • A browser, f.e. Firefox

What is Laravel

  • A PHP framework for web applications
  • Developed by Taylor Otwell
  • First release: February 2012
  • Open Source (MIT licence)

Why Laravel

According to the developers it is a 'clean, modern web application framework’, which is built on other great tools. In addition, it is said that Laravel is ‘fun to code’.

Laravel is a MVC Framework

  • MVC = Model View Controller, a modern structure of web applications.
  • Model: application data and functionalities
  • View: the visible output, the HTML
  • Controller: interaction between user, model and view. Facilitated in Laravel by PHP.

Standard tools in Laravel

  • Routing of incoming requests
  • HTML templating (Blade)
  • Database definition and version control (Laravel’s Migrations and Eloquent ORM)
  • Authentication: login users and manage permissions.
  • Emailing with attachments

Laravel core is not a cms like Drupal 8

Laravel out of the box is not a cms. There is a cms component available (October cms), but in this regard Laravel cannot be compared with Drupal 8, which does offer in the core full blown cms functionalities. If you want to compare Laravel with Drupal, you will need to do this on the level of Drupal API and not Drupal cms.

2. Laravel’s foundation

Laravel’s foundation is built on strong components:

  1. Symfony for core Laravel functionalities: including simulation, access to files and debugging. Drupal 8 is also using Symfony components.
  2. Composer: a dependency manager where hundreds of packages are already available. (similar to NPM for Node.js). Composer can also be used in Drupal 8, but not to the extent of Laravel: Drupal 8 is using modules with YAML files for this.
  3. Eloquent ORM (Object Relational Mapper): object oriented database management. Similar to the Database abstraction layer in Drupal 8
  4. Migrations: database version control for Laravel. This is similar to the schema API in Drupal 8 and Migrations from Ruby on Rail Migrations.
  5. Blade: html templating system, Drupal 8 uses Twig.

Laravel is a framework built on several other strong frameworks. Below an explanation of each component:

2.1 Laravel’s foundation: Symfony

Symfony is one of the main components in Laravel. The following Symfony components are, among others, used in Laravel:

Future releases of Laravel
Laravel has announced to stay in sync with future releases of Symfony.

Symfony users
When you are a user of Symfony you can also use Laravel components.

2.2 Laravel’s foundation: Composer

Laravel uses Composer, a PHP dependency manager. The main features are:

  • Works on a ‘per project’ basis, not global.
  • Works on Mac, Windows and Unix.
  • The dependencies are defined in a JSON file: composer.json. Composer can also be used in Drupal 8. This approach is also similar to the package.json in Node.js where NPM is ‘acting’ as Composer, see also.
  • See Packagist.org for 3rd party packages that can be used in Laravel by installing them through Composer.

2.3 Laravel’s foundation: Eloquent ORM

Eloquent ORM is Laravel’s database component, similar to the Database abstraction layer in Drupal 8. ORM is an acronym for Object Relational Mapper. It has been developed for Laravel, but can also be used outside Laraval. It is using an Active record pattern for database CRUD actions. It can facilitate one-on-one, one-on-many and many-on-many relations.

2.4 Laravel’s foundation: Migrations

Tables can be created, structured and (version) controlled through Laravel’s Migrations. All this is done via code, not configuration.

2.5 Laravel’s foundation: Blade

Blade is Laravel’s html templating machine. A Blade file is saved with the extension ‘.blade.php’. Variables in the template file can be placed as follows: {{variable}} (XSS filtered) or {!! variable !!} (unfiltered, [!] only use this when you know exactly what you are doing). You can also use PHP functionalities and codes in blade files. Blade also supports subtheming and conditional controls. 

3. Installing Laravel

I am working on a Mac with OS X El Capitan. The current Laravel version is 5.1, and that is the version I am going to use. Go to Laravel docs and follow the instructions:

  • Make sure you have installed Composer.
  • Make sure the directory ~/.composer/vendor/bin is in your PATH, so that the laravel command is everywhere available. Learn here how.
  • Now you can install via the command laravel new a fresh Laravel installation. I am now going to my webroot and enter laravel new blog concept: a fresh Laravel installation will be created in the folder /blogconcept:

The created install:

  • You will get an ‘application key’. This will be used, among other things, to encrypt data, such as session data.
  • Go to the Laravel installation and run this command: php artisan serve to activate the Laravel server. Artisan is Laravel’s command line environment.

Go to your browser and navigate to http://localhost:8000. You should be seeing this:

4. Routing in Laravel

Routes are used to facilitate incoming page requests. This is similar to Drupal 7’s hook_menu() and Drupal 8’s routing system. The routes can be found in /app/Http/routes.php:

Static routes
In routes.php you will see the default homepage defined, which you saw above in the browser. Here you can add your own routes. Below an example of a page with static information:

In a browser:

Dynamic routes
Routes can also be built dynamically through working with variables:

Note the double quotes that are required to dynamically print out the variable. If you are using single quotes, Laravel will print literally {$person}.

In the browser:

5. Laravel’s Migrations: management of the database structure

First you will need a database, the standard used here is MySQL; I will make a database called ‘blog concept’. All the database settings are in config/database.php:

In this file you can set:

  • Fetch style
  • Type database: mysql is the standard, but Laravel also supports sqlite, pgsql and sql server.
  • The database connections, I am entering the following:

Tables can be managed manually through for example phpmyadmin, but that is not advisable. In Laravel the structure of tables/database can be programmed in code, resulting in flexibility and version control. ‘Database structure’ is also called ‘schema’.

By managing this in Laravel’s Migration developers can easily keep their databases in sync within a version control system, such as GIT. So you can also easily revert a database change.

Example: I am creating the initial migration file through command php artisan make:migration create_content_table. In the created file I am adding code that defines database tables:

This migration class exists of two methods: up and down. Up is used to create new tables, down is used to make the Up actions undone.

Execute command php artisan migrate, that will apply the migration code, and voila: the database tables are created:

More information: http://laravel.com/docs/5.1/migrations

6. Query the database with Eloquent ORM

For now I have manually filled the newly created tables with test content. Below a simple example to query this data:

  • Create a Model: php artisan make:model Content
  • Laravel creates the model in the /app folder:

  • The model is called ‘Content’ and not ‘Contents’, Laravel is smart enough to make that connection by itself.
  • Add the following code in routes.php:

$content = App\Content::find(1) => This is all it takes to query record with id=1 from the database table 'Contents', also here Laravel is smart enough to make the link with ‘Contents’. Then, all the fields from that record are stored in object $content, which can be assigned as variables to a blade template.

More information: http://laravel.com/docs/5.1/eloquent#defining-models

7. HTML templating in Laravel: Views & Blade

As previously indicated the HTML templating engine Blade is used in Laravel. The HTML files are called views, something else than Drupal Views: these are lists. An example of the use hereof can be seen immediately in the standard installation. In routes.php on line 15 the Laravel view ‘welcome’ is invoked: return view(‘welcome’);.

The views are included in the folder /resources/views, there you can also find the standard view ‘welcome.blade.php’:

An own dynamic view

Blade facilitates dynamically filling HTML pages. An example: I am creating a new view file called ‘about.blade.php’ and copy the HTML from welcome.blade.php:

I am adding the following code in routes.php:

You can see that the ‘about’ view is evoked through View::make() with an additional array included in which variables with content are defined that were previously loaded from the database.

Then I can use those variables in the Blade template:

In the browser:

FYI: more about Blade templates.

8. Data from a RESTful Drupal 8 API

As an example I am using the Drupal 8 API that I built earlier. The json output is looking like this:

First I played a bit around with Composer packages Buzz & Guzzle, both http clients. Those packages are facilitating much more than just retrieving data from a REStful API: POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading from JSON data, etc...

That is too much overhead, for now I can work with a standard php functionality: file_get_contents en json_decode:

  1. Create a new route: /blogs
  2. Query the json data from the external Drupal 8 RESTful API.
  3. Run through the json arrays data and create a new array where: key = url, value = blog title
  4. Render the Blade html view ‘blogs’.

Then I am copying an existing blade view and rename it to ‘blogs.blade.php’:

In this blade html view I am running through the associative array and am creating in this way a list with links:

Creating the detail page of a blog

Finally I would like to accomplish that when I click a link, the detail page of that blog appears:

  1. Create a new route with a variable
  2. Request the data from the Drupal 8 RESTful API.
  3. Look for a match in the url variable and a url in the json array from the API.
  4. When a match is found, create the variable: the title and body from the matched item.
  5. Render the html through a blade view.

In a browser:

As you can see, a lot still needs to be done concerning the styling. But as a purely functional concept, I am leaving it now the way it is.

Wrap up

Ok, that’s it for now. This is only an introduction in which I produced a concept. Many advanced components of Laravel have not yet been discussed, such as incorporating the logic code /routes.php that I placed to Models and Controllers. I would like to discuss this further in a next blog. Questions or feedback, let me know!

-- Cheers, Joris

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web