Laravel Speed and Performance Optimization 101 – The Guideline

speed-1249610_1920I am working with a pretty heavy Laravel site with many requests and lots of Eloquent/SQL calls. Even though the high-memory and high-cpu VPS, I felt there is room for performance improvement. That is why I would like to write out some improvements to speed up Laravel:

1. Use Database or Redis for cache and sessions

When you navigate to config/cache.php and config/session.php, you see that the default CACHE_DRIVER and SESSION_DRIVER = file. If you have Redis installed, just try to set it as a cache and session driver. Check if Redis is installed by running:

redis-cli

If it is installed, try to define the drivers in your .env file:

CACHE_DRIVER=redis
SESSION_DRIVER=redis

2. Use several artisan pre-made commands

There are various artisan commands that are made to cache several parts of Laravel. You can configure them in the deployment process of Laravel Forge or Envoyer:

php artisan route:cache
php artisan config:cache
php artisan optimize --force

 

Use Developer tools guideline

Do a run at https://developers.google.com/web/fundamentals/performance/ and optimize several steps:

3. Optimize images like PNGs and JPEGs

Images sometime possess useless extra data that can be lossless optimized. Therefore you can use the packages OptiPNG and JPEGOptim. In Ubuntu install OptiPNG:

sudo apt-get update
sudo apt-get install optipng

And also install JPEGOptim:

sudo apt-get install jpegoptim

Now navigate to the folder that you would like to optimize its images. For optipng run:

optipng *

For jpegoptim run:

for i in *.jpg; do jpegoptim --all-progressive "$i"; done

Note that also the subdirectories might be optimized

4. Use HTTP2 instead of HTTP 1.1 if you have an SSL certificate enabled

The following guideline helps you through the process of updating to HTTP2 in Nginx.

Note that you need to have a SSL certificate. Google PageSpeed gave a server speed change from 0.52s (without HTTP2, with SSL) to 0.35s (with HTTP2)

Result: About 30% speed increase

5. Cache response in Redis or File

Sometimes it is unnecessary that the page is called from a database many times. Just caching the page reduces quite some load. That is exactly the same idea of the Laravel Response Cache plugin. The install instructions are quite good. In my case it had a drastic performance improvement.

Result: about 200 ms speed increase in my case

6. Optimize InnoDB innodb_buffer_pool_size

I am not sure why, but for some reason InnoDB has a really small innodb_buffer_pool_size when deploying your initial Laravel Forge server. In my default case, the innodb_buffer_pool_size was 8MB, while some blogs estimate that you can reserve up to 80% of your ram for innodb_buffer_pool_size. So edit the my.conf file:

sudo nano /etc/mysql/my.cnf

And add for example:

innodb_buffer_pool_size = 1G

Result: Several times faster queries

7. Reduce load by adding swap

My server regularly had Redis full-memory issues and high loads. This was solved by adding some swap to Ubuntu. As described by DigitalOcean:

One of the easiest way of increasing the responsiveness of your server and guarding against out of memory errors in your applications is to add some swap space. Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.

Read more about adding swap at the DigitalOcean website.

Result: a reduction in load when entering the ‘top’ command

This list is still a work-in-progress list, although above tips gave me a speed improvement of MORE THAN 1 SECOND. Got any tips, let me know in the comments!

Also share your speed improvements 🙂



Laravel Eloquent Triple Pivot Relations

Solving the HasManyTriple problem

Sometimes you find yourself in the situation where you have a table like shop_country_category, which has the following structure:

countries
- id
- name

shop
- id
- name

products
- id
- name

shop_country_product
- id
- country_id
- shop_id
- product_id

In this case a shop has specific products that differ per country. So, for example in the Shop.php Eloquent model use:

    /**
     * The country-specific products that belong to a shop (triple pivot relation)
     */
    public function countryProducts()
    {
        return $this->belongsToMany('App\Product','shop_country_product')
                    ->withPivot('country_id');
    }

In this way you can access that shop_country_category

Or use a plugin

I’ve not tested it, but I heard this package might work with Laravel 5.

Do you have a better solution?

Do not hesitate to share them in the comments.



Laravel 5.1 logout custom message and redirect to previous page

When you’re logging out in Laravel 5 and 5.1 the AuthenticatesUsers is called and the getLogout method. Since, it’s in the Illuminate directory it’s not nice to write in this file directly. It’s better to rewrite the getLogout method from an Auth\AuthController.

Normally AuthCntroller, it might use this traits:

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

Now we’ll rename the getLogout of the AuthenticatesUsers trait:

use AuthenticatesAndRegistersUsers
    {
        getLogout as authLogout;
    }
    use ThrottlesLogins;

Now we can rewrite the getLogout and still use/inherit the old trait’s class:

    /**
     * Overwrite getLogout method of trait AuthenticatesUsers and calls it again, since it's renamed as $this->authLogout();
     * @return Response
     */
    public function getLogout()
    {
        if (!empty(URL::previous()) && !str_contains(URL::previous(), "auth/"))
        {
            $this->redirectAfterLogout = URL::previous(); // Send back to previous url if possible
        }

        alert()->success('You\'re logged out', 'Logout'); // Send a flash message e.g. with the SweetAlert package: https://github.com/uxweb/sweet-alert
 
        return $this->authLogout(); // rest of the old method of the trait
    }


Laravel 5 socialite with Facebook integration

Would you like to offer a Facebook login functionality next to a regular e-mail based login? This is a tutorial to achieve that with Laravel 5 and the Socialite plugin. This tutorial is based on Matt Stauffer’s tutorial.

First of all pull in Laravel Socialite via composer:

composer require laravel/socialite

Create the users and password_remember migration:

$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('avatar');
$table->string('password', 60);
$table->boolean('is_admin');
$table->rememberToken();
$table->timestamps();

Get your Facebook developer id and secret at: https://developers.facebook.com/.

Insert the Facebook credentials into the app/services.php file:

'facebook' => [
        'client_id' => env('FACEBOOK_ID'),
        'client_secret' => env('FACEBOOK_SECRET'),
        'redirect' => env('FACEBOOK_URL'),
    ],

In my case, I store them in the .env file as environment variables:

FACEBOOK_ID=xxx
FACEBOOK_SECRET=yyy
FACEBOOK_URL=http://myapp.devapp/auth/facebook/callback

Create a users model and make sure that some fields are fillable:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'avatar', 'facebook_id'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

So the model and migrations are prepared, if necessary, run your migration:

php artisan migrate

Register a new controller in your routes file (if there’s an auth controller already, do it above the auth controller):

Route::get('/auth/facebook', 'Auth\SocialController@redirectToProvider');
Route::get('/auth/facebook/callback', 'Auth\SocialController@handleProviderCallback');

Create the Facebook Social Auth Controller (app/Http/Controllers/Auth/SocialController.php):

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use Socialite;

class SocialController extends Controller
{
    /**
     * Redirect the user to the Facebook authentication page.
     *
     * @return Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * Obtain the user information from Facebook.
     *
     * @return Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('facebook')->user();

        $authUser = $this->findOrCreateUser($user);

        Auth::login($authUser, true);

        return redirect()->back();
    }

    /**
     * Return user if exists; create and return if doesn't
     *
     * @param $fbUser
     * @return User
     */
    private function findOrCreateUser($fbUser)
    {

        if ($authUser = User::where('facebook_id', $fbUser->id)->first()) {
            return $authUser;
        }

        return User::create([
            'name' => $fbUser->name,
            'email' => $fbUser->email,
            'facebook_id' => $fbUser->id,
            'avatar' => $fbUser->avatar
        ]);

    }
}

You can now link to your social auth controller from somewhere in your blade view:

<a class="btn btn-primary" href="{{ action('Auth\SocialController@redirectToProvider') }}"><span class="glyphicon glyphicon-thumbs-up"></span> Login with Facebook</a>

Important safety note

If you’d like to keep the possibility for people to login, make sure that you’ve empty password validation checks, so that people can’t sign in with only Facebook e-mail addresses.

That’s it. Do you’ve additions to this tutorial? Let me know in the comments.