Laravel 5.2 view composer gets executed multiple times

Don't route file requests through laravel and serve a blank image on 404

.htaccess sample:

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png|ico)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*$ /no_picture.png [L]

You would post this above the rules that redirect to index.php

This is assuming that pictures are served from the website and not by streaming database contents.

Basically what happens is this:

  • Backend user uploads image:
  • laravel stores image in /some/path/to/store/data/public/12a/4d8/458/12a4d8458.gif
  • laravel stores image as 12a4d8458.gif in your database
  • -------------------- time passes ------------------------
  • visitor requests page.
  • request doesn't match a file. redirect to index.php(as per .htaccess)
  • request gets send to index.php
  • laravel builds page. Finds image
  • laravel composes full public url path
  • www.awesome.com/data/public/12a/4d8/458/12a4d8458.gif
  • composed html contents get pushed to visitor
  • ---------------- milliseconds pass ------------------------
  • visitor requests image /data/public/12a/4d8/458/12a4d8458.gif
  • request matches file file gets served by apache
  • laravel remains blissfully unaware of request
  • ----------------- not a millisecond has passed -------------
  • visitor requests image /data/public/4e8/d44/98f/4e8d4498f.gif
  • request doesn't match a file. redirect to index.php(as per .htaccess)
  • laravel builds page. doesn't find a route.
  • laravel invokes 404 routines
  • laravel builds 404 page with all triggers associated
  • laravel serves 404 to user

So what you want to do in the last step is prevent the image request even reaching laravel, by serving your own image as per defined by .htaccess rules. That way your webserver can respond much faster on the missing image.