Edit on GitHub
Report issue
Page history

Run Laravel on Google App Engine standard environment

Author(s): @bshaffer ,   Published: 2019-01-31

Brent Shaffer | Developer Programs Engineer | Google

Contributed by Google employees.

Laravel is an open source web framework for PHP developers that encourages the use of the model-view-controller (MVC) pattern.

You can check out PHP on Google Cloud to get an overview of PHP and learn ways to run PHP apps on Google Cloud.


  1. Create a project in the Cloud Console.
  2. Enable billing for your project.
  3. Install and initialize the Cloud SDK.

All code for this tutorial is available in the PHP samples repository.


Follow the official documentation for installing Laravel from laravel.com.


  1. Create a new Laravel project using the laravel installer.

    laravel new blog
  2. Go to the blog directory

    cd blog
  3. Run the app with the following command:

    php artisan serve
  4. Visit http://localhost:8000 to see the Laravel Welcome page.


  1. Create an app.yaml file with the following contents:

    runtime: php72
      ## Put production environment variables here.
      APP_STORAGE: /tmp
      SESSION_DRIVER: cookie
  2. Replace YOUR_APP_KEY in app.yaml with an application key you generate with the following command:

    php artisan key:generate --show

    If you're on Linux or macOS, the following command will automatically update your app.yaml:

    sed -i '' "s#YOUR_APP_KEY#$(php artisan key:generate --show --no-ansi)#" app.yaml
  3. Modify bootstrap/app.php by adding the following block of code before the return statement. This will allow you to set the storage path to /tmp for caching in production.

    # [START] Add the following block to `bootstrap/app.php`
    | Set Storage Path
    | This script allows you to override the default storage location used by
    | the  application.  You may set the APP_STORAGE environment variable
    | in your .env file,  if not set the default location will be used
    $app->useStoragePath(env('APP_STORAGE', base_path() . '/storage'));
    # [END]

    If you've added the code correctly, your file will look like this.

  4. Finally, remove the beyondcode/laravel-dump-server composer dependency. This is a fix for an error which happens as a result of Laravel's caching in bootstrap/cache/services.php.

    composer remove --dev beyondcode/laravel-dump-server

    If you're using Laravel 6, remove facade/ignition instead:

    composer remove --dev facade/ignition
  5. Run the following command to deploy your app:

    gcloud app deploy
  6. Visit http://YOUR_PROJECT_ID.appspot.com to see the Laravel welcome page. Replace YOUR_PROJECT_ID with the ID of your Google Cloud project.

    Laravel welcome page

Set up Database Sessions

Note: This section only works with Laravel 5.4.16. To use earlier versions of Laravel, you need to manually add the DB_SOCKET value to config/database.php (see #4178)

  1. Follow the instructions to set up a Google Cloud SQL Second Generation instance for MySQL. Keep track of your instance name and password, as they will be used below.

  2. Follow the instructions to install the Cloud SQL proxy client on your local machine. The Cloud SQL proxy is used to connect to your Cloud SQL instance when running locally.

    • Enable the Cloud SQL Admin API in order to use the Cloud SQL Proxy Client.

    • Use the Google Cloud SDK from the command line to run the following command. Copy the connectionName value for the next step. Replace YOUR_INSTANCE_NAME with the name of your instance:

      gcloud sql instances describe YOUR_INSTANCE_NAME | grep connectionName
    • Start the Cloud SQL proxy and replace YOUR_CONNECTION_NAME with the connection name you retrieved in the previous step.

      ./cloud_sql_proxy -instances=YOUR_CONNECTION_NAME=tcp:3306
    • Use gcloud to create a database for the application.

      gcloud sql databases create laravel --instance=YOUR_INSTANCE_NAME
  3. Run the database migrations for Laravel. This can be done locally by setting your parameters in .env or by passing them in as environment variables. Be sure to replace YOUR_DB_PASSWORD below with the root password you configured:

    # create a migration for the session table
    php artisan session:table
    php artisan migrate --force
  4. Modify your app.yaml file with the following contents:

    runtime: php72
      ## Put production environment variables here.
      APP_STORAGE: /tmp
      CACHE_DRIVER: database
      SESSION_DRIVER: database
      ## Set these environment variables according to your CloudSQL configuration.
      ## for MYSQL, use DB_SOCKET:
      ## for PostgreSQL, use DB_HOST:
      # DB_HOST: "/cloudsql/YOUR_CONNECTION_NAME"
  5. Replace YOUR_DB_DATABASE, YOUR_DB_USERNAME, YOUR_DB_PASSWORD, and YOUR_CONNECTION_NAME with the values you created for your Cloud SQL instance above.

Set up Stackdriver Logging and Error Reporting

Before we begin, install both of the Google Cloud client libraries for Stackdriver Logging and Error Reporting:

composer require google/cloud-logging google/cloud-error-reporting

Stackdriver Logging

You can write logs to Stackdriver Logging from PHP applications by using the Stackdriver Logging library for PHP directly.

  1. First, create a custom logger in app/Logging/CreateStackdriverLogger.php:

    namespace App\Logging;
    use Google\Cloud\Logging\LoggingClient;
    use Monolog\Handler\PsrHandler;
    use Monolog\Logger;
    class CreateStackdriverLogger
         * Create a custom Monolog instance.
         * @param  array  $config
         * @return \Monolog\Logger
        public function __invoke(array $config)
            $logName = isset($config['logName']) ? $config['logName'] : 'app';
            $psrLogger = LoggingClient::psrBatchLogger($logName);
            $handler = new PsrHandler($psrLogger);
            $logger = new Logger($logName, [$handler]);
            return $logger;
  2. Next, you'll need to add our new custom logger to the channels array in config/logging.php:

    'channels' => [
        // Add the following lines to integrate with Stackdriver:
        'stackdriver' => [
            'driver' => 'custom',
            'via' => App\Logging\CreateStackdriverLogger::class,
            'level' => 'debug',

    If you've added the code correctly, your file will look like this.

  3. Modify your app.yaml file to set the LOG_CHANNEL environment variable to the value stackdriver:

    runtime: php72
      LOG_CHANNEL: stackdriver
      # The rest of your environment variables remain unchanged below
      # ...
  4. Now you can log to Stackdriver Logging anywhere in your application!

    Log::info("Hello Stackdriver! This will show up as log level INFO!");

    For example, add the following route to routes/web.php and browse to /log/some-message-here to see a log entry in Logging:

    Route::get('/log/{message}', function ($message) {
        Log::info("Hello my log, message: $message");
        return view('welcome');

    These entries appear in the log of the request they occurred under, as well as in the individual log specified by their log name (app, in this case).

    Note: The first time you deploy, you may get the log message This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application.. If you see this, ignore it and make a second request. On your next request, your logged message should appear in the logs as expected.

Stackdriver Error Reporting

You can send error reports to Stackdriver Error Reporting from PHP applications by using the Stackdriver Error Reporting library for PHP.

  1. Add the following use statement at the beginning of the file app/Exceptions/Handler.php:

    use Google\Cloud\ErrorReporting\Bootstrap;
  2. Edit the report function in the same file app/Exceptions/Handler.php as follows:

    public function report(Exception $exception)
        if (isset($_SERVER['GAE_SERVICE'])) {
        } else {
  3. Now any PHP Exception will be logged to Stackdriver Error Reporting!

    throw new \Exception('PHEW! We will see this in Stackdriver Error Reporting!');

    For example, add the following route to routes/web.php and browse to /exception/my-test-exception to see an exception appear in Error Handling:

    Route::get('/exception/{message}', function ($message) {
        throw new Exception("Intentional exception, message: $message");

Submit a tutorial

Share step-by-step guides

Submit a tutorial

Request a tutorial

Ask for community help

Submit a request

View tutorials

Search Google Cloud tutorials

View tutorials

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies. Java is a registered trademark of Oracle and/or its affiliates.