Reputation: 4717
When using Model::firstOrCreate
in Laravel 4.2, is there a way of knowing which happened,, first or create?
Let me explain,,, My understanding is that with ::firstOrCreate a record is created IF it doesn't exist OR values of records containing argument array data are returned.
So if I have something like this:
// Auth::user()->id; returns 7
$person = Persons::firstOrCreate(array(
'approver' => 123,
'receiver' => Auth::user()->id,
'plan' => 'gold',
));
And I have these records
approver | receiver | plan
____________________________________
123 | 7 | silver
____________________________________
128 | 7 | gold
____________________________________
123 | 7 | platinum
____________________________________
Then a new record will be created
approver | receiver | plan
____________________________________
123 | 7 | silver
____________________________________
128 | 7 | gold
____________________________________
123 | 7 | platinum
____________________________________
123 | 7 | gold
____________________________________
And if I run the above code again then the new value will not be created and this record will be returned
approver | receiver | plan
____________________________________
123 | 7 | gold
____________________________________
But if my code looks like this
$person = Persons::firstOrCreate(array(
'approver' => 123,
'receiver' => Auth::user()->id
));
These records will be returned
approver | receiver | plan
____________________________________
123 | 7 | silver
____________________________________
123 | 7 | platinum
____________________________________
123 | 7 | gold
____________________________________
If my understanding of ::firstOrCreate is not correct please help me understand it better.
And as I mentioned,, I am interested to know if there is a way to determine if CREATE of new record happened or not?
Upvotes: 2
Views: 2635
Reputation: 219946
The model has a wasRecentlyCreated
property:
$person = Persons::firstOrCreate([
'approver' => 123,
'receiver' => auth()->id(),
'plan' => 'gold',
]);
if ($person->wasRecentlyCreated) {
// $person was created
} else {
// $person was fetched
}
For older versions of Laravel, you can achieve what you want with firstOrNew
:
$person = Persons::firstOrNew([
'approver' => 123,
'receiver' => Auth::user()->id,
'plan' => 'gold',
]);
if (! $person->id) {
$person->save();
// $person was created...
} else {
// $person was fetched...
}
Upvotes: 9