Reputation: 2417
I have defined Request inside the construct method of this class.
/**
* @var Request
*/
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
Now when I try to retrieve the post data in some function like this:
public function postListsAction()
{
dd($this->request->get("title"));
}
I am getting following error:
Cannot autowire service "App\Controller\ListController": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists.
How can I fix this issue?
Upvotes: 2
Views: 2890
Reputation: 6170
As the error message says, Request class you're trying to inject is not declared as a service. Use RequestStack instead:
namespace App\Newsletter;
use Symfony\Component\HttpFoundation\RequestStack;
class NewsletterManager
{
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function anyMethod()
{
$request = $this->requestStack->getCurrentRequest();
// ... do something with the request
}
}
Regards
Upvotes: 6
Reputation: 36
My demo:
Router:
Route::get('/test','Test\TestController@index');
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function index()
{
dd($this->request->get("name"));
}
it's working!
Upvotes: -3
Reputation: 14
Constructor is being called automatically when you are calling that controller and that time you are not passing any post data (I mean any request object). So you need to pass $request object on your that function where you are receiving post data.
public function postListsAction(Request $request)
{
dd($request->title);
}
Upvotes: 0
Reputation: 18250
The injectable service class is called RequestStack
You can access the current request by calling getCurrentRequest
e.g.
namespace App\Managers;
use Symfony\Component\HttpFoundation\RequestStack;
class SomeManager
{
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function serviceMethod()
{
$request = $this->requestStack->getCurrentRequest();
}
}
Upvotes: 1
Reputation: 574
I think the issue is you are trying to inject the Request as a service in the constructor. Could you try the following approach
use Symfony\Component\HttpFoundation\Request;
public function postListsAction(Request $request)
{
dd($request->get("title"));
// .....
}
Symfony documentation: https://symfony.com/doc/4.3/controller.html#the-request-object-as-a-controller-argument
Upvotes: 1