且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我在哪里可以在 laravel 中设置标题

更新时间:2023-01-17 10:37:34

有几种不同的方法可以做到这一点 - 都有优点/缺点.

There are a couple of different ways you could do this - all have advantages/disadvantages.

选项 1(简单):由于数组只是静态数据 - 只需手动将标题直接放在视图布局中 - 即不要从任何地方传递它 - 直接在视图中对其进行编码.

Option 1 (simple): Since the array is just static data - just manually put the headers in your view layouts directly - i.e. dont pass it from anywhere - code it straight in your view.

<?php
  //set headers to NOT cache a page
  header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
  header("Pragma: no-cache"); //HTTP 1.0
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

选项 2: 使用 查看作曲家.您可以在过滤器之前使用 App 将标题绑定到您应用中的所有视图.

Option 2: Use view composers. You can use an App before filter to bind the header to all views in your app.

App::before(function($request)  
{
     $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');

     View::share('headers', $headers);
}); 

然后在您的视图中回显 $headers.

Then just echo out the $headers in your view(s).

注意:您必须让视图设置您的标题 - 这就是为什么我们将标题传递"到 Laravel 处理的视图中.如果您尝试从过滤器或其他内容中输出标头本身,则会导致问题.

Note: you must let the view set your headers - that is why we are 'passing' the header into view for Laravel to handle. If you try and output the header itself from within a filter or something, you'll cause issues.

编辑选项 3:我刚刚发现了这个 - 你可以试试这个

Edit Option 3: I just found out about this - you could try this

App::before(function($request)  
{
     Response::header('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate');
     Response::header('Pragma', 'no-cache');
     Response::header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');
});