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

Farirai's avatar

Facing problem changing my api body to objects when making a post request

previously i was send my data like below and this was working my request body

 {
            "title": "Mr.",
            "first_name": "Karina",
            "last_name": "Kemmer",
            "nick_name": "bdubuque",
            "job_title": "Gaming Manager",
            "gender": "Male",
            "date_of_birth": "2003-08-04",
            "verification_status": null,
            "photo": null,
            "id_number": "65-5678976-R55"
        } 

my store request

 <?php

namespace App\Http\Requests;

use App\Rules\ZimbabweanPhoneNumber;
use App\Rules\ZimbabweanIdNumber;
use App\Rules\DateOfBirth;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;

class UserStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            // personal information
            'title' => 'required',
            'first_name' => 'required',
            'last_name' => 'required',
            'nick_name' => 'nullable',
            'job_title' => 'nullable',
            'gender' => 'nullable',
            'date_of_birth' => ['required', 'date', 'date_format:Y-m-d'],
            'photo' => 'nullable',
            'id_number' => ['required', 'string', new ZimbabweanIdNumber()],

            //address
            'address_type' => 'nullable|integer',
            'is_billing' => 'nullable|integer',
            'address_line1' => 'nullable',
            'address_line2' => 'nullable',
            'postal_zip_code' => 'nullable',
            'country_code' => 'nullable',
            'state_region' => 'nullable',
            'city_town' => 'nullable',
            'status' => 'nullable|integer',
            'address_verification_status' => 'nullable|integer',

            //email
            'email_type' => 'nullable',
            'address' => 'nullable',
            'email_verification_status' => 'nullable',
            'email_is_primary' => 'nullable|boolean',

            //phone
            'phone_type' => 'nullable',
            'phone_country_code' => 'nullable',
            'number' => ['required', 'string', new ZimbabweanPhoneNumber()],
            'phone_verification_status' => 'nullable',
            'phone_is_primary' => 'nullable|integer',

            //security
            'password' => 'nullable',
            'security_code' => 'nullable',
            'secret_question_1' => 'nullable',
            'security_answer_1' => 'nullable',
            'security_question_2' => 'nullable',
            'security_answer_2' => 'nullable',

            //preferences
            'preferred_language_code' => 'nullable',
            'enable_facebook_account' => 'nullable|boolean',
            'enable_promotion_notification' => 'nullable|boolean',
            'enable_email_notification' => 'nullable|boolean',
            'enable_sms_notification' => 'nullable|boolean',
            'enable_push_notification' => 'nullable|boolean',
            'timezone' => 'nullable',
            'enable_device_authentication' => 'nullable|boolean',

            //code
            'code' => 'nullable',

            //terms_conditions
            'terms_conditions_acceptance' => 'nullable',

            //geo_coordinates
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'position_description' => 'nullable',

            //custom_fields
            'custom_field_acceptance' => 'nullable',
            'acceptance2' => 'nullable',

            //notation
            'notes' => 'nullable',

            'validate',
            'validate' => 'nullable|integer',
        ];
    }
    public function headers(): array
    {
        return [
            'lang' => $this->header('lang'),
            'Time_zone' => $this->header('Time_zone'),
            'Source_id' => $this->header('Source_id'),
        ];
    }
}

my controller

 <?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Accounts;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests\UserStoreRequest;
use App\Http\Resources\V1\UserResource;
use App\Http\Resources\V1\UserCollection;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return new UserCollection(User::all());
    }

    public function createUser(Request $request)
    {
        // Create the user
        $user = User::create([
            // User data...

        ]);

        // Fetch a random account number from the accounts table
        $accountNumber = Accounts::pluck('account_number')->random();

        // Create the associated account with the randomly picked account number
        $user->accounts()->create([
            'account_number' => $accountNumber,
            'card_number' => '1234567890', // Assuming a placeholder card number
        ]);

        // Retrieve the user with the associated account
        $userWithAccount = User::with('accounts')->find($user->id);

        // Return the response with the user and account information
        return new UserResource($userWithAccount);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(UserStoreRequest $request)
    {
        return new UserResource(User::create($request->all()));
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        return new UserResource($user);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UserStoreRequest $request, string $id)
    {
        $request->validated();
        $user = User::findOrFail($id);
        $user->update($request->all());
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $user = User::findOrFail($id);
        $user->delete();
    }
}

my model

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Accounts;
use Database\Factories\UserFactory;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        //personal information
        'title',
        'first_name',
        'last_name',
        'nick_name',
        'job_title',
        'gender',
        'date_of_birth',

        'id_number',

        //address
        'address_type',
        'is_billing',
        'address_line1',
        'address_line2',
        'postal_zip_code',
        'country_code',
        'state_region',
        'city_town',
        'status',
        'address_verification_status',

        //email
        'email_type',
        'address',
        'email_verification_status',
        'email_is_primary',

        //phone
        'phone_type',
        'phone_country_code',
        'number',
        'phone_verification_status',
        'phone_is_primary',

        //security
        'password',
        'security_code',
        'secret_question_1',
        'security_answer_1',
        'security_question_2',
        'security_answer_2',

        //preferences
        'preferred_language_code',
        'enable_facebook_account',
        'enable_promotion_notification',
        'enable_email_notification',
        'enable_sms_notification',
        'enable_push_notification',
        'timezone',
        'enable_device_authentication',

        //code
        'code',

        //terms_conditions
        'terms_conditions_acceptance',

        //geo_coordinates
        'latitude',
        'longitude',
        'position_description',

        //custom_fields
        'custom_field_acceptance',
        'acceptance2',

        //notation
        'notes',

        //others
        'validate',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = ['password', 'remember_token'];

    public function account()
    {
        return $this->hasOne(Accounts::class, 'user_id');
    }

    protected static function booted()
    {
        parent::booted();

        static::created(function ($user) {
            $account = Accounts::inRandomOrder()->first();
            if (!$account) {
                // Handle the case where no accounts are available
                throw new \Exception('No accounts available.');
            }

//            $account->id = $user->id;
            $account->user_id = $user->id;

            $account->save();
        });
    }

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
}

i want to change my request body to this

 {
   
        "personal_info": {
            "title": "Mr.",
            "first_name": "Karina",
            "last_name": "Kemmer",
            "nick_name": "bdubuque",
            "job_title": "Gaming Manager",
            "gender": "Male",
            "date_of_birth": "2003-08-04",
            "verification_status": null,
            "photo": null,
            "id_number": "65-5678976-R55"
        },
        "address": {
            "address_type": null,
            "is_billing": null,
            "address_line1": null,
            "address_line2": null,
            "postal_zip_code": null,
            "country_code": null,
            "state_region": null,
            "city_town": null,
            "status": null,
            "address_verification_status": null
        },
        "email": [
            {
                "email_type": null,
                "address": null,
                "email_verification_status": null,
                "email_is_primary": null
            }
        ],
        "phone": [
            {
                "type": null,
                "country_code": null,
                "number": "+263781840930",
                "verification_status": null,
                "is_primary": null
            },
            {
                "type": null,
                "country_code": null,
                "number": "+263781840930",
                "verification_status": null,
                "is_primary": null
            }
        ],
        "security": {
            "password": null,
            "security_code": null,
            "secret_question_1": null,
            "security_answer_1": null,
            "security_question_2": null,
            "security_answer_2": null
        },
        "preferences": {
            "preferred_language_code": null,
            "enable_facebook_account": null,
            "enable_promotion_notification": null,
            "enable_email_notification": null,
            "enable_sms_notification": null,
            "enable_push_notification": null,
            "timezone": null,
            "enable_device_authentication": null
        },
        "currency": [
            {
                "code": null
            }
        ],
        "terms_conditions": {
            "terms_conditions_acceptance": null
        },
        "geo_coordinates": {
            "latitude": null,
            "longitude": null,
            "position_description": null
        },
        "custom_fields": {
            "custom_field_acceptance": null,
            "acceptance2": null
        },
        "notes": {
            "notes": null
        },
        "validate": {
            "validate": null
        },
        "account_number": null
    }

what must i change

0 likes
2 replies

Please or to participate in this conversation.