Home

6 minute read

Sidecar for Laravel

Tony Lea

Sidecar for Laravel

Sidecar is an awesome Laravel package that will allow you to run Lambda functions directly from your Laravel application. Meaning you can run Node, Python, Ruby, Java, Go, and many others through a Lambda function from inside Laravel. Truly Mind-blowing!

In this tutorial, you'll learn how to install, configure, and run code using Sidecar. First; how about a quick example to get you excited about this package 👏

👀 A Quick Example

Here is a quick example of a Sidecar Lambda function.

The first file defines how it will be deployed (App\Sidecar\ExampleFunction.php), and the other will be the file that gets deployed as your Lambda function (sidecar/example.js).

// App\Sidecar\ExampleFunction.php

<?php

namespace App\Sidecar;

use Hammerstone\Sidecar\LambdaFunction;
use Hammerstone\Sidecar\Package;
use Hammerstone\Sidecar\Runtime;

class ExampleFunction extends LambdaFunction
{

    public function handler()
    {
        return 'sidecar/example@hello';
    }

    public function package()
    {
        return [
            'sidecar/example.js'
        ];
    }
}


// sidecar/example.js

exports.hello = async function (event) {
    return `Hello World`
}

After deploying this Lambda function, you'll then be able to call it from your Laravel application and see the output on the screen.

lambda-hello-world.png

What's happening here 👆 is pretty amazing. Your Laravel application is calling this NodeJS function which is then being executed on AWS Lambda, and the response is sent back to your Laravel application and displayed in your browser 🤯

Creating Lambda functions with Sidecar is pretty simple and super powerful. So, let's dive into this tutorial and show you how to set up a Lambda function, configure it, execute it, and do a bunch of other cool things!

Let's get started 👏

💾 Installation

Installing Sidecar is very simple. Inside of an existing or new Laravel app, install the sidecar package with the following composer command:

composer require hammerstone/sidecar

After that's completed, you'll want to go into that directory and run the following artisan command:

php artisan sidecar:install

That's pretty much it! Installation is effortless, and same goes for the configuration steps 🙌 Let's do that next.

⚙️ Configuration

Sidecar has built-in configuration steps to help you configure AWS with your application. To get started, run the following command:

php artisan sidecar:configure

You will be presented with a few prompts for adding your AWS key, secret, and region. These prompts will also setup an IAM user and a bucket with the correct permissions to execute your AWS lambda functions 🕺

sidecar-config.png

Sidecar will also add a few environment variables to your application. You may also choose to manually add these environment variables to your .env.

Below are the .env variables that Sidecar will need.

SIDECAR_ACCESS_KEY_ID=XXXXXXXXXXXXXX
SIDECAR_SECRET_ACCESS_KEY=abcdefghijklmnopqrstuvwxyz
SIDECAR_REGION=us-east-1
SIDECAR_ARTIFACT_BUCKET_NAME=sidecar-us-east-1-##########
SIDECAR_EXECUTION_ROLE=arn:aws:iam::############:role/sidecar-execution-role

Now that we have Sidecar all setup, let's have some fun running Lambda functions 🎉

🛠 Create a NodeJS Lambda function

There are three simple steps to follow to create a simple Lambda function.

  1. Create our New Function Class
  2. Create our Function Entry Point
  3. Add our Function to the Config

1. Create our New Function Class

For this example, we are going to create a simple Node JS script, so let's create a new class located at App\Sidecar\NodeJSFunction.php with the following contents:

<?php

namespace App\Sidecar;

use Hammerstone\Sidecar\LambdaFunction;
use Hammerstone\Sidecar\Package;
use Hammerstone\Sidecar\Runtime;

class NodeJSFunction extends LambdaFunction
{

    public function handler()
    {
        return 'sidecar/index@hello';
    }

    public function package()
    {
        return [
            'sidecar/index.js'
        ];
    }
}

In this file, we need to define two methods, the handler() and the package(). This class defines our Lambda function and our entry point.

2. Create our Function Entry Point

Next, we need to create a file located at sidecar/index.js, the entry point for our Lambda function. This file contains a simple Node script that will print out a simple message. Here are the contents of the index.js file:

exports.hello = async function (event) {
    return `Hey Ma 👋, This code is being run from a Lambda function!`
}

3. Add our Function to the Config

Now that we have our function class and our entry point file, we need to add our function to the config/sidecar.php configuration file. Inside of the 'functions' => [] array we will add our Lambda class, like so:

'functions' => [
    \App\Sidecar\NodeJSFunction::class,
],

Awesome! We just created our first Lambda Node function with Sidecar 🕺 Now, we need to deploy it.

🚀 Deploy our Lambda Function

We can quickly deploy our new Lambda function with the following command:

php artisan sidecar:deploy --activate

If everything gets deployed successfully, we'll see an output that looks like the following:

nodefunction.png

You'll also be able to visit your Lambda Dashboard and see your Lambda Serverless function in the list.

lambda-dashboard.png

Next, we may want to test the output by running our Lambda function directly inside our Laravel application; let's dive into that next 👇

💻 Execute our Lambda Function

We can execute our Lambda function with the following command:

\App\Sidecar\NodeJSFunction::execute()->body();

It might be best to view this output from a route. Open up your routes/web.php and replace the homepage route with the following:

Route::get('/', function () {
    return \App\Sidecar\NodeJSFunction::execute()->body();
});

If you open up your browser, you'll see your NodeJS Lambda function execute and display the contents on the screen.

lambda-output.png

Excellent! We are now executing a NodeJS lambda function from our Laravel application and displaying the output inside a route. Next, what if we wanted to pass data from our Laravel application to our Lambda function. We'll cover that next.

🧙‍♂️ Pass Data to our Function

Let's modify our sidecar/index.js to have the following contents:

exports.hello = async function (event) {
    return `Hey ${event.name} 👋, This code is being run from a Lambda function!`
}

Then, let's deploy our updated Lambda with the following command:

php artisan sidecar:deploy --activate

Now, we can pass data to our function by updating our routes/web.php file to look like this:

Route::get('/', function () {
    return \App\Sidecar\NodeJSFunction::execute([
        'name' => 'Johnny'
    ])->body();
});

If we visit our home route inside of a browser, we'll now see the updated output:

lambda-output-2.png

Instead of "Hey Ma", we now see the message "Hey Johnny", which is the name that we passed to our Lambda function. How cool is that!

Specifying Different Runtimes

Using Sidecar and Lambda, we specify what kind of code we want to run. Say, for instance, that we want to execute some code in Python, we could easily create a new class PythonFunction inside of our App\Sidecar directory with the following contents:

<?php

namespace App\Sidecar;

use Hammerstone\Sidecar\LambdaFunction;
use Hammerstone\Sidecar\Package;
use Hammerstone\Sidecar\Runtime;

class PythonFunction extends LambdaFunction
{

    public function handler()
    {
        return 'sidecar/index@handler';
    }

    public function runtime()
    {
        return Runtime::PYTHON_39;
    }

    public function package()
    {
        return [
            'sidecar/index.py'
        ];
    }
}

You may have noticed we have a new method in this class called runtime(), you can find the Sidecar Supported Runtimes here. Keep in mind that you can create any runtime that you want; these are just runtimes supported out of the box.

Next, we'll create our Python script at sidecar/index.py with the following contents:

import os

def handler(event, context):
    return "Heyo, This code is being executed from my Python Lambda function!"

We are using index.py, but you can choose any filename you would like; make sure to call it accordingly in your Lambda Class.

Then, we can add this to our config/sidecar.php:

'functions' => [
    \App\Sidecar\NodeJSFunction::class,
    \App\Sidecar\PythonFunction::class,
],

Finally, we re-deploy our Lambda functions:

php artisan sidecar:deploy --activate

If we change our home route inside our routes/web.php to the following:

Route::get('/', function () {
    return \App\Sidecar\PythonFunction::execute()->body();
});

And we visit our home route in a browser; we'll see the following output:

lambda-output-3.png

You can also check out your Lambda dashboard, and you should see that we now have two functions in the list, one for our Node function and the other for our Python function 🙌

lambda-dashboard

Superb! We can pretty much run any programming language from our Laravel application and isolate it inside of a Lambda function 🤯

💡 Learning More

You can learn more about using Sidecar by visiting the official documentation at https://hammerstone.dev/sidecar/docs/main. Additionally, you will probably be interested in viewing Aaron Francis' Laracon talk where he shows you in a video most of the stuff that we covered above.

Be sure to keep an eye out for future posts on Sidecar as I learn more about all the cool things that Sidecar can do 🤙