Skip to content

Instantly share code, notes, and snippets.

@jeffochoa jeffochoa/1.php Secret
Last active Apr 22, 2019

Embed
What would you like to do?
speed-up-your-laravel-pages-by-caching-the-responses
<?php
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\Nckg\Minify\Middleware\MinifyResponse::class
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
],
<?php
public function show($id)
{
$post = Cache::remember("post-{$id}", function () use ($id) {
return Post::find($id);
}
return view('post')->withPost($post);
}
<?php
protected $routeMiddleware = [
...
'doNotCacheResponse' => \Spatie\ResponseCache\Middlewares\DoNotCacheResponse::class,
'cacheResponse' => \Spatie\ResponseCache\Middlewares\CacheResponse::class,
];
<?php
// Out of cache
Route::get('/preview/{slug}', 'ArticleController');
/**
* Cached routes
*/
Route::middleware('cacheResponse')->group(function () {
Route::get('/{slug}', 'ArticleController');
});
<?php
namespace App\Observers;
use App\Post;
use Spatie\ResponseCache\Facades\ResponseCache;
class PostObserver
public function saved(Post $post)
{
ResponseCache::forget(url($post->slug));
}
public function saved(Post $post)
{
ResponseCache::forget(url($post->slug));
}
```
<?php
namespace App\Providers;
use App\Post;
use App\Observers\PostObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Post::observe(PostObserver::class);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.