【问题标题】:Laravel 5: Calling routes internallyLaravel 5:内部调用路由
【发布时间】:2016-05-26 22:36:07
【问题描述】:

在 Laravel 5 中,有没有办法在应用程序内部/以编程方式调用路由?我找到了很多 Laravel 4 的教程,但我找不到版本 5 的信息。

【问题讨论】:

  • 您是否在问如何在应用程序中使用自己的路由? IE。在控制器内部获得路由的结果?这些是 JSON 端点吗?
  • 您不必这样做。你可以实例化你的控制器并调用方法
  • @Geckob 发布了正确答案。出于好奇,您为什么需要这样做?
  • 将回报嵌入为更大回报的子级。

标签: laravel laravel-5


【解决方案1】:

使用 laravel 5.5,这个方法对我有用:

$req = Request::create('/my/url', 'POST', $params);
$res = app()->handle($req);
$responseBody = $res->getContent();
// or if you want the response to be json format  
// $responseBody = json_decode($res->getContent(), true);

来源: https://laracasts.com/discuss/channels/laravel/route-dispatch

*注意:如果您尝试访问的路线可能会遇到问题 具有身份验证中间件,您没有提供正确的凭据。 为避免这种情况,请务必设置所需的正确标头,以便正常处理请求(例如Authorisation bearer ...)。

更新:我已经在 laravel 8 中尝试过这种方法并且它有效,但是如果您使用的是 PHP 8.0 版,您可能需要在此行之前调用 opcache_reset(); $req = Request::create('/my/url', 'POST', $params); 以避免错误。

查看guzzlehttp/guzzle dosn't work after update php to php 8了解更多信息

【讨论】:

  • 我正在尝试这种方法,但我无法获取 $params 下发送的 POST 数据。
【解决方案2】:

你可以试试这样的:

// GET Request
$request = Request::create('/some/url/1', 'GET');
$response = Route::dispatch($request);

// POST Request
$request = Request::create('/some/url/1', 'POST', Request::all());
$response = Route::dispatch($request);

【讨论】:

  • 从 Artisan 命令调用时,Route::dispatch 似乎无法正常工作!但是@erwan 的回答在这种情况下效果很好:$response = app()->handle($request);
  • @ArnovanOordt 的建议是使用app()->handle() 而不是Route::dispatch(),如果您遇到\Illuminate\Http\Request 的错误实例被注入到您的中间件的问题,则可以解决此问题。跨度>
  • 同意@ArnovanOordt info RE:从 Artisan 命令调用。 app()->handle($request) 是解决方案
【解决方案3】:

您实际上可以调用与该路由关联的控制器,而不是在内部“调用”该路由。

例如:

Routes.php

Route::get('/getUser', 'UserController@getUser');

UserController.php

class UserController extends Controller {

   public function getUser($id){

      return \App\User::find($id);

   };
}

您实际上可以调用UserController@getUser 而不是调用/getUser 路由。

$ctrl = new \App\Http\Controllers\UserController();
$ctrl->getUser(1);

这与calling 内部路由相同,如果您的意思是这样的话。希望有帮助

【讨论】:

  • 这对于寻找输入数据的路线有什么作用?即,一个 POST 路由。
  • 有什么想法吗,@geckob?
  • @vcardillo 同样的事情。但是传递一些参数给函数来模仿post bosy
  • Laravel 在内部做了很多事情来调度路由,远远超出了简单地创建控制器实例和调用方法,所以这样做会遇到很多问题。正确答案来自@The Alpha
【解决方案4】:
// this code based on laravel 5.8
// I tried to solve this using guzzle first . but i found guzzle cant help me while I 
//am using same port. so below is the answer
// you may pass your params and other authentication related data while calling the 
//end point
public function profile(){

//    '/api/user/1' is my api end please put your one
// 
$req = Request::create('/api/user/1', 'GET',[ // you may pass this without this array
        'HTTP_Accept' => 'application/json', 
        'Content-type' => 'application/json'
        ]);
$res = app()->handle($req);
$responseBody = json_decode($res->getContent()); // convert to json object using 
json_decode and used getcontent() for getting content from response 
return response()->json(['msg' =>$responseBody ], 200); // return json data with 
//status code 200
   }

【讨论】:

    【解决方案5】:

    这些答案都不适合我:它们要么不接受查询参数,要么不能使用现有的 app() 实例(config & .env vars 需要)。

    我想在内部调用路由,因为我正在编写控制台命令来与我的应用的 API 交互。

    这就是我所做的对我很有效的事情:

    <?php // We're using Laravel 5.3 here.
    
    namespace App\Console;
    
    use App\MyModel;
    use App\MyOtherModel;
    use App\Http\Controllers\MyController;
    use Illuminate\Console\Command;
    
    class MyCommand extends Command
    {
        protected $signature = 'mycommand
                                {variable1} : First variable
                                {variable2} : Another variable';
    
        public function handle()
        {
            // Set any required headers. I'm spoofing an AJAX request:
            request()->headers->set('X-Requested-With', 'XMLHttpRequest');
    
            // Set your query data for the route:
            request()->merge([
                'variable1' => $this->argument('variable1'),
                'variable2'  => $this->argument('variable2'),
            ]);
    
            // Instantiate your controller and its dependencies:
            $response = (new MyController)->put(new MyModel, new MyOtherModel);
    
            // Do whatever you want with the response:
            var_dump($response->getStatusCode()); // 200, 404, etc.
            var_dump($response->getContent()); // Entire response body
    
            // See what other fun stuff you can do!:
            var_dump(get_class_methods($response));
        }
    }
    

    您的控制器/路由将完全像您使用 curl 调用它一样工作。玩得开心!

    【讨论】:

      猜你喜欢
      • 2014-10-13
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 2015-06-16
      • 2015-10-02
      • 1970-01-01
      • 2015-07-31
      • 2017-05-22
      相关资源
      最近更新 更多