Skip to content

Instantly share code, notes, and snippets.

@devudit
Last active May 6, 2016 10:37
Show Gist options
  • Save devudit/81d4a824861d7d9e11aad7f4abc8c493 to your computer and use it in GitHub Desktop.
Save devudit/81d4a824861d7d9e11aad7f4abc8c493 to your computer and use it in GitHub Desktop.
Cache js files in laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class CacheJsController extends Controller
{
function __construct()
{
}
public function cache_js(Request $request, $file)
{
$_expires = 20160;
switch ($file) {
case 'analytics.js':
$_remote_file = 'https://www.google-analytics.com/analytics.js';
break;
default:
\App::abort(404);
break;
}
if (!Cache::has($file)) {
$_remote = file_get_contents($_remote_file);
$_time = new \DateTime('now');
Cache::put($file, [$_time, $_remote], $_expires);
} else {
$_cache = Cache::get($file);
$_remote = $_cache[1];
$_time = $_cache[0];
}
$response = Response::make($_remote, 200)
->header('Content-Type', 'text/javascript')
->header('Cache-Control', 'private, max-age=' . $_expires)
->setLastModified($_time)
->setExpires(\Carbon\Carbon::now()->addMinutes($_expires));
return $response;
}
}
<?php
// Add this to your routes.php
Route::get('/js/{file}', 'CacheJsController@cache_js');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment