Last active
May 6, 2016 10:37
-
-
Save devudit/81d4a824861d7d9e11aad7f4abc8c493 to your computer and use it in GitHub Desktop.
Cache js files in laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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