Skip to content

Beginner’s Guide to Deploying PHP Laravel on the Google Cloud Platform

Reading Time: 6 minutes

Laravel is one of the leading frameworks used by the PHP Community. On the other hand, Google offers an excellent more cost-effective Cloud Platform on its own. But make to run your existing Laravel application may be a nightmare if you don’t follow these steps. I have tried a lot and finally found the solution, even you can run your latest Laravel version also.

Google Cloud Platform

Google Cloud Platform, offered by Google, is a suite of distributed computing administrations that keeps running on a similar foundation that Google utilizes inside for its end-client products, for example, Google Search and YouTube.Alongside a lot of the board instruments, it gives a progression of secluded cloud administrations including figuring, information stockpiling, information examination, and machine learning. Enlistment requires a Mastercard or financial balance subtleties.

Google Cloud Platform is a suite of open distributed computing administrations offered by Google. The stage incorporates a scope of facilitated administrations for figure, stockpiling, and application improvement that keep running on Google equipment. Google Cloud Platform administrations can be gotten to by programming designers, cloud directors, and other venture IT experts over the general population web or through a devoted system association.

Google keeps on including more elevated amount administrations, for example, those identified with enormous information and machine learning, to its cloud stage. Google’s enormous information administrations incorporate those for information preparation and investigation, for example, Google BigQuery for SQL-like questions made against multi-terabyte informational collections.

Also, Google Cloud Dataflow is information preparing administration planned for examination; remove, change and burden (ETL); and continuous computational tasks. The stage likewise incorporates Google Cloud Dataproc, which offers Apache Spark and Hadoop administrations for enormous information preparation.

See also  Excellent Chess Board Design using PHP with Chess Pieces 2024

For man-made consciousness (AI), Google offers its Cloud Machine Learning Engine, an oversaw administration that empowers clients to manufacture and prepare machine learning models. Different APIs are likewise accessible for the interpretation and examination of discourse, content, pictures, and recordings.

Google additionally gives administrations to IoT, for example, Google Cloud IoT Core, which is a progression of overseen administrations that empowers clients to devour and oversee information from IoT gadgets.

The Google Cloud Platform suite of administrations is continually developing, and Google occasionally presents, changes, or suspends administrations depending on client requests or aggressive weights. Google’s primary rivals in the general society distributed computing market incorporate Amazon Web Services (AWS) and Microsoft Azure.

Google offers preparing projects and affirmations identified with Google Cloud Platform, including programs for cloud framework, information and machine learning, application improvement, and G suite organization, just as an early-on program for its cloud stage. There are three Google Cloud accreditations an IT expert can acquire: a Certified Professional Cloud Architect, a Certified Professional Data Engineer, and a Certified Professional G Suite Administrator.

Laravel

Laravel is a free, open-source[3] PHP web system, made by Taylor Otwell and expected the improvement of web applications following the model–view–controller (MVC) compositional example and dependent on Symfony. A portion of the highlights of Laravel is a particular bundling framework with a committed reliance chief, diverse courses for getting to social databases, utilities that guide in application sending and upkeep, and its introduction toward syntactic sugar. The source code of Laravel is facilitated on GitHub and authorized under the terms of the MIT License.

Notwithstanding Laravel’s implicit and discretionary bundles, Laravel likewise offers a paid arrangement of extra highlights packaged into a bundle named Laravel Spark. The bundle was created by Taylor Otwell and gives extra devices to online SaaS organizations to incorporate with administrations like Stripe, Producing solicitations, Bootstrap 4.0, and group validation. As of June 2018, the bundle variant is 6.0.

See also  3D Mobile Game Development 🏈 - 8 Kickstart Skills To Start

Preparations

To access Google Cloud you should enable its billing with your valid credit card. Currently, its coming with $300 free for 300 days :). Hope it’s ok for testing purposes. A little bit of Unix Commands knowledge is preferable, but not a must.

Few more steps

1. Create a New Project in the Google Cloud Platform.

Google-Cloud-Platform

2. Create an App Engine Instance

Google-Cloud-Shell

3. Create Mysql Instance

Google-Cloud-Mysql-Instance

Upload your files

There are 2 options to upload your files.

a. You can create a Bucket and upload your files

b. You can upload files directly to app engine storage. (we preferred this for easy access!)

First, upload all of your files, I prefer to use Github or similar Git Repos.

then clone it directly to Google App Engine from the Google Shell.

git clone https://github.com/karthik/laravel.git

What is App.yaml

Google-cloud-App-Engine

App.yaml is the configuration file that is used for App Engine Setting.

Google-Cloud-App-Engine-Storage

Launch Code Editor from Google Shell to access all the files and create an App.yaml on your project folder with the following lines.

runtime: php
env: flex

runtime_config:
  document_root: public

# Ensure we skip ".env", which is only for local development
skip_files:
  - .env

env_variables:
  # Put production environment variables here.
  APP_LOG: errorlog
  APP_DEBUG: true
  APP_KEY: [your-application-key]
  STORAGE_DIR: /storage
  CACHE_DRIVER: database
  SESSION_DRIVER: database

Connect with Mysql Database

As you know we already created a mysql instance. In this step, we just implement the credentials of our MySQL database instance into the Laravel app.  All we can do with the App.yaml

  ## Set these environment variables according to your CloudSQL configuration.
  DB_HOST: localhost
  DB_PORT: 3306
  DB_DATABASE: database
  DB_USERNAME: root
  DB_PASSWORD: 123456
  DB_SOCKET: "/cloudsql/cloud-project:us-central1:mysql-laravel"
  
beta_settings:
    # for Cloud SQL, set this value to the Cloud SQL connection name,
    # e.g. "project:region:cloudsql-instance"
    cloud_sql_instances: "cloud-project:us-central1:mysql-laravel"

Activate API

This one is a very important step and essential to run our application with MySQL instance.

See also  Good Coding Standards of PHP

Google-Cloud-Mysql-Api

Settings for Laravel 5.0

All the above settings to make Laravel’s recent versions work as a charm. But for Laravel 5.0,  We need some more tweaks to run.

1. Add the PHP Version to your Composer.json

"require": {
		"php": "5.6.*",
		"laravel/framework": "5.0.*"
	},

2. Add Line in Config/Database.php

'unix_socket' => env('DB_SOCKET', ''),

3. Replace the MysqlConnector file with the following (it will located on the Vendor directory)

<?php namespace Illuminate\Database\Connectors;

class MySqlConnector extends Connector implements ConnectorInterface {

  /**
	 * Establish a database connection.
	 *
	 * @param  array  $options
	 * @return PDO
	 */
	public function connect(array $config)
	{
		$dsn = $this->getDsn($config);

		// We need to grab the PDO options that should be used while making the brand
		// new connection instance. The PDO options control various aspects of the
		// connection's behavior, and some might be specified by the developers.
		$options = $this->getOptions($config);

		$connection = $this->createConnection($dsn, $config, $options);

		// We need to explicitly exec the 'use' mysql command in case the 
		// unix_socket option is used in the dsn.
		if (isset($config['unix_socket']))
		{
			$connection->exec("use {$config['database']};");
		}

		$collation = $config['collation'];

		$charset = $config['charset'];

		// Next we will set the "names" and "collation" on the clients connections so
		// a correct character set will be used by this client. The collation also
		// is set on the server but needs to be set here on this client objects.
		$names = "set names '$charset' collate '$collation'";

		$connection->prepare($names)->execute();

		return $connection;
	}

	/**
	 * Create a DSN string from a configuration.
	 *
	 * @param  array   $config
	 * @return string
	 */
	protected function getDsn(array $config)
	{
		extract($config);

		// Sometimes the developer may specify the specific UNIX socket that should be used
		if (isset($config['unix_socket']))
		{
			$dsn = "unix_socket={$config['unix_socket']}";
		}
		else
		{
			// But more often a single hostname is supplied with an optionnal port number.
			// Warning : when 'localhost' is used, the mysql driver will use the default 
			//			unix socket value, use '127.0.0.1' instead.
			// Note :	according to the PHP documentation the unix_socket option and the 
			//			host[port] option should not be used together.
			$dsn = "host={$host}";

			if (isset($config['port']))
			{
				$dsn .= ";port={$port}";
			}
		}

		// Finally, the 'mysql:' prefix as well as the database name are added
		$dsn = "mysql:{$dsn};dbname={$database}";

		return $dsn;
	}

}

Thanks, Gmergoil for this script.

Deploy your application

gcloud app deploy

Great! finally, you get to run your Laravel application on Google Cloud.

Hope you enjoy the article! I would like to receive your suggestions & comments.

Share your thoughts

Leave a Reply