How to Install Laravel on Ubuntu 22.04 [Super Easy Guide]

0
Install Laravel on Ubuntu 22.04
Install Laravel on Ubuntu 22.04

Laravel is a well-known PHP framework that is open source and it provides various sets of tools and resources for developing new and advanced PHP applications. In this tutorial, you will learn how to install laravel on Ubuntu 22.04 easily.

Laravel’s popularity has expanded quickly in recent years, with so many developers selecting it as their ideal framework of preference for a simplified development process, thanks to a rich ecosystem exploiting its built-in capabilities. This tutorial will walk you through installing and configuring the  Laravel application on Ubuntu 22.04 system, using Composer to fetch and manage framework components and Apache, and Nginx to deliver the application.

When you’re done with the tutorial, you’ll have a fully functioning Laravel sample application that pulls data from the MySQL 8 database of your system.

Prerequisites to Install Laravel on Ubuntu 22.04

To successfully install laravel and complete the guide you have to perform the following tasks below on your Ubuntu 22.04

  • First Create a sudo user on your system and enable the ufw
  • Install the LEMP stack on your Ubuntu 22.04 system with MySQL 8
  • Install Composer on Your System
  • Install PHP on your Ubuntu 22.04 system

Step 1: Installing Required PHP modules to Install Laravel on Ubuntu 22.04

So to install Laravel on Ubuntu 22.04 your system you must first need to install several PHP modules that the framework requires. The php-mbstring, php-xml, and php-bcmath PHP modules will be installed using apt in your system. These PHP extensions offer further help with character encoding, XML, and precision mathematics for Laravel.

If you are using apt for the first time in your system for this session, then first you need to use the update command in your terminal to refresh the package management cache:

$ sudo apt update

You can now install the necessary packages with:.

$ sudo apt install php-mbstring php-xml php-bcmath php-curl

Now your system is totally ready to run Laravel’s installation using Composer, but first you’ll need to create a database on your system for the application.

Step 2: Create Database for the Laravel

To explain Laravel’s basic deployment and usage, we’ll build a tour list application that displays a list of locations a user wants to visit and a list of places they’ve actually been to.

This may be maintained in a locations table with a field for locales called names and another for marking it as visited or not visited called seen. We’ll also include an id field to identify an individual for each entry.

Now in your system, you have to connect to the database from the Laravel application, and for that, we’ll establish a special MySQL account with full access to the travellist database.

Now while writing, the native MySQL PHP library mysqlnd does not support caching sha2 authentication, MySQL 8’s default authentication technique.

To connect to the MySQL database using PHP, we’ll need to configure your database user with the MySQL native password authentication technique in your system.

To begin with it, just log in using the below command for the MySQL console as the root database user in your system

$ sudo mysql

Now run the following command in your system from your MySQL console to create a new database:

CREATE DATABASE travellist;

You should now create a new user in the database and provide them complete access to the newly established custom database.
In this example, we’ll create a user named travellist user with the password “password”, which you should replace with a safe password of your choice:

CREATE USER 'travellist_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';

We must now provide this user access to the travellist database:

GRANT ALL ON travellist.* TO 'travellist_user'@'%';

This grants the travellist_user full access to the travellist database while prohibiting this user to create or alter other databases on your server.

Now follow the below code to exit from MySQL shell of your system:

exit

You can now verify that the new user has the necessary rights by login back into the MySQL console with the custom user login credentials:

mysql -u travellist_user -p

Take note of the -p argument in this command, which prompts you for the password you used to create the travellist_user user. Now confirm to the shell that you have permission to the travellist database after logging onto the MySQL console:

SHOW DATABASES;

This will result in the following output:

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

Next, in the travellist database, add a table called locations. Now run the below statement from the MySQL console:

CREATE TABLE travellist.places (
	id INT AUTO_INCREMENT,
	name VARCHAR(255),
	visited BOOLEAN,
	PRIMARY KEY(id)
);

Now you have to Fill in the locations table with several sample data:

INSERT INTO travellist.places (name, visited) 
VALUES ("Tokyo", false),
("Budapest", true),
("Nairobi", false),
("Berlin", true),
("Lisbon", true),
("Denver", false),
("Moscow", false),
("Olso", false),
("Rio", true),
("Cincinnati", false),
("Helsinki", false);

Run the following command to validate that the data was correctly saved to your table:

SELECT * FROM travellist.places;

The output will be looked like this:

+----+-----------+---------+
| id | name      | visited |
+----+-----------+---------+
|  1 | Tokyo     |       0 |
|  2 | Budapest  |       1 |
|  3 | Nairobi   |       0 |
|  4 | Berlin    |       1 |
|  5 | Lisbon    |       1 |
|  6 | Denver    |       0 |
|  7 | Moscow    |       0 |
|  8 | Oslo      |       0 |
|  9 | Rio       |       1 |
| 10 | Cincinnati|       0 |
| 11 | Helsinki  |       0 |
+----+-----------+---------+
11 rows in set (0.00 sec)

You can quit the MySQL console after ensuring that you have entered valid data in your sample table:

exit

You are now ready to build the application and link it with the new database.

Step 3: Creating New Laravel Application

After installing Laravel on Ubuntu 22.04, You will now use the composer and use the create-project command to build a new Laravel application. This Composer tool is commonly used to bootstrap new applications that are built on current frameworks with the present content management systems.

We’ll use travellist in Laravel as an example application throughout this article, but you’re free to use something else. The travellist application will show a list of places retrieved from a local MySQL server, with the goal of demonstrating Laravel’s basic settings and confirming that you can connect to the database.

To begin, navigate to your user’s home directory:

cd ~

Now The below command will generate the new travellist directory with a minimal Laravel application with default settings:

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

You will see something like this:

Creating a "laravel/laravel" project at "./travellist"
Installing laravel/laravel (v9.1.5)
  - Installing laravel/laravel (v9.1.5): Extracting archive
Created project in /home/sammy/travellist
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies
. . .
Package manifest generated successfully.
78 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force
No publishable resources for tag [laravel-assets].
Publishing complete.
> @php artisan key:generate --ansi
Application key set successfully.
. . .

When the installation is complete, navigate to the application’s directory and execute Laravel’s artisan command to ensure that all the components were properly installed:

cd travellist
php artisan

You’ll get something like this:

Laravel Framework 9.8.1

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display help for the given command. When no command is given display help for the list command
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi|--no-ansi  Force (or disable --no-ansi) 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 result indicates that the application files are there and that the Laravel command-line tools are functioning properly. However, we must still setup the program to configure your database and a few additional elements.

Step 4: Configuring Laravel on Ubuntu 22.04

So now the Laravel configuration files are stored in a directory named config, which is situated within the application’s root directory. Moreover, when you will try to install Laravel using Composer, an environment file is created.

This file includes settings particular to the present context in which the program is executing, and it takes precedence over the values set in conventional configuration files in the config directory.

Each installation in a new environment necessitates the creation of a customized environment file to describe things like database connection settings, debug options, application URLs, and other elements that may differ depending on the environment in which the application is operating.

To adjust the configuration parameters for such a current application environment, we’ll now update the .env file.

After that, you have to Open the.env file using your preferred command line editor. We’ll use nano in this case

nano .env

Even though this file contains numerous configuration variables, you do not need to put them all up right now. The following is a summary of the factors that demand quick attention:

  • APP_NAME: It is the application name that is used for notifications and messages.
  • APP_ENV: To check the current application environment.
  • APP_KEY: It is used for generating salts and hashes, also this unique key is automatically created when installing Laravel via Composer, so users don’t need to change it.
  • APP_DEBUG: It is used or not to show debug information on the client side.
  • APP_URL: This is basically the base URL for the application that is used for generating application links.
  • DB_DATABASE: This is to check the database name.
  • DB_USERNAME: This is used to connect the username to the database.
  • DB_PASSWORD: Helps to connect passwords to the database.

These parameters are set by default for a local development platform that employs Homestead, a bundled Vagrant box offered by Laravel. We’ll adjust these numbers to suit our sample application’s existing environment settings.

Now If you’re installing Laravel in a production or testing environment, leave the APP DEBUG option enabled to get critical debug information whenever testing the application in a browser. In this scenario, the APP ENV variable should always be set to production or testing.

When you are installing Laravel in a production system, you should also uncheck the APP DEBUG option since it displays sensitive information about your application to the final user. In this situation, the APP ENV should be updated to production.

The.env file below configures our sample application for development

APP_NAME=TravelList
APP_ENV=development
APP_KEY=APPLICATION_UNIQUE_KEY_DONT_COPY
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=travellist
DB_USERNAME=travellist_user
DB_PASSWORD=password

. . .

Adjust your variables as needed. Once you’ve finished editing, save and shut the file to preserve your changes. If you’re using nano, use CTRL+X, then Y and press Enter to confirm.

Your Laravel application has now become up and running, but we need to set up the web server so that you can access it through a browser. The following step will be to set up Nginx to serve your Laravel application.

Step 5: Setting Up Nginx

We installed Laravel in a local folder of your system’s remote user’s home directory, and while it works great for private development settings, it is not a recommended technique for public-facing web servers.

We’ll relocate the app folder to /var/www, which is the default location for Nginx web applications.

To begin, use the mv command to copy the program folder and all of its contents to /var/www/travellist:

sudo mv ~/travellist /var/www/travellist

We must now provide the web server clients the write access to the data storage and cache directories, which are where Laravel saves application-generated files:

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

Now the application files are in order, but Nginx must still be configured to deliver the content. To do this, we’ll add a new virtual host config file to /etc/nginx/sites-available:

sudo nano /etc/nginx/sites-available/travellist

So the suggested settings for Laravel apps on Nginx are contained in the configuration file below:

Open /etc/nginx/sites-available/travellist then paste the code.

server {
 listen 80;
    server_name server_domain_or_IP;
    root /var/www/travellist/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Copy the contents of this file to your system file /etc/nginx/sites-available/travellist file then, if required, update the highlighted values to match your personal setup. When you’re through editing, save and shut the file.

Now create a symbolic link for travellist in sites-enabled to enable the new virtual host config file:

sudo ln -s /etc/nginx/sites-available/travellist /etc/nginx/sites-enabled/

To ensure that there are no syntax problems in the configuration, use:

sudo nginx -t

You should get something like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Reload Nginx to apply the changes and to do that paste the below code

sudo systemctl reload nginx

Now, open your browser and navigate to the app using the server’s domain or IP, as provided in the configuration file using the server name directive:

http://server_domain_or_IP

This shows a page with the Laravel logo.

That means your Nginx server is set up correctly to serve Laravel. You may now begin constructing your app on top of the skeleton supplied by the default configuration.

The following step will be to adapt the application’s main route to query the database using Laravel’s DB facade.

Conclusion

I hope this tutorial was useful to install Laravel on Ubuntu 22.04. You’ve also installed a new Laravel application on top of a LEMP stack (Linux, Nginx, MySQL, and PHP) on an Ubuntu 22.04 server. You’ve also modified your static routes to query the database and display the outcomes in a custom view.

You may construct new routes and views from here for any more pages your application requires.

More information about routes, views, and database support can be found in the official Laravel documentation. If you’re delivering to production, you should also look at the optimization section for a few different approaches to increase the speed of your application.

LEAVE A REPLY

Please enter your comment!
Please enter your name here