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

dwacas11@gmail.com's avatar

Laravel get JSON array

public function register(Request $request){

      $user = $this->user->create([
        'name' => $request->get('name'),
        'surname' => $request->get('surname'),
        'email' => $request->get('email'),
       'password' => bcrypt($request->get('password'))
     ]);

        return response()->json(['status'=>true,'message'=>'User created                
       successfully','data'=>$user]);

}

I have this register user functions, now I need POST simple text, but I want POST json array like this: json

[{"email":"[email protected]"},{"password":"123456"},{"name":"123456"},{"surname":"123456"}]

0 likes
13 replies
tykus's avatar

You can decode that JSON, create a collection from the resulting array of arrays, and collapse the collection into a simple associative array:

// assuming the JSON is received as a single field???
$userData = collect(json_decode($request->get('json')))
    ->collapse();
//[
//       "email" => "[email protected]",
//      "password" => "123456",
//       "name" => "123456",
//      "surname" => "123456",
//]

$user = $this->user->create($userData);
1 like
dwacas11@gmail.com's avatar

public function register(Request $request){

  $userData = collect(json_decode($request->get('json')))
    ->collapse();

    $user = $this->user->create($userData);

}

I POST like this: http://imgur.com/XZRHp4K and have error

FatalThrowableError in Builder.php line 732: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in C:\xampp\htdocs\svt\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1329

Because $userData is empty

edoc's avatar

why don't you cast to an array?

tykus's avatar

Sorry, my fault, needed to convert back to an array after the Collection steps:

$userData = collect(json_decode($request->get('json')))
    ->collapse()->all();
tykus's avatar

What is coming in on the request? Can you dd($request->all()) at the top of your register() method and post it here?

tykus's avatar

You said you wanted to send this JSON:

[{"email":"[email protected]"},{"password":"123456"},{"name":"123456"},{"surname":"123456"}]

But what is actually being received at the Controller? Just temporarily, do the following so we can see what the request payload actually looks like:

public function register(Request $request){
    dd($request->all());
    
    //$userData = collect(json_decode($request->get('json')))
            ->collapse()->all();

        //$user = $this->user->create($userData);
}

Please or to participate in this conversation.