Laravel 5:内部调用路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37472138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:52:40  来源:igfitidea点击:

Laravel 5: Calling routes internally

laravellaravel-5

提问by vcardillo

Is there a way, in Laravel 5, to call routes internally/programmatically from within the application? I've found a lot of tutorials for Laravel 4, but I cannot find the information for version 5.

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

回答by erwan

Using laravel 5.5, this method worked for me:

使用 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);

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

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

*note:maybe you will have issue if the route you're trying to access has authentication middleware and you're not providing the right credentials. to avoid this, be sure to set the correct headers required so that the request is processed normally (eg Authorisation bearer ...).

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

回答by The Alpha

You may try something like this:

你可以尝试这样的事情:

// 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);

回答by geckob

You can actually call the controller that associates to that route instead of 'calling' the route internally.

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

For example:

例如:

Routes.php

路由.php

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

UserController.php

用户控制器.php

class UserController extends Controller {

   public function getUser($id){

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

   };
}

Instead of calling /getUserroute, you can actually call UserController@getUserinstead.

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

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

This is the same as callingthe route internally if that what you mean. Hope that helps

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

回答by Rajib

// 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
   }

回答by heisian

None of these answers worked for me: they would either not accept query parameters, or could not use the existing app() instance (needed for config & .env vars).

这些答案都不适合我:他们要么不接受查询参数,要么无法使用现有的 app() 实例(需要配置和 .env 变量)。

I want to call routes internally because I'm writing console commands to interface with my app's API.

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

Here's what I did that works well for me:

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

<?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));
    }
}

Your Controller/Route will work exactly as if you had called it using curl. Have fun!

您的控制器/路由将完全像您使用curl. 玩得开心!