Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lararara's avatar

Transform incoming (API/POST) request json field into php array?

How can I transform an incoming API request field, in my case it's blog into a PHP array automatically? Without needing to json_decode everything in each controller method?

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreBlogDataRequest $request) 
    {
		// Has a rule with 'blog' => ['required', 'json'],

		$validated = $request->safe()->collect();

		// $validated['blog'] is a json string and I'd need to convert it via php_decode to store it so the 
		// $casts will convert it into an ArrayObject properly. 
	}

I don't see anything in Laravel that could take in the $request and transform it automatically. I know I can call json_decode manually, but if I have 10 methods, then I need to do the same thing after the $validated call each time.

0 likes
5 replies
eszterczotter's avatar
Level 31

You can add this to StoreBlogDataRequest:

    protected function passedValidation()
    {
        $this->merge([
            'blog' => json_decode($this->input('blog'), true),
        ]);
    }

Make sure you add the true flag to json_decode, because the merged value has to be an array.

Since Laravel automatically validates requests when typehinted, you do not actually need the $request->safe() call, because that will get specifically the values that went into the validator, in which blog will still be a string, but you could use $request->json('blog') or $request->input('blog') to retrieve the merged value in your Controller.

Another perfectly valid option would be to add a getter to StoreBlogDataRequest like this:

    public function getBlogAsArray(): array
    {
        return json_decode($this->safe()->input('blog'), true);
    }

Then you could just use the $request->getBlogAsArray() to get the desired value. This option also works if you have turned off automatic request validation for some reason and absolutely must use the $request->safe() method. But again, if you haven't turned it off, you can just use $request->input('blog') or $request->json('blog') in the getter as well.

1 like
lararara's avatar

@eszterczotter Thanks for this, didn't know about the passedValidation or the no need to call $request->safe() part.

1 like
lararara's avatar

@martinbean No it doesn't, I thought that was what the automatic serialsation / deserialsation did. I assumed incorrectly

Please or to participate in this conversation.