Laminas Diactoros JsonResponse

Hi,

i have create a very simple Action for a test. I send a Ajax request and want a JsonResponse.

Every time i use the Laminat Diactoros Json Response function i get a the default layout HTML Template back.

public function ajaxRequestAction(){
	$request = $this->getRequest();
	$test = $request->getPost()->toArray();
 	return new \Laminas\Diactoros\Response\JsonResponse(
		     $test,
		     200,
		     ['Content-Type' => ['application/json']]
	 );

}

Hello and welcome to our forums! :smiley:

This is correct as far as laminas-diactoros cannot be used in this way in a laminas-mvc based application.

Use the strategy function of laminas-view to create alternative outputs like JSON:

Register the strategy, for example in config/autoload/global.php

return [
    // …
    'view_manager' => [
        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],
];

Then use the related view model in your controller action:

public function ajaxRequestAction()
{
	$request = $this->getRequest();
	$test    = $request->getPost()->toArray();

 	return new \Laminas\View\Model\JsonModel($test);
}

This will use the JsonRenderer of laminas-view to generate the output.

1 Like

See also at the controller plugins there you will find the AcceptableViewModelSelector plugin:

https://docs.laminas.dev/laminas-mvc/plugins/#acceptableviewmodelselector-plugin

1 Like

Thank you so much :upside_down_face:
It works perfect!