简体   繁体   English

laravel 中的 updateOrCreate 函数

[英]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_id

$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.如果您在 UserController 中使用“updateOrCreate”方法,那么将它们放在同一个端点中并不是一个好习惯。 Normally, "updateOrCreate" should be used for secondary type of data.通常,“updateOrCreate”应该用于次要类型的数据。 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.此外,如果你有 Auth::id(),那么你就有了一个用户。 So there is nothing to create.所以没有什么可以创造的。 To update the user, just use update method and get the user with id.要更新用户,只需使用 update 方法并获取具有 id 的用户。

To create a user, use the "store" method pass the values and create it there.要创建用户,请使用“store”方法传递值并在那里创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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