sn n
sn n

Reputation: 399

Laravel updateOrCreate with where clause

How to implement updateOrCreate function with where clause.

For example. I would want to update a field only if certain column contains a specific value otherwise don't update. Is it possible with updateOrCreate function?

Upvotes: 2

Views: 17177

Answers (4)

Dylan Glockler
Dylan Glockler

Reputation: 1219

If you're trying to set a value based on some criteria you can use a ternary:

'user_id' => ($request->user_id && is_numeric($request->user_id) ? $request->user_id : \Auth::user()->id)

This is the equivalent of saying, if user_id is provided and numeric, set the value to $request->user_id, otherwise take the user_id from the authenticated user, a simpler example:

'user_id' => ($request->user_id ? $request->user_id : null)

If a user_id is give in the request use that value, otherwise set value to null.

Upvotes: 0

Volod
Volod

Reputation: 1437

updateOrCreate doesn't provide this functionality as far as I know. Instead you can use regular where clause followed by update. From your question I see that you don't need to create at all.

Something::where('column', 'value')->first()->update(['otherColumn' => 'some value']);

Upvotes: 1

user5446912
user5446912

Reputation:

updateOrCreate is an update with where-clause:

$user = User::updateOrCreate(
    [
        'id'    => $userId,
        'type'  => $userType,
    ], 
    [
        'name'  => $userName,
        'email' => $userEmail,
    ]
);

This query will update the user with $userName and $userEmail if a user exists with matching $userId and $userType. If no matching user is found, a new user is created with $userId, $userType, $userName and $userEmail.

So the first array is the "where-clause" that has to match for the update, second array is the values that should be updated if a match is found and a merge of both arrays are used when creating a new user if no match was found.

See docs here

Upvotes: 10

albus_severus
albus_severus

Reputation: 3712

updateOrCreate mainly used when you upadate one column value in your model.You don't know the condition either this row is exists or not.If the row is exists then it just upadte your column value otherwise it create that row.

$update_value = YourModel::updateOrCreate(
    ['your_checking_column' => 'your_value',],
    ['your_updated_coumn' => 'your_updated_value']
);

Upvotes: 2

Related Questions