UpdateOrCreate not working has expected - laravel

im trying to user the method "updateOrCreate", and works almost has expected but with a problem.
For example if the record doesnt exists it creates, untill now great, but for example if i change a value in my case the "mybankroll" value it creates another record. I can that understand that is creating because one of the columns record value doesnt exist, but i dont understand how the update actions is fired.
My code example:
UserBankroll::updateOrCreate(
['my_bankroll' => $request->mybankroll, 'currency' => 'EUR'],
['user_id' => Auth::user()->id]
);
But if i try to update the value of my_bankroll, instead of updating it created another record.

You seem to have your arrays backwards.
The first array should be what you are matching against, the second array should be the update values.
https://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html#method_updateOrCreate

UserBankroll::updateOrCreate(
['user_id' => Auth::user()->id],
['my_bankroll' => $request->mybankroll, 'currency' => 'EUR']
);

Related

Laravel Eloquent updateOrCreate doesn't work properly

I once wrote probably same question last time and I'm back..
Laravel Eloquent firstOrCreate doesn't work properly
On the last question, I found that fillable property filters update field manifest. So, if you want to update a table based on fieldA and fieldB, then your code might be..
$modelOrRelation->updateOrCreate(
['fieldA' => 'a', 'fieldB' => 'b'], ['otherfields' => 'update value']
);
and you MUST specify those fields on fillable property. $fillable = ['fieldA', 'fieldB', ...]
This is what I know about firstOrCreate and updateOrCreate.
At this time, following code generate many same rows. It looks like, the first parameter ['candle_date_time_kst'] do nothing..
// candleRelation is hasMany relation..
$candleRelation = $market->candles($period);
$created = $created->add($candleRelation->updateOrCreate(
[
'candle_date_time_kst' => $time,
],
$item
));
This creates many same candle_date_time_kst value rows. At this time, fillable property already filled target fields.
What else do I miss?
Is updateOrCreate should not trust? I didn't think so.. There are something I miss... any insight?
#220114 update
So, I do my homework..
Using DB::getQueryLog(), I get this query..
It looks like, updateOrCreate() remembers the last update value. Then if I reuse same eloquent relation object for another updateOrCreate(), method use last update parameter again. It makes and clause, so return record is none..
So, I use newQuery() method for initialize query bindings.
$created->add($candleRelation->newQuery()->updateOrCreate(
[
'candle_date_time_kst' => $time
],
$item
));
#220114
Unfortunately, retest reveals newQuery() actually not helping..
I tried $relation->newModelInstance() and getting same bindings.
What I trying to do is getting same parent binding without anything else. .. anyone knows?
Based on binding, when I get relation model I can get clean binding also. So I just do below..
$created->add($market->candles($period)->updateOrCreate(
[
'candle_date_time_kst' => $item['candle_date_time_kst']
],
$item
));
Only change is $candleRelation to $market->candles($period).
On each attempt, new relation instance produce so binding problem won't even exists.
.... I'm mad.
you need to supply an array in the format
[ column => value, ... ] not [ value ]
I had a similar problem a time ago. And the UpdateOrInsert method solved it.
Unfortunately, this method is Query Builder, not eloquent. But to achieve this result that was the only really working solution to me.
The issue for only happened when I tried to use more than 1 column on where clause, like in your example.

Problem with adding record to database after seeds in Laravel

I add test records to the database using seeds
public function run()
{
DB::table('categories')->insert([
['id' => 1,'name' => 'Select a category', 'slug' => null],
['id' => 2,'name' => 'Computers', 'slug' => 'computer-&-office'],
]);
}
But then, if I want to add a new record to the database, already through the form, I get the error
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey"
I understand that when I add a new record through the form, it is created with id = 1, and I already have this id in the database. How can I avoid this error?
You should remove id from insert() and make it auto increment in mysql,
It complains about a unique constraint, meaning your primary key is indexed as "categories_pkey" or you have another field that is unique.
This happens because you are inserting a record and a record already exists where that column must be unique.
In general production workflow, when you add a record you never specify an ID. Most cases (there are exceptions) ID is an autoincrement integer, meaning it adds up automatically. On the first insert the database set its ID to 1, the second to 2 and so on.
As a seeder, its generally a good idea to set up the ID so you know that a certain ID matches a certain item (as a base content of a project like user states or roles).
As a regular workflow (from a form submission), you can have something like this
DB::table('categories')->insert([
['name' => 'some value', 'slug' => 'some slug']
]);
However, I don't advise to use DB::table when Laravel provides ActiveRecords pattern (ORM, called Eloquent) which you should take a look here.
https://laravel.com/docs/8.x/eloquent#introduction
Besides the benefits of layer abstraction and working with activerecords, It produces a much cleaner code like
$data = ['slug' => 'some slug', 'name' => 'some name'];
Category::create($data);

I get duplicate entries with the attach method in Laravel 5. Not sure what the problem is

So I'm trying to attach id's with some meta data to a pivot table in Laravel 5.
For some reason, I get the two inserts where there should be one, and the wrong ID's being inserted the second time round.
I'm not sure if there is something I might be missing here.
This is the code:
$match_values = array(
'dataId' => $result->id,
'dataMetaId' => $the_meta->id
);
$result->campaignDataMeta()->attach($match_values, [
'meta_value' => $value
]);
The database structure consists of a main campaignData table for email campaigns, a campaignDataMeta table (id, timestamps, name) for email meta data names, and a lookup table campaignDataMatches (id, campaignDataId, campaignDataMetaId, meta_value).
In campaignDataMatches I get the campaignDataId value sometimes being inserted into the campaignDataMeta column.
I've solved the problem.
Apparently had to add the relevant ID (in this case the dataMetaId) within the attach parameter.
Like this:
$result->dataMeta()->attach([$data_meta_id => [
'meta_value' => $value
]]);
Check the database columns primary maybe the dataId and metaId are both primary.

Laravel Create Record and Use ID Value in Another Column

When I create a new record in my Fan model, at the same time that I create the new Fan record, I want to use the new ID value in another column. I'm trying to do this all at once and not have another method to go back and update the record.
$fan = Fan::create([
'display_name' => $displayName,
'bio' => $bio,
'logo_url' => $logoUrl,
'algolia_id' => 'fan_'??, // I want to replace ?? with this record's ID value.
]);
I've tried $fan, but doesn't work since that variable isn't created yet. I cannot use Auth because the ID isn't the Auth user's ID.
Thanks!
I doubt you can automatically do it, you should do it in 2 steps:
$fan = Fan::create([
'display_name' => $displayName,
'bio' => $bio,
'logo_url' => $logoUrl
]);
$fan->algolia_id = 'fan_' + $fan->id;
$fan->save();
That said, it's not a great database design, you'd rather want to build the algolia_id field when you need to use it, since you'd store duplicated value (the id and the algolia_id are the same except for fan_).

First Or Create

I know using:
User::firstOrCreate(array('name' => $input['name'], 'email' => $input['email'], 'password' => $input['password']));
Checks whether the user exists first, if not it creates it, but how does it check? Does it check on all the params provided or is there a way to specifiy a specific param, e.g. can I just check that the email address exists, and not the name - as two users may have the same name but their email address needs to be unique.
firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate() and firstOrNew():
firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.
Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().
As of Laravel 5.3 it's possible to do this in one step with firstOrCreate using a second optional values parameter used only if a new record is created, and not for the initial search. It's explained in the documentation as follows:
The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument.
Example
$user = User::firstOrCreate([
'email' => 'dummy#domain.example'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
This returns the User for the specified email if found, otherwise creates and returns a new user with the combined array of email, firstName, and lastName.
This technique requires Mass Assignment to be set up, either using the fillable or guarded properties to dictate which fields may be passed into the create call.
For this example the following would work (as a property of the User class):
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['email', 'firstName', 'lastName'];
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like:
$user = User::firstOrCreate([
'email' => 'abcd#gmail.com'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it checks only the email.
An update:
As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.
The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:
See the Laravel API documentation
You can always check if in current instance the record is created with the help of
$user->wasRecentlyCreated
So basically you can
if($user->wasRecentlyCreated){
// do what you need to do here
}

Resources