从Laravel中的服务提供商获取url参数 [英] Get url parameter from Service Provider in Laravel

查看:256
本文介绍了从Laravel中的服务提供商获取url参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在Laravel中,您会获得一个带有所有参数的请求包.但是在服务提供商中却并非如此.但是我们确实有request()对象.

Normally in Laravel you get a request bag with all parameters in it. But in a service provider this is not the case. But we do have the request() object.

但是,它不包含资源路由中给定的url参数.

However, this does not contain the url parameters given in the resource routing.

所以我正在寻找一种从路线中检索{id}的方法.

So what I'm looking for is a way to retrieve the {id} from the route.

我尝试过:

request()->route('id')
Route::get('id')
Request::get('id')

所有这些返回null

All of these return null

推荐答案

在解析请求之前,将调用任何服务提供商的 boot() register()方法和请求参数是已知的,这就是为什么您无法访问它们的原因.

Both boot() and register() methods of any service provider are called before request is parsed and request parameters are known, that's why you can't access them.

服务提供者应该注册服务,并且不应依赖于请求上下文.如果要在服务中使用请求参数,请将 request 服务声明为服务的依赖项,以便在实例化服务时将其注入.

Service providers are supposed to register services and shouldn't depend on the request context. If you want to use request parameters in your services, declare request service as a dependency of your service so that it's injected the moment your service gets instantiated.

这篇关于从Laravel中的服务提供商获取url参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆