databaselaraveleloquentuserfrosting

Create a Record in Eloquent database if it's not existing when selecting


I created a Model and so on, and now I get my data with that code:

 $all_keys = MemberAux::select('apikey','apisecret')->where('user_id', $user_id)->first();

The table has basically just an auto-increment id, a user_id, and two data fields. I output them or update them with

$all_keys->apikey = $apikey_new;
$all_keys->apisecret = $apisecret_new;
$all_keys->save();

Works great. But when a record does not exist yet, I get errors. Now I read about the firstOrCreate method, but I'm such an beginner, I don't even know where I have to write it in my select "string". The answers and solutions I found imply knowledge I don't have yet.

BTW: I'm using Userfrosting which uses Slim Framework, Laravel and Eloquent.


Solution

  • The lazy way:

    $all_keys = MemberAux::select('apikey','apisecret')->where('user_id', $user_id)->first();
    if(!$all_keys){
     $all_keys = new MemberAux();
    }
    // rest of your code
    $all_keys->save();
    

    The way, that I think you were looking for:

    $all_keys = MemberAux::firstOrCreate(['user_id' => $user_id]);
    // rest of your code
    $all_keys->save();
    

    Note, that you may have to set fillable fields in your model.