Ad

How Does FirstOrNew Looks For Records On The Database?

- 1 answer

I have an existing record on my table:

company_id       first_name      last_name         age    
DCI-201812001      John             Doe            27

What I want is that, if I insert new record, I want to check if the record is new or to be updated by checking the first_name, last_name, and age.

I used firstOrNew method in Laravel, however, when I tried to insert a record with the ff. values:

first_name = "John"
last_name = "Doe"
age = 29

Laravel's firstOrNew thinks that it is the same as my existing record stated above.

This is my controller: enter image description here

Screenshots

  1. This is what being retrieved when I inserted a record somewhat the same with the existing record. first_name = "John", last_name = "Doe", age = 29. It retrieved the existing record. Why does it retrieves the existing record when the age column is different? Why it doesn't consider the age that I passed?

enter image description here




Please disregard question number 2. I realized that if record is not found, it returns a new instance of the model.

  1. This is what being retrieved when I inserted a completely different record. first_name = "Felicita", last_name = "Ignacio", age = 25. Why does the age column become null when I passed a value 25 on age column on the form?

enter image description here

Ad

Answer

Your first_name, last_name, and age need to be like this:

[
    'first_name' => ...,
    'last_name' => ...,
    'age' => ...,
]

not like this:

['first_name' => ...],
['last_name' => ...],
['age' => ...],

You're sending three separate arrays as three separate arguments. You should be sending one array as the first argument.

(The second argument for firstOrNew is an additional array of default values to set if the orNew part executes.)

Ad
source: stackoverflow.com
Ad