im@markvi.eu

In Lar­avel, you can use the upda­te­OrIn­sert method to per­form an upsert (update or insert) oper­a­tion on the data­base. The method takes two argu­ments: an array of con­di­tions to match a record in the table, and an array of val­ues to update or insert if the record doesn’t exist.

Here’s an exam­ple of how you can use the upda­te­OrIn­sert method to upsert a record in a users” table:

User::updateOrInsert(
    ['email' => $request->input('email')],
    [
        'name' => $request->input('name'),
        'password' => Hash::make($request->input('password')),
    ]
);

In this exam­ple, it will look for a record in the users” table where the email” col­umn is equal to the val­ue of the email input field in the request. If a match­ing record is found, it will update the name” and pass­word” columns with the val­ues from the request. If no match­ing record is found, it will insert a new record with the val­ues from the request.

You could also use Elo­quent mod­els and upda­te­Or­Cre­ate() method to achieve the same results as above.

User::updateOrCreate(
    ['email' => $request->input('email')],
    [
        'name' => $request->input('name'),
        'password' => Hash::make($request->input('password')),
    ]
);

This will also update the exist­ing record if it found with the attrib­ut­es passed or insert if not.

Please note that, for this exam­ples to work you should have user mod­el and it should be ref­er­enced accord­ing­ly in the code.

Similar Articles