1

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.

Standard
  • 1,450
  • 17
  • 35

2 Answers2

3
 $all_keys = MemberAux::firstOrCreate(
            [
                'user_id' => $user_id
            ],
            [
                'apikey'    => $apikey_new,
                'apisecret' => $apisecret_new
            ]);

In this code block, the first array inside the firstOrCreate performs the where query seeing if the user_id exists or not. if found then returns that records from database else create the new record using both array, first parameter and the second parameter.

But in your case, you should use updateOrCreate since you are fetching the record and updating it.

$all_keys = MemberAux::updateOrCreate(
        [
            'user_id' => $user_id
        ],
        [
            'apikey'    => $apikey_new,
            'apisecret' => $apisecret_new
        ]);

The logic behind is same as firstOrCreate but in updateOrCreate your database record will also be updated to the value provided in the second parameter (array)

Anuj Shrestha
  • 966
  • 6
  • 18
1

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.

KiprasT
  • 370
  • 5
  • 14