简体   繁体   中英

updateOrCreate Function in laravel

Code is fine and I'll double check my code but I didn't find anything wrong in my code. This doesn't update or insert address or new user data in any condition.

$user = User::updateOrCreate(
    [
        'id' => Auth::id(),
        'address' => auth()->user()->address
    ],
    [
        'address' => $request->address
    ]
);

if ($user)
    return response()->json([
        'status' => 200,
        'add' => $request->address,
        'msg' => 'Address Updated Successfully'
    ]);
else
    return response()->json([
        'status' => 200,
        'msg' => 'Error Occured'
    ]);

Same Code here just taking user_id in parameter

$user = User::updateOrCreate(
    [
        'id' => $request->id
    ],
    [
        'address' => $request->address
    ]
);

if ($user)
    return response()->json([
        'status' => 200,
        'add' => $request->address,
        'msg' => 'Address Updated Successfully'
    ]);
else
    return response()->json([
        'status' => 200,
        'msg' => 'Error Occured'
    ]);

If you use "updateOrCreate" method in UserController, this is not a good practice to make them in the same endpoint. Normally, "updateOrCreate" should be used for secondary type of data. For main data, creating and updating should hit the separate endpoints thus separate methods.

Furthermore, If you have Auth::id(), then you have a user. So there is nothing to create. To update the user, just use update method and get the user with id.

To create a user, use the "store" method pass the values and create it there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM