Laravel的助手在某些情境/课程中无法正常工作

时间:2016-06-05 02:45:03

标签: php laravel-5.2 helpers

我有一个关于使用Laravel帮助者的问题(在我的情况下是路由助手)。

在控制器中调用帮助程序时,它可以正常工作。例如:

class PollController extends Controller {

    public function show(Request $request)
    {
        $route = route('polls.show'); 
        // returns 'http://application.app/polls/show'
        $data = [
            'user_token' => $request->get('token')
        ];

        return view('polls.form')->with($data);
    }

    public function save(Request $request)
    {
        dd($request->all());
    }
}

但是,在artisan tinker或命令类中调用同一个帮助器时。例如:

class Inspire extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'inspire';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Display an inspiring quote';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $route = route('polls.show'); // **returns 'http://localhost/polls/show'**
        $this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
    }
}

它(第二种情况)对我不利。我试图通过使用常量来保存正确的值然后在命令类上使用它来解决这个问题,但我遇到了同样的问题。

我希望解决这个问题,并且我希望知道为什么在这些情况下行为是不同的。

提前致谢。

1 个答案:

答案 0 :(得分:1)

route()帮助程序(以及url()和一些Laravel功能)使用当前HTTP请求中的域名。由于Artisan命令不会拥有 HTTP请求,因此Laravel会回退到app.url配置设置。将其(或默认情况下,您的.env APP_URL设置)从默认http://localhost更改为您网站的网址。