Linux

How to Install Laravel on Ubuntu 20.04

How to Install Laravel on Ubuntu 20.04

All you need to know to deploy the Laravel web apps on an Ubuntu 20.04 LTS machine

Laravel is a very popular open-source PHP framework with expressive and elegant syntax that is used to design modern and beautiful web applications. Laravel aims to eliminate the pain of web development and make it a fun and creative experience, turning web developers into web artists.

In this guide, you will learn how to install Laravel with the LAMP stack on the Ubuntu 20.04 server to run & run your web apps.

Precondition

To follow this guide, you need an Ubuntu 20.04 LTS server and login as a sudo user. Before we begin, update and upgrade the Ubuntu 20.04 package by running:

sudo apt update && sudo apt upgrade

Install LAMP Stack

LAMP is an acronym for the Linux operating system, Apache web server, MySQL database and PHP programming language. We already use Ubuntu 20.04 which marks Linux in the LAMP stack. So we will install the remaining three packages to complete the LAMP stack for our Laravel application.

There is no meta package available to install the LAMP stack in the Ubuntu 20.04 repository. But we can use the neat little feature of the apt package manager called task. The assignment is symbolized using the task name provided with a cadet (^) added to it.

sudo apt install lamp-server^

This command will look for package list files for all “Task:” fields and install all packages with “server-lights” in their assignment fields. So the LAMP stack consists of Apache, MySQL and PHP packages with all the dependencies installed on your Ubuntu server.

Configure the Firewall

After you install the LAMP stack, you also need to configure the uncomplicated firewall (UFW) and change the rules so that you can access the Apache server from the internet.

UFW provides a simple application profile that can be used to change rules and divert traffic on network ports. Run the following command to list all applications that access network ports:

sudo ufw app list

You will see an output like this:

Available applications:
 Apache
 Apache Full
 Apache Secure
 OpenSSH

The network ports opened by this profile on your Ubuntu 20.04 server are listed below:

  • Apache: This profile only opens port 80 (allows HTTP traffic)
  • Apache Complete: This profile opens 80 & 443 ports (allows HTTP & HTTPS traffic)
  • Apache Secure: This profile only opens on port 443 (allows HTTPS traffic)
  • OpenSSH: This profile opens port 22 which enables the SSH protocol

You need to enable the “Apache Full” profile which will allow traffic to the Apache web server from the internet. In addition, you also need to enable the ‘OpenSSH’ profile which allows traffic on port 22 (SSH) on your Ubuntu 20.04 server. If you enable UFW without allowing the ‘OpenSSH’ profile you will not be able to connect to your server using SSH.

To change UFW rules and allow traffic on ports 80 and 22, run:

sudo ufw allow 'Apache Full'
sudo ufw allow 'OpenSSH'

Then activate the UFW firewall using the following command:

sudo ufw enable

You might get a prompt that says “command could interfere with an existing ssh connection. Continue with the operation (y | n)?” Press Y to continue because we have added rules to allow SSH on UFW.

Now you can access Apache’s default web page using your Ubuntu server’s IP address from the internet. To do this, open your browser and type the IP address of your Ubuntu 20.04 server in the URL bar and press enter.

http://Your_ubuntu_server_ip

1

This page confirms that the Apache web server is running correctly and UFW rules are set correctly.

Setting up a MySQL Database for Laravel

Laravel 7 makes interacting with databases very simple in various supported databases such as MySQL version 5.6+, PostgreSQL 9.4+, SQLite 3.8.8+ and SQL Server 2017+. We already have the latest MySQL package installed with lamp-sever tasks ^. So in this section, we will configure the MySQL server and then look at how to set up new MySQL users and databases for the Laravel apps.

Configure MySQL

The MySQL database is equipped with a pre-installed security script that can be used to remove some insecure default settings. It is recommended that you run this script before you use your Laravel apps.

sudo mysql_secure_installation

The above command will run a security script that will ask you a series of questions to configure the MySQL server.

First, you will be asked if you want to set the VALIDATE PASSWORD plugin. This plugin checks your password and ranks it as safe or unsafe based on the password validation policy level that you will choose immediately. So press Y if you want to activate this plugin.

Output:

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: Y

Then set the password validation policy level by entering 0, 1 or 2 depending on how strong you want to create a password for your database.

Output:

There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2

Next, you will be asked to enter a new password for the MySQL root user. Enter the appropriate password for your MySQL root. The VALIDATE PASSWORD plugin will give you an estimate of the strength of your password according to your password validation level. Press Y to continue with the password you provided.

Output:

Please set the password for root here.

New password:

Re-enter new password:

Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y

Press Y for other confirmation, they will delete some anonymous users and test the database, disable remote root login and reload the new settings for the MySQL server. Once complete, test your database by running:

sudo mysql

The above command will open the MySQL console, connecting to the MySQL database as the root user. You will see an output like this:

Output:

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.20-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

You might notice that you don’t need to enter the password that you have set for the MySQL root user. That’s because the default authentication method for MySQL administrative root users is caching_sha2_authentication instead of the mysql_native_password method which uses a password to login.

So by default, you can only log in as a MySQL root user with an active sudo user who acts as additional security for the MySQL server. But the PHP MySQL library does not support the caching_sha2_authentication method. Therefore we need to use the mysql_native_password method when we create a new user for Laravel because it uses a password to connect & interact with the database.

Create New MySQL Users & Database

It is always a good practice to create a new user and database specifically for your application instead of using the MySQL root user and testing the database. So we will set up a new MySQL user called laravel_user and a database called laravel. If you have followed the tutorial to this point, you must open the MySQL console. To create a user named laravel_user, run the following query in the MySQL console:

Note: Replace the test passed in the MySQL request below with a strong password.

CREATE USER 'laravel_user'@'%' IDENTIFIED WITH mysql_native_password BY 'testpass';

Next, create a database called laravel for our Laravel application by running this query:

CREATE DATABASE laravel;

Only MySQL root users have permission to the newly created database laravel. Give all permissions via the laravel database to laravel_user by running:

GRANT ALL ON laravel.* TO 'laravel_user'@'%';

So, we now have a new MySQL user and database, exit the MySQL console by running:

EXIT;

Test your new MySQL user by logging into the MySQL console with it, to do so run this command in the terminal:

mysql -u laravel_user -p

Pay attention to the -p flag in the command, it will ask you for the password you used when creating laravel_user (testpass in query). After you enter the MySQL console as laravel_user, confirm that the user has access to the laravel database by running:

SHOW DATABASES;
Output:

+--------------------+
| Database           |
+--------------------+
| laravel            |
| information_schema |
+--------------------+
2 rows in set (0.01 sec)

The above output confirms that the laravel_user MySQL user has permission to the laravel database. Exit the MySQL console using EXIT; request that we continue to make the DemoApp Laravel application.

Install Laravel

The Laravel framework uses Composer to download and manage its dependencies. So, we need to install Composer on our Ubuntu 20.04 machine before we can create the Laravel application.

Install Composer

Composer is a dependency management tool for PHP, which makes installing and updating PHP frameworks and libraries easier. We will see how to quickly install Composer in this tutorial so that we can use it to download and manage the Laravel framework.

You need to install a number of additional packages that are needed by Composer to function like php-cli to run PHP scripts on the terminal and unzip to help Composer extract packages. Install both by running:

sudo apt install php-cli unzip

Then to install Composer globally, download the Composer installation script with curl and install using the following command:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Finally, verify that the composer is installed correctly by running:

composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.10.8 2020-06-24 21:23:30

Usage:
  command [options] [arguments]

This output confirms that Composer works well on your Ubuntu 20.04 server, you can start using it to install and manage PHP frameworks and libraries.

Create the Laravel Apps

We have quite a lot needed to create a Laravel application on our Ubuntu 20.04 server except for a few PHP extensions. Install this missing extension using the following command:

sudo apt install php-mbstring php-xml php-bcmath php-zip php-json

Now, we can install Laravel and create a new Laravel application with the help of Composer. First, make sure you are in your user’s home directory:

cd ~

Then create a new Laravel project using the composer project create command:

composer create-project --prefer-dist laravel/laravel LaravelApp

The above command will create a new project called LaravelApp and will also install and configure the Laravel Framework for you. You will see an output similar to this:

Output:

Creating a "laravel/laravel" project at "./LaravelApp"
Installing laravel/laravel (v7.12.0)
Installing laravel/laravel (v7.12.0): Downloading (100%)
Created project in /home/ath/LaravelApp
@php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 97 installs, 0 updates, 0 removals
Installing voku/portable-ascii (1.5.2): Downloading (100%)
Installing symfony/polyfill-ctype (v1.17.1): Downloading (100%)
Installing phpoption/phpoption (1.7.4): Downloading (100%)
Installing vlucas/phpdotenv (v4.1.7): Downloading (100%)
Installing symfony/css-selector (v5.1.2): Downloading (100%)

When the installation is complete, open the application’s root directory and then run the Laravel command to verify that all components are installed correctly:

cd LaravelApp/
php artisan
Output:
Laravel Framework 7.18.0

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
....

This output confirms that the installation was successful and all files are in place and the Laravel command line tool is functioning properly. However, we still need to configure the application to manage the database and several other settings.

Configure the Laravel Apps

The Laravel configuration file is located in a directory called config in the application’s root directory. Additionally, when we installed Laravel through Composer, it created an environment file called “.env” in the application’s root directory. The environment file includes environment specific configuration and takes precedence over the settings in the usual configuration file located in the config directory.

Note: The environment configuration file contains sensitive information about your server such as database password, Laravel application key etc. Therefore the file cannot be shared publicly.

We will now edit the .env file to change the configuration and add database credentials to it. Open the file using nano editor by running:

nano .env

There are many configuration variables in this .env file. We don’t need to change each of them, because Composer has configured most settings automatically. So, here is a list of some of the main configuration variables that you should know about:

  • APP_NAME: The application name is used for notifications and messages, so we will set it to ‘LaravelApp’.
  • APP_ENV: This variable is used to indicate the current application environment. Can be set to the local environment, development, testing or production. We will set it to the development environment for now.
  • APP_KEY: Unique application key used to make salt and hashes for web applications. This is automatically generated when you install Laravel via Composer, so there is no need to change this.
  • APP_DEBUG: Can be set to true or false, depending on whether you want to display errors on the client side. Set to false when you move to the production environment.
  • APP_URL: Base URL or IP for the application, change it to your domain name if you have it for your Laravel application or leave it untouched for now.
  • DB_DATABASE: The name of the database that you want to use with the Laravel application. We will use the MySQL “Laravel” database that we created when configuring MySQL.
  • DB_USERNAME: Username to connect to the database. We will use the MySQL user ‘laravel_user’ that we created.
  • DB_PASSWORD: Password to connect to the database.
APP_NAME=LaravelApp APP_ENV=development APP_KEY=base64:Application_unique_key APP_DEBUG=true APP_URL=http://domain_or_IP LOG_CHANNEL=stack DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=laravel_user DB_PASSWORD=testpass

Make changes to the .env file accordingly and when you have finished editing, save and exit the file using CTRL + X then press Y and press enter to confirm. Now, all that’s left is to configure the Apache server and create a virtual host for our Laravel application.

Setting up Apache Web Server

We have installed Laravel in the user’s home directory’s local folder. Although this works well for local development, it is recommended to have a web application directory located at / var / www. The reason we didn’t install Laravel directly in / var / www is because it’s owned by root and Composer shouldn’t be used with sudo.

So use the mv command to move the Laravel application folder and its contents to / var / www:

sudo mv ~/Laravel/ /var/www

The LaravelApp directory is owned by the user, so you can still edit and make changes to the file without using the sudo command. But the Apache web server needs access to the cache and application storage directory because Laravel stores the application that generates files in it. Change the owner of this folder to the www-data user using the chown command:

sudo chown -R www-data.www-data /var/www/LaravelApp/storage
sudo chown -R www-data.www-data /var/www/LaravelApp/bootstrap/cache

After changing the owner of this directory, enable Apache mod_rewrite as requested by Laravel to transform the URL correctly as interpreted by its routing function via the .htaccess file.

sudo a2enmod rewrite

Next, we need to set up a virtual host for the Laravel application. The virtual host configuration is located at / etc / apache2 / sites-available. We will edit the default virtual host file to use the Laravel application. Open the default virtual host configuration file using Nano Editor:

sudo nano /etc/apache2/sites-available/000-default.conf

Change the document root from / var / www / html to / var / www / LaravelApp / public and add the following snippet below the Boot Document line:

<Directory /var/www/LaravelApp>

AllowOverride All
</Directory>
Your 000-default.conf should look like this now with a few comments.
<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/LaravelApp/public
        <Directory /var/www/LaravelApp>
		AllowOverride All
	</Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Restart the Apache web server by running the following command:

sudo systemctl restart apache2

Now go to your browser and type the IP address of your Ubuntu 20.04 server. You will see the Laravel start page instead of the default Apache welcome page.

2

Assuming you have followed this guide so far, you must have a Laravel application that works with a MySQL database called laravel for that. From this point on, you can start developing your own Laravel application. To learn more about the Laravel framework and its use visit the Laravel document page.

Related posts

How to Install OpenCV on Ubuntu 20.04

Linux

How to use GNU Debugger on Linux

Linux

How To Install NTP (Chrony) On CentOS 8 / CentOS 7 & RHEL 8 / RHEL 7

Linux

How to Install Gitea on CentOS 8

Linux

How to Customize the Linux Terminal on a Chromebook

Linux

How to compile the ONLYOFFICE Document Server from source code on Ubuntu

Linux

How to Play PS2 Games on Ubuntu Using PCSX2

Linux

How to Install Sensu Monitoring on Ubuntu 20.04

Linux

How To Remove Snap From Ubuntu

Linux