Search code examples
mysqlsqllaraveleloquentlaravel-9

Laravel UpdateOrCreate with if condition


I'm using laravel 9 and would like to make a updateOrCreate query with a condition tied to it.

I want to toggle between two statuses inside the UpdateOrCreate condition.

I know you can use conditionally if statements in stuff like OrderByRaw as demonstrated below:

->orderByRaw("IF(id = {$this->request['filterID']}, 0,1)");

I tried something similar for the updateOrCreate like below:

Auth::user()->favorites()->updateOrCreate([
    'favoriteable_id' => 2,
    'favoriteable_type' => Asset::class,
],[
    "status" => "IF(status = {$active}, {$inactive},{$active})"
]);

I have a table where the status defaults to status active; that's fine when creating the record. However, when the user toggles the favorite functionality, I would like the record to switch between active and inactive status.

Is there any way to do this with the inbuild query builder from eloquent?


Solution

  • You may rewrite the Illuminate\Database\Eloquent\Relations\HasOneOrMany@updateOrCreate method to look like this:

    tap(Auth::user()->favorites()->firstOrNew([
        'favoriteable_id' => 2,
        'favoriteable_type' => Asset::class,
    ]), function ($instance) {
            $instance->fill(['status' => $instance->status == 'active' ? 'inactive' : 'active']);
    
            $instance->save();
    })