Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
sn n Avatar asked Jan 31 '26 03:01

sn n


1 Answers

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