Deploy Laravel on shared hosting without headaches

Deploy a fully functional Laravel app on shared hosting with our guide on choosing providers and setting up database, storage, and cache configurations.

Deploy Laravel on Shared Hosting

Deploying a Laravel application on shared hosting can be a daunting task. You’ve probably spent hours searching for answers online, only to find conflicting information and outdated solutions. Perhaps you’ve tried uploading your project to a shared hosting provider, but couldn’t get past the first hurdle: configuring the database connection or setting up the web server.

You’ll build a fully functional Laravel application on a shared hosting server by following this step-by-step guide. By the end of it, you’ll have successfully deployed your application with a working database connection and properly configured storage and cache setup. This tutorial will walk you through the entire process, from choosing a suitable shared hosting provider to testing your application on the live server.

Choosing a Shared Hosting Provider with PHP Support

When it comes to deploying Laravel on shared hosting, the first step is choosing a provider that supports PHP and has the necessary features for a smooth deployment.

I’ve used SiteGround and Hostinger in the past, both of which have good support for PHP and offer easy one-click installations for popular frameworks like Laravel. If you’re already using a provider, make sure they meet these basic requirements.

You can check if your hosting provider supports PHP by logging into their control panel (cPanel or Plesk usually) and searching for the PHP version installed on the server. For example, with SiteGround:

<?php
$ phpinfo();
?>

This code will display a page showing the PHP version, so make sure it’s at least 8.0 to run Laravel.

When selecting a hosting provider, keep an eye out for the following:

  • Support for PHP versions 7.4 or higher (Laravel requires at least PHP 7.4)
  • MySQL or MariaDB support (Laravel uses these databases by default)
  • Optional: support for other features like Redis, Memcached, or Elasticsearch if you plan to use them

Make sure the provider has good reviews and a reputation for providing reliable hosting services. With the right provider in place, you can move on to uploading your Laravel project to the server.

Uploading Your Laravel Project to the Server

To upload your Laravel project to the shared hosting server, you’ll need to use a file transfer protocol (FTP) client or the control panel provided by your hosting provider.

Using FileZilla for FTP Upload

I prefer using FileZilla as my FTP client. First, download and install it from www.filezilla-project.org. Then, create an FTP account with your hosting provider to get the server’s IP address, username, and password.

Open FileZilla and navigate to Site Manager > New Site. Fill in the server details:

Host: ftp.your-hosting-provider.com
Username: ftp_username
Password: ftp_password
Protocol: FTP (or SFTP if available)

Uploading Files Using the Control Panel

Alternatively, you can use the control panel provided by your hosting provider to upload files. The process is usually more straightforward but less customizable than using an FTP client.

Upload all the project files to the root directory of your website. If you’re using a subdomain or a specific folder for your Laravel installation, upload the files accordingly.

Make sure to exclude the vendor directory and the node_modules directory if you have any JavaScript packages installed. You can use .gitignore files to ignore these directories during deployment.

Keep in mind that you’ll need to configure the database connection and set up a virtual host for your Laravel installation once the upload is complete.

Configuring the Database Connection in Laravel

Now that your project is uploaded and you have a basic Nginx or Apache configuration set up, it’s time to configure the database connection in your Laravel application.

To do this, navigate to the .env file located in the root of your project. Update the DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD values as necessary to match your shared hosting provider’s MySQL or PostgreSQL database settings. Here’s an example:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydatabase
DB_USERNAME=myuser
DB_PASSWORD=mypassword

Note: You may need to adjust the DB_HOST value depending on whether your shared hosting provider uses a socket connection or not.

Once you’ve updated the .env file, run the following command in your terminal:

php artisan config:clear

This will clear the cached configuration and apply the new database settings. You can then verify that your database connection is working by running:

php artisan db:seed --class=UsersTableSeeder

Replace UsersTableSeeder with the actual seeder class you’re using to seed your database.

With this step complete, you should now be able to interact with your shared hosting provider’s database from within your Laravel application.

Setting Up Nginx or Apache for Laravel

To serve your Laravel application, you’ll need a web server like Nginx or Apache configured to point to the public directory of your project. I’m assuming you’ve installed Nginx on your shared hosting provider’s system. If not, refer to their documentation on how to install it.

Create a new file called nginx.conf in /etc/nginx/conf.d/ (you may need to adjust the path depending on your OS and configuration):

sudo nano /etc/nginx/conf.d/nginx.conf

Add the following configuration:

server {
    listen 80;
    server_name example.com;

    root /path/to/public/directory;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # adjust PHP version and socket path as needed
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include fastcgi_params;
    }
}

Make sure to replace /path/to/public/directory with the actual path of your Laravel project’s public directory.

After saving the file, reload Nginx to apply the changes:

sudo nginx -s reload

If you’re using Apache, you can follow similar steps or use a virtual host configuration like this:

<VirtualHost *:80>
    ServerName example.com

    DocumentRoot /path/to/public/directory

    <Directory "/path/to/public/directory">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>

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

Save this file as /etc/apache2/sites-available/example.com.conf (again, adjust the path and name as needed) and enable it:

sudo a2ensite example.com.conf

That’s it. Your Laravel application should now be accessible via its domain or IP address.

This concludes our shared hosting setup tutorial for Laravel. Next, update your project to the latest dependencies using Composer.

Updating Composer and Installing Dependencies

Now that your Laravel project is uploaded to the server, it’s time to update Composer and install its dependencies.

First, navigate to your project directory using SSH:

cd /path/to/your/project

Update the composer.json file by running:

composer update

This may take a few minutes depending on the size of your project and the speed of your connection. Once complete, you’ll see an updated list of dependencies.

Next, install any new dependencies that have been added or updated by running:

composer install

You can verify that all dependencies are installed correctly by checking the vendor directory:

ls -l vendor/

This should display a list of directories containing your project’s dependencies. Make sure to check for any errors or warnings during this process.

If you encounter any issues, refer to the Composer documentation for troubleshooting assistance. With all dependencies in place, your Laravel application is now ready for further configuration and deployment.

Running Migrations and Seeding the Database

With your database connection configured, it’s time to run your migrations and seed the database. This step is crucial as it sets up your application’s schema and populates the database with initial data.

First, navigate to your project directory in the terminal and run the following command:

composer dump-autoload && php artisan migrate --seed

The dump-autoload part ensures that Composer updates its internal map of files, which is necessary for Laravel’s migration system. The migrate command runs any pending database migrations to update your schema.

If you’re using a fresh installation of Laravel or have made significant changes to your schema, run the following commands instead:

composer dump-autoload && php artisan migrate --seed && php artisan db:seed

The db:seed command is used separately when seeding the database with initial data. This step can take some time depending on the size of your database and the number of records being inserted.

Once you’ve completed this step, your application’s schema should be set up, and the database should be populated with initial data. Make sure to test your application thoroughly after running migrations and seeding the database.

You’re now one step closer to having a fully functional Laravel application on your shared hosting server!

Configuring Laravel’s Storage and Cache

By default, Laravel uses a file system for storing cached data, which can become an issue on shared hosting where disk space is limited. We need to configure the storage and cache properly so that our application doesn’t run out of space.

First, we’ll configure the storage. Open the config/filesystems.php file in your project’s root directory:

// config/filesystems.php

'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => public_path('storage'),
    ],
],

Here, we’re specifying that our local storage should be at public/storage.

Next, we need to configure the cache. Open the config/cache.php file:

// config/cache.php

'driver' => env('CACHE_DRIVER', 'file'),

We’ll set the driver to file by default. However, for production environments like shared hosting, it’s recommended to use Redis or Memcached instead.

To use Redis, install it first (you may need to ask your host to enable it). Then, in the config/cache.php file:

'driver' => env('CACHE_DRIVER', 'redis'),
'redis' => [
    'host' => env('REDIS_HOST', 'localhost'),
    'port' => env('REDIS_PORT', 6379),
    'database' => env('REDIS_DB', 0),
],

Make sure to install the Redis package via Composer. You can do this by running composer require predis/predis in your terminal.

Remember to update your .env file with the correct host, port, and database for Redis if you’re using it.

Testing Your Application on the Shared Hosting Server

Now that your Laravel application is set up and configured on the shared hosting server, it’s time to test if everything works as expected.

Open a web browser and navigate to your application’s URL. If you’ve followed the previous steps correctly, you should see your application’s welcome page. However, to ensure everything is working properly, let’s run some tests from the command line.

First, update your APP_URL in the .env file with the actual URL of your shared hosting server:

APP_URL=https://your-shared-hosting-server.com

Next, navigate to your project directory and run the following commands:

composer dump-autoload --optimize
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear

These commands will clear any cached configurations, routes, views, and other dependencies. Then, you can run your application’s tests using the following command:

php artisan test

This will run all the tests in your tests directory and report any errors or failures.

If everything passes without issues, congratulations! You’ve successfully deployed and tested your Laravel application on a shared hosting server.

Frequently Asked Questions

What is the minimum PHP version required to run Laravel on shared hosting?

Laravel requires at least PHP 7.4, so make sure your hosting provider supports this version.

How do I check if my hosting provider supports PHP?

Log into your control panel (cPanel or Plesk) and search for the PHP version installed on the server.

Can I use a different database management system other than MySQL or MariaDB with Laravel on shared hosting?

Yes, but you’ll need to ensure that the alternative database system is supported by your hosting provider.

What’s the difference between using an FTP client and the control panel to upload my Laravel project?

Both methods work, but using an FTP client like FileZilla can be more convenient for large file transfers.

I’ve uploaded my Laravel project, but I keep getting a ‘database connection failed’ error. What’s causing this issue?

This is likely due to incorrect database credentials or a mismatch between your local and remote database configurations.

Should I choose SiteGround or Hostinger for deploying my Laravel application on shared hosting?

Both providers are good options, but consider factors like pricing, features, and customer support when making your decision.

Comments

comments