Laravel Installation Guide [Step-By-Step Explained]


Written By - Muhammad Azeem
Advertisement

Introduction to Laravel (Overview)

Laravel is an open-source PHP framework developed by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern. Laravel is one of the most popular PHP frameworks, alongside Symfony and CodeIgniter.

It is based on Symfony and includes a set of tools and libraries. Laravel is a full-stack framework that includes a suite of tools and components for building modern web applications. It is designed to provide an easy-to-use and powerful development environment for rapid application development.

Laravel includes a robust set of features, such as routing, authentication, sessions, and caching, that can be used to quickly and easily build applications. It also provides an intuitive and expressive syntax that makes writing code simpler and more enjoyable.

 

Pre-requisites

Before diving into the installation process for Laravel, it's crucial to ensure your development environment meets the minimum system requirements. Failing to satisfy these prerequisites could lead to installation issues or operational inefficiencies down the line. Here are the fundamental elements your system should have:

 

Installing PHP

Installing PHP is one of the first steps you'll need to take to get Laravel up and running, as it's a PHP framework. Below are instructions for installing PHP and its required extensions.

Laravel requires a specific version of PHP. As of my last update in September 2021, Laravel 8.x requires PHP >= 7.3.

To install PHP on Ubuntu, you can run the following command:

sudo apt update
sudo apt install php

To check if PHP is installed and see its version, run:

Advertisement
php -v

 

Required PHP Extensions

Laravel requires several PHP extensions to function correctly. While installing PHP as described above, you may have already installed these required extensions. If not, here's how you can install the most commonly required PHP extensions for Laravel on Ubuntu:

sudo apt update
sudo apt install php php-cli php-fpm php-json php-common php-mysql php-zip php-gd php-mbstring php-curl php-xml php-pear php-bcmath

Here's a quick rundown of what each extension is generally used for:

  • php-cli: For running PHP from the command line
  • php-fpm: For FastCGI Process Manager
  • php-json: For JSON support
  • php-common: For common utilities
  • php-mysql: For MySQL database support
  • php-zip: For Zip archive support
  • php-gd: For image processing
  • php-mbstring: For multi-byte string support
  • php-curl: For making HTTP requests
  • php-xml: For XML parsing
  • php-pear: For PEAR package repository
  • php-bcmath: For arbitrary-precision mathematics

 

Installing Composer

Composer is a crucial component for Laravel development. It serves as a dependency manager for PHP, allowing you to manage your project's libraries and dependencies, and also facilitates autoloading of your project classes.

It's a good practice to update your package database before installing any new software:

sudo apt update

Before installing Composer, you may need to install some additional packages:

sudo apt install curl php-cli php-mbstring git unzip

To download the Composer installer, run:

curl -sS https://getcomposer.org/installer -o composer-setup.php

After downloading the installer, you can install Composer globally (i.e., make it available system-wide) by using:

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

To make sure Composer was installed successfully, run:

composer --version

 

Laravel Installation Methods

There are primarily two ways to install a new Laravel project: using the Laravel Installer and using Composer's create-project command. Here's how you can go about each:

 

1. Laravel Installer

The Laravel Installer is a convenient way to create new Laravel projects. It provides a faster setup process compared to Composer's create-project command.

Before using the Laravel Installer, you have to install it. You can install it globally on your system so that you can create Laravel projects from anywhere. Run the following command to install:

composer global require laravel/installer

Make sure to place Composer's system-wide vendor bin directory in your $PATH so the laravel executable is found when you run the laravel command in your terminal.

If you'd like to make the change permanent, you'll need to add the export command to a shell startup script like ~/.bashrc, ~/.zshrc, or ~/.profile, depending on which shell you are using.

Open ~/.bashrc in a text editor and add the following line at the end:

export PATH="$PATH:$HOME/.config/composer/vendor/bin"

or, for some systems:

export PATH="$PATH:$HOME/.composer/vendor/bin"

Then, apply the changes:

source ~/.bashrc

After installing the Laravel Installer, you can create a new Laravel project by running:

laravel new project-name

Replace project-name with your desired project name.

 

2. Using Composer for Laravel Installation

If you don't want to install the Laravel Installer, you can create a new Laravel project using Composer's create-project command.

To create a new Laravel project, navigate to the directory where you want the project to be installed and run:

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

Replace project-name with your desired project name.

Note: This method can be slower than using the Laravel Installer because Composer will download all the Laravel dependencies.

Both of these methods will create a new Laravel project, download its dependencies, and set up a basic directory structure for you to start developing your application.

 

Setting Up Web Server

After you've installed PHP and Composer, and created a Laravel project, you'll need to set up a web server to host and run your Laravel application. The two most commonly used web servers for Laravel are Apache and Nginx.

 

Install and Configure Apache

Apache is a popular, open-source web server. You can install it and configure it to serve your Laravel application as follows:

First, update your package list and install Apache:

sudo apt update
sudo apt install apache2

To serve a Laravel application, you'll need to edit the Apache configuration to point it to the public directory of your Laravel application.

Create a new Apache configuration file for your site.

sudo nano /etc/apache2/sites-available/my-laravel-project.conf

Add the following lines, modifying them to match your specific paths and domain.

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /home/deepak/my-laravel-project/public

    <Directory /home/deepak/my-laravel-project/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Enable the new site and disable the default site.

sudo a2ensite my-laravel-project.conf
sudo a2dissite my-laravel-project

Enable Apache’s mod_rewrite module to support the .htaccess file.

sudo a2enmod rewrite

Restart Apache to apply changes.

sudo systemctl restart apache2

For any issues you can check /var/log/apache2/error.log

 

Install and Configure Nginx

Nginx is another popular web server, known for its performance and scalability.

To install Nginx, you can use the following commands:

sudo apt update
sudo apt install nginx

Open a new Nginx configuration file for your site.

sudo nano /etc/nginx/sites-available/my-laravel-project

Add the following configuration, modifying to fit your specific paths and domain.

server {
    listen 80;
    server_name yourdomain.com;
    root /home/deepak/my-laravel-project/public;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }
}

Create a symbolic link to enable the site.

sudo ln -s /etc/nginx/sites-available/my-laravel-project /etc/nginx/sites-enabled

Test the configuration.

sudo nginx -t

Reload Nginx to apply changes.

sudo systemctl reload nginx

 

Database Configuration

After setting up your Laravel project and web server, it's crucial to configure your environment settings properly. Laravel uses the .env file for this purpose, which is located in the root directory of your Laravel project.

The .env file contains key-value pairs that define the settings and credentials your application needs. For example, it includes database connection settings, mail server settings, and many other configurations that your Laravel application will use.

You should never commit your .env file to version control. It often contains sensitive information like API keys and database passwords.

 

Install and Configure MySQL Server

If you haven't installed MySQL yet, you can install it by running:

sudo apt update
sudo apt install mysql-server

After installing MySQL, it's a good idea to run the secure installation script:

sudo mysql_secure_installation

To check if MySQL is running:

systemctl status mysql.service

If it's not running, you can start it with:

sudo systemctl start mysql

Log in to MySQL using the root account:

sudo mysql -u root

Note: If you've set a password for the root user, you'll need to use -p and enter the password when prompted:

MySQL 8 introduced a new default authentication plugin that can cause issues with older clients. You can update the root user to use the mysql_native_password plugin as shown below:

ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'new_password';

Flush privileges to apply changes:

FLUSH PRIVILEGES;

Create a new database that your Laravel application will use:

CREATE DATABASE laravel;

Type exit and hit Enter to exit MySQL:

EXIT

 

Check MySQL User Permissions

Make sure the MySQL user specified in .env has the necessary permissions to access the database.

You can login to the MySQL shell and grant permissions:

mysql -u root -p

Then run:

GRANT ALL ON laravel.* TO 'root'@'localhost';

Replace 'laravel' with your database name and 'root' and 'localhost' with your MySQL username and host respectively.

 

Check Firewall Rules

If your MySQL server is on a remote machine, make sure your firewall is configured to allow traffic on the MySQL port (default is 3306).

 

Environment Configuration

The .env file is also where you'll configure your database connections. By default, Laravel is configured to use MySQL, but you can change this to a database engine of your choice.

Here are the default MySQL settings in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=Passw0rd

Parameters Explained:

  • DB_CONNECTION: The database driver to use (mysql, pgsql, sqlsrv, etc.)
  • DB_HOST: The hostname of your database server
  • DB_PORT: The port number to use when connecting to the database server
  • DB_DATABASE: The name of the database
  • DB_USERNAME: The username for the database connection
  • DB_PASSWORD: The password for the database connection

After editing the .env file, you'll need to clear the configuration cache to apply the changes:

php artisan config:clear

If you've added new variables to .env and want them to be loaded, run:

php artisan config:cache

Laravel recommends caching configuration for production for better performance, but while developing, you might want to keep the cache clear so that changes are applied immediately.

 

Directory Permissions

After installing Laravel and configuring the environment, it's crucial to set the proper permissions for certain directories to make sure Laravel can run smoothly. The storage and bootstrap/cache directories should be writable by your web server for Laravel to function correctly.

The storage directory contains compiled Blade templates, file-based sessions, file caches, and other files generated by the framework. Incorrect permissions can lead to various errors and issues.

To set the permissions, navigate to your Laravel project directory and execute the following commands:

Change to the Laravel Project Directory

cd my-laravel-project

Set the appropriate permissions for the storage directory.

On a Linux or macOS system, you can set the permissions using the following command:

sudo chmod -R 775 storage

Or, you can change the ownership to the web server user (commonly www-data for Apache and Nginx on Ubuntu). User 'deepak' is my system user which will act as user owner as the entire data is under user's home folder.

sudo chown -R deepak:www-data storage

On some systems, you might need to also set permissions for the bootstrap/cache directory:

sudo chmod -R 775 bootstrap/cache

Or change its ownership:

sudo chown -R deepak:www-data bootstrap/cache

The exact user and permissions might vary depending on your web server and system configuration. The above examples are commonly used settings that work on Ubuntu systems running Apache or Nginx.

Ensure that the ownership of the parent directories leading up to the public directory is set to the user and group that the Apache web server (usually www-data) uses. This is crucial for Apache to be able to traverse the directory structure and serve the files.

sudo chown -R deepak:www-data /home/deepak/my-laravel-project/public
sudo chmod -R 755 /home/deepak/my-laravel-project/public

 

Running Migrations

In a Laravel project, migrations are like version control for your database. They allow you to modify your database schema in a structured and organized manner. Running migrations is usually one of the last steps in setting up a fresh Laravel application.

Migrations reside in the database/migrations directory. Each migration file contains a class with two methods: up() and down(). The up() method is used to add new tables, columns, or indexes to your database, while the down() method is used to reverse the operations done by the up() method.

To run all of your outstanding migrations, navigate to the root directory of your Laravel project and run the following command:

php artisan migrate

Output:

   INFO  Preparing database.  

  Creating migration table ............................................................................................................... 37ms DONE

   INFO  Running migrations.  

  2014_10_12_000000_create_users_table ................................................................................................... 68ms DONE
  2014_10_12_100000_create_password_reset_tokens_table ................................................................................... 66ms DONE
  2016_06_01_000001_create_oauth_auth_codes_table ........................................................................................ 84ms DONE
  2016_06_01_000002_create_oauth_access_tokens_table ..................................................................................... 83ms DONE
  2016_06_01_000003_create_oauth_refresh_tokens_table .................................................................................... 79ms DONE
  2016_06_01_000004_create_oauth_clients_table ........................................................................................... 52ms DONE
  2016_06_01_000005_create_oauth_personal_access_clients_table ........................................................................... 26ms DONE
  2019_08_19_000000_create_failed_jobs_table ............................................................................................. 53ms DONE
  2019_12_14_000001_create_personal_access_tokens_table .................................................................................. 66ms DONE

This command will execute the up() method from your migration files, effectively updating your database schema as specified.

If you encounter errors, it's usually a good idea to check your .env file to make sure your database credentials and other settings are correct.

Note: Make sure you've already set up your database and updated the .env file with the correct database information before running this command. Otherwise, Laravel won't be able to connect to the database, and the migration will fail.

 

Testing Laravel Installation

After installing Laravel and resolving any errors, it's crucial to confirm that the installation is successful. Here's how you can do it:

Local Development Server: If you've used Laravel's built-in development server, you should be able to access the Laravel welcome page by navigating to http://127.0.0.1:8000 in your web browser.

Run the server with:

php artisan serve

Open your browser and go to http://127.0.0.1:8000. You should see the Laravel welcome page.

Laravel Installation Guide [Step-By-Step Explained]

 

Apache/Nginx: If you've configured Apache or Nginx, visit the configured domain or IP address where your Laravel application is located.

Laravel Installation Guide [Step-By-Step Explained]

 

Troubleshooting: Common Issues and Solutions for Laravel Installation

1. "SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'"

Possible Causes:

  • MySQL root user is not correctly configured in Laravel's .env file.
  • MySQL service isn't running.

Solutions:

  • Update .env file with correct database credentials.
  • Run sudo service mysql start.

 

2. "The stream or file ... could not be opened in append mode: Permission denied"

Possible Causes:

  • Incorrect folder permissions.

Solutions:

  • Run sudo chown -R www-data:www-data storage/ bootstrap/cache/.
  • Run sudo chmod -R 755 storage/ bootstrap/cache/.

 

3. “No application encryption key has been specified.”

Possible Causes:

  • .env is missing or misconfigured.

Solutions:

  • Copy .env.example to .env and run php artisan key:generate.

 

Summary

Congratulations, you've successfully navigated through the initial complexities of installing Laravel and resolving some common issues related to web servers and permissions. Laravel offers a robust and flexible framework for building both small-scale and large-scale web applications. Having a good understanding of the installation process and how to troubleshoot common issues is the first step toward becoming proficient in Laravel development.

  • We went through the basic prerequisites including installing PHP, Composer, and your choice of a web server.
  • We explored two methods to install Laravel: Laravel Installer and Composer.
  • We discussed configuring the environment, including the .env file and setting up a MySQL database.
  • We tackled running migrations to initialize your database.
  • Finally, we went over some common issues you might encounter and how to resolve them, especially those related to Apache and Nginx.

Next Steps

  1. Dive Into Laravel Documentation: The official Laravel documentation is a treasure trove of information.
  2. Build a Basic Project: Try creating a simple CRUD (Create, Read, Update, Delete) application to get hands-on experience.
  3. Learn More About Routing, Middleware, and Controllers: These are the building blocks of any Laravel application.
  4. Join a Community: Websites like Stack Overflow and the Laravel subreddit are excellent places for seeking help and sharing knowledge.

 

Additional Resources

Tutorials

Documentation

Courses

Books

 

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment