Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

Where can I set headers in laravel

I want to set headers as array('Cache-Control'=>'no-cache, no-store, max-age=0, must-revalidate','Pragma'=>'no-cache','Expires'=>'Fri, 01 Jan 1990 00:00:00 GMT'); for all my views, currently I'm doing this in all controllers while returning views, like

$headers=array('Cache-Control'=>'no-cache, no-store, max-age=0, must-revalidate','Pragma'=>'no-cache','Expires'=>'Fri, 01 Jan 1990 00:00:00 GMT');

Redirect::to('/',301,$headers);`

So instead of writing this for each and every route can it be done in global scope, so that headers are set for every view.

I tried setting headers by creating after filter, but didn't get it to work.

Can anyone tell me where can I set the headers for all my views?

UPDATE One of my view file meta content

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>

Now when i use Redirect::to('/',301,$headers) The header in firebug is

Cache-Control   max-age=0, must-revalidate, no-cache, no-store, private
Connection  Keep-Alive
Content-Type    text/html; charset=UTF-8
Date    Tue, 09 Jul 2013 14:52:08 GMT
Expires Fri, 01 Jan 1990 00:00:00 GMT

And when I use Redirect::to('/');

The header in firebug is

Cache-Control   no-cache
Connection  Keep-Alive
Content-Type    text/html; charset=UTF-8
Date    Tue, 09 Jul 2013 14:52:08 GMT
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Laravel 5, using Middleware, creating a new file, modifying an existing file:

New file: app/Http/Middleware/AddHeaders.php

<?php namespace AppHttpMiddleware;

use Closure;
use IlluminateContractsRoutingMiddleware;

// If Laravel >= 5.2 then delete 'use' and 'implements' of deprecated Middleware interface.
class AddHeaders implements Middleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('header name', 'header value');
        $response->header('another header', 'another value');

        return $response;
    }
}

Modify existing file app/Kernel.php

protected $middleware = [
.
.
.

        'AppHttpMiddlewareAddHeaders',
    ];

And you're set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...