如何在每次页面加载时(但仅在路由控制器执行之后)执行代码?

时间:2019-04-01 12:22:52

标签: laravel

我正在基于Laravel的项目上工作,我需要在每次页面加载时执行一些“基本” php代码。到目前为止,我将代码放在AppServiceProvider的boot()中。效果很好,但是只有在已经执行了路由控制器的代码之后,我才需要执行“基本”代码。

我已经搜索过laravel的官方文档,但是我仍然不知道该怎么做。

这是我的路线的样子:

Route::match(['get', 'post'], '/profile/email/{profile_id?}', 'profileController@profileHandleEmail')->name('profile/email');

我要达到的结果是先执行profileController @ profileHandleEmail中的代码,再执行AppServiceProvider中的“基本”代码。

哪种方法是最好的方法?我想使用AppServiceProvider无法实现。

2 个答案:

答案 0 :(得分:0)

实现所需目标的建议方法是使用中间件:

运行php artisan make:middleware PostProcess

它应在App\Http\Middleware下生成一个中间件类

class PostProcess {

      public function handle($request, $next) {
          $response = $next($request);
          // Run you code here. 
          return $response
      }
}

然后修改您的App\Http\Kernel.php中间件:

protected $middleware = [
       //Existing entries
       \App\Http\Middleware\PostProcess::class
];

该中间件将在生成响应之后但在将响应发送到客户端之前运行。如果要在之后之后运行代码,则将响应发送给客户端,您可以使用terminable middleware

class PostProcess {

      public function handle($request, $next) {
          return $next($request);
      }

      public function terminate($request, $response) {
         //Your code here 
      }
}

答案 1 :(得分:0)

第一步:创建中间件

php artisan make:middleware PostProcess

Step2:编写所需的代码

class PostProcess {

      public function handle($request, $next) {
          if(condition){
              you code here
          }
          return $next($request);
      }
}

Step3:在kernel.php中调用中间件

 protected $routeMiddleware = [
     'admin' => \App\Http\Middleware\PostProcess::class,
 ];

第4步:在路由文件中调用中间件

 Route::group(['middleware' => 'admin'], function() {

 });