timgavin
8 months ago

Insert or Update with Increments

Posted 8 months ago by timgavin

I'm looking to persist search terms and record how many times they've been searched with an incrementing value.

In the following example I'm recording a username search. If the record isn't found, create a new one. If it is found, update it. Simple enough.

There's got to be a cleaner way of doing this though, right?

$search = Search::where('term', $request->username)->first();

if($search) {
    $search->increment('clicks', 1);
    $search->save();
} else {
    Search::create([
        'term' => $request->username,
        'clicks' => 1
    ]);
}

Please sign in or create an account to participate in this conversation.