firstOrCreate() should persist an instance of Flight and return it. My inclination is that name is not mass-assignable; do you have $fillable = ['name']; set in the Flight model?
firstOrNew
Hi
Looking at the docs (https://laravel.com/docs/5.1/eloquent) regarding firstOrCreate and firstOrNew I was expecting these 2 things to happen :-
- Return an Eloquent model if a record is found matching the attributes passed. This works as expected.
- If a record isn't found return an new Eloquent model. This works but the model doesn't have the data pre-populated.
Am I the only one that finds this behaviour a bit odd. In the below example after dump()ing the $flight variable the attributes node on the debug is blank if the record isn't found. Is that right? Should it not be pre-populated with the name field set to 'Flight 10'? It feels like we have to set the name variable whether if finds a records or not, which seems a bit messy and unnecessary.
I know that firstOrNew doesn't persist to the database and Create does but I see the same behaviour with both functions.
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
dump($flight); // the name field isn't set at this point so we have to manually set it.
$flight->name = 'Flight 10';
$flight->save();
Maybe I'm doing something wrong or miss understanding the functionality? Has anyone else had experience of this?
Cheers Rich
Please or to participate in this conversation.