Skip to content
Advertisement

Sending JSON to Laravel using POST request

so I am trying to get a hang of laravel HTTP requests and am facing an error when sending a post request that contains a JSON body…

When I first tried it out, I got an error using the same code that worked for a post request that had params attached to the URL…

My store function

public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string',
            'details' => 'required|string',
            'completed' => 'required',
            'modified' => 'required'
        ]);
        $user = Auth::id();
        $userDetails = UserDetailModel::find(1)->UserDetailId;
        $todo = new UserTodoModel;
        $todo->UserDetailId = $userDetails;
        $todo->Title = $request->title;
        $todo->Details = $request->details;
        $todo->completed = $request->completed;
        $todo->modified = $request->modified;
        $todo->save();
        return response()->json([
            'message' => 'Successfully added!'
        ], 200);
    }

Error I got

Integrity constraint violation: 1048 Column 'Title' cannot be null (SQL: insert into `UserTodo` (`UserDetailId`, `Title`, `Details`, `completed`, `modified`, `DateModified`, `DateCreated`) values (1, ?, ?, ?, ?, 2020-05-19 01:06:50, 2020-05-19 01:06:50)) in file D:My WorkspaceLaravelawizvendorlaravelframeworksrcIlluminateDatabaseConnection.php on line 671

I then found this post Posting JSON To Laravel

Which in turn led me to use this

public function store(Request $request)
    {
        // dd($request);
        $validator = Validator::make($request->all(), [
            'Title' => 'required|string',
            'Details' => 'required|string',
            'completed' => 'required',
            'modified' => 'required'
        ]);
        $user = Auth::id();
        $userDetails = UserDetailModel::find(1)->UserDetailId;
        $testData = (object) $request->json()->all();
        // dd($testData);
        $todo = new UserTodoModel;
        $todo->UserDetailId = $userDetails;
        $todo->Title = $testData->Title;
        $todo->Details = $testData->Details;
        $todo->completed = $testData->completed;
        $todo->modified = $testData->modified;
        dd($testData);
        $todo->save();
        return response()->json([
            'message' => 'Successfully added!'
        ], 200);
    }

Then I started getting this error and am not sure why…

ErrorException: Undefined property: stdClass::$Title in file D:My WorkspaceLaravelawizappHttpControllersDashboardUserTodoController.php on line 49

EDIT

Sorry, I forgot to post the dd() output…

When I use dd($testData) I get this.

{#1251
  +"0": array:8 [
    "UserTodoId" => 0
    "UserDetailId" => 1
    "Title" => "Test item2"
    "Details" => "This is a test item2"
    "completed" => 1
    "modified" => 0
    "DateCreated" => "2020-05-20T00:00:00.000000Z"
    "DateModified" => "2020-05-22T00:00:00.000000Z"
  ]
}

but when I use dd($testData->Title) I end up getting the same error

Undefined property: stdClass::$Title

I am running laravel 7.0

As for my request, I am using postman.

This is the JSON am sending

[
    {
        "UserTodoId": 0,
        "UserDetailId": 1,
        "Title": "Test item2",
        "Details": "This is a test item2",
        "completed": 1,
        "modified": 0,
        "DateCreated": "2020-05-20T00:00:00.000000Z",
        "DateModified": "2020-05-22T00:00:00.000000Z"
    }
]

and those are my headers and those are my headers

EDIT 2

What would I do if I’m sending a nested JSON, how would I go about trying to access the inner JSON? Nested JSON

{
    "fName": "Ahmed",
    "lName": "Abdelsalam",
    "email": "test@tessssssdst.com",
    "password": "123456789",
    "userDetails": {
        "FirstName": "Ahmed",
        "MiddleName": "Adil",
        "LastName": "Abdelsalam",
        "Designation": "Cashier",
        "Gender": "Male",
        "DOB": "2020-05-20T00:00:00.000000Z"
    }
}

Controller

    public function register(Request $request)
    {
        // Creating the user entry
        // JSON conversion
        $userData = (object) $request->json()->all();

        // Validation
        // $userData->validate([
        //     'fName' => 'required|string',
        //     'lName' => 'required|string',
        //     'email' => 'required|string|email|unique:users',
        //     'password' => 'required|string'
        // ]);
        // Creating instance
        $user = new User;
        $user->first_name = $userData->fName;
        $user->last_name = $userData->lName;
        $user->email = $userData->email;
        $user->password = bcrypt($userData->password);
        // Saving instance
        $user->save();

        // Creating the user details entry
        // Getting user ID
        $userId = User::where('email', $userData->email);
        // JSON conversion
        $userDetailsRawData = $userData->userDetails;
        $userDetailsData = (object) $userDetailsRawData->json()->all();
        dd($userDetailsData);
        // Validation
        // $userDetailsData->validate([
        //     'FirstName' => 'required|string',
        //     'MiddleName' => 'required|string',
        //     'LastName' => 'required|string',
        //     'Designation' => 'required|string',
        //     'Gender' => 'required|string',
        //     'DOB' => 'required',
        //     'Email' => 'required|string|email|unique:userdetails',
        // ]);
        // Creating instance
        $userDetails = new UserDetailModel();
        $userDetails->FirstName = $userDetailsData->FirstName;
        $userDetails->MiddleName = $userDetailsData->MiddleName;
        $userDetails->LastName = $userDetailsData->LastName;
        $userDetails->Designation = $userDetailsData->Designation;
        $userDetails->Email = $userData->email;
        $userDetails->Gender = $userDetailsData->Gender;
        $userDetails->DOB = $userDetailsData->DOB;
        $userDetails->UserId = $userId;
        // Saving instance
        $userDetails->save();
        return response()->json([
            'message' => 'Successfully created user!'
        ], 201);
    }

Without adding the json()->all() I end up getting an array and when I add it I get an error, I tried converting the array using json_decode() but I couldn’t use ‘->’ to access elements in the resulting JSON I seem to be missing something here

Advertisement

Answer

The element Title of your request is empty or is not present in the request

This can be due to a typo, error in the caps or something similar.

The first error shows an error in thee database trying to insert a record with an explicit required filed with null.

The second tells you are trying to access to a property that has not being initialized.

Edit:

After reviewed the dump of your variable and your request it’s visible that you are setting your requests as an element of one array.

That is why the member Title doesn’t exists. If you try to access like this: $testData[0]->Title you will find your value.

You don’t get errors before because you are assigning the values to the main $testData object.

My suggestion is update your request like this:

{
    "UserTodoId": 0,
    "UserDetailId": 1,
    "Title": "Test item2",
    "Details": "This is a test item2",
    "completed": 1,
    "modified": 0,
    "DateCreated": "2020-05-20T00:00:00.000000Z",
    "DateModified": "2020-05-22T00:00:00.000000Z"
}

Sending just one object instead of an array with one element.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement