Skip to content
Advertisement

How to get JSON from one parameter of request in Laravel

I want to send a stringified JSON to one of the fields of an API request like following:

Decoded:

https://api.some.com/foo/bar?a=788&b=My Name&c=[{"name":"pejman"},{"Some":"thing"}]

I want to get c parameter using $request->c but I want to get it as a decoded JSON automatically in my controller.

This is my PHP code

MyRequest.php:

<?php

use InfyOmGeneratorRequestAPIRequest;

class MyRequest extends APIRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'a' => 'required',
            'b' => 'required',
            'c' => 'requried',
        ];
    }
}

SomeController.php:

<?php

class SomeController extends Controller
{

    public function store(MyRequest $request)
    {
        $c = $request->c;
        $c = $request->json('c');
        $c = $request->json()->all();
    }

}

???? I want $c to be a JSON decoded automatically in my controller, How can I do that? Is that event possible to do this using MyReqest and how?

Advertisement

Answer

You can manipulate the request data using prepareForValidation() method that located in IlluminateValidationValidatesWhenResolvedTrait. So, implement this method in your MyRequest class:

protected function prepareForValidation()
{
    $this->merge([
        'c' => json_decode($this->c),
    ]);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement