ivqonsanada's avatar

How to edit database notification data

this is the current schema of notifications

 Schema::create('notifications', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });

i can read it using this

                $userNotification = $user->notifications()
                    ->where('type', 'match-request-xxx')
                    ->whereRaw("CAST(data::json->>'request_join_id' AS INTEGER) = ?", [$requestJoinId])
                    ->first();

but after try to update it using this

                if ($userNotification) {
                    $data = $userNotification->data;

                    $data['request_join_vote_status'] = $voteStatus;

                    $userNotification->update([
                        'data' => json_encode($data),
                    ]);

                    return JsonResponseHelper::successResponse($userNotification, 'Request join vote updated successfully');
                }

the response already changed, but the database not changed at all

0 likes
4 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To edit the data field of a notification in Laravel, you need to ensure that you're correctly handling the JSON data. The code you provided is mostly correct, but let's go through it step-by-step to ensure everything is clear and functioning as expected.

Step-by-Step Solution

  1. Retrieve the Notification: You are correctly retrieving the notification using the where clauses. Ensure that $requestJoinId is correctly set and matches the data in your database.

  2. Decode the JSON Data: When you access $userNotification->data, it should be decoded into an associative array. If it's not, you need to decode it manually.

  3. Update the Data: Modify the data as needed.

  4. Encode the Data: Before updating the database, encode the modified data back to JSON.

  5. Update the Notification: Use the update method to save the changes.

Here's a refined version of your code:

if ($userNotification) {
    // Decode the JSON data into an associative array
    $data = json_decode($userNotification->data, true);

    // Update the specific field
    $data['request_join_vote_status'] = $voteStatus;

    // Encode the data back to JSON and update the notification
    $userNotification->update([
        'data' => json_encode($data),
    ]);

    return JsonResponseHelper::successResponse($userNotification, 'Request join vote updated successfully');
}

Additional Considerations

  • Error Handling: Consider adding error handling for JSON encoding/decoding to ensure data integrity.
  • Database Transactions: If this operation is part of a larger set of database operations, consider using a transaction to ensure atomicity.
  • Testing: Test the update operation to ensure that the data is correctly modified and saved in the database.

By following these steps, you should be able to successfully update the data field of a notification in your Laravel application.

Shivamyadav's avatar

Try this

if ($userNotification) {
    // Decode the JSON data into an array
    $data = json_decode($userNotification->data, true);

    // Update the data as needed
    $data['request_join_vote_status'] = $voteStatus;

    // Update the notification data in the database
    $userNotification->update([
        'data' => json_encode($data),
    ]);

    return JsonResponseHelper::successResponse($userNotification, 'Request join vote updated successfully');
}
1 like
ivqonsanada's avatar

sadly still not working

                if ($userNotification) {
                    // Get the existing data array
                    $data = json_decode($userNotification->data, true);

                    $data['request_join_vote_status'] = $voteStatus;

                    $userNotification->data = json_encode($data);
                    $userNotification->read_at = now();

                    $userNotification->save();

                    $userNotification->update([
                        'data' => $data,
                        'read_at' => now(),
                    ]);

                    return JsonResponseHelper::successResponse($userNotification, 'Request join vote updated successfully');
                }

i have tried both approach by save function or update function, the response model show the updated version but nothing happen on the database, i tried to also update the read_at but nothing happen also

update:

i also tried to use forceFill function and nothing happened in the database

                  $updateResult = $userNotification->forceFill([
                        'data' => $data, // No need to manually encode if cast is set
                        'read_at' => now(),
                    ])->save();
ivqonsanada's avatar

ah, it actually a simple issue, i forget this process is in the middle of DB Transaction, and i just return it earlier while the DB Commit is in the last line

i should realize this earlier, what a waste of time :|, anyway, thank you for the help @shivamyadav

Please or to participate in this conversation.