Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

richwilliamson's avatar

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 :-

  1. Return an Eloquent model if a record is found matching the attributes passed. This works as expected.
  2. 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

0 likes
5 replies
tykus's avatar
tykus
Best Answer
Level 104

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?

1 like
richwilliamson's avatar

Thanks for the reply, It's a good shout and it did make me double check but yes I've got the fillable setup on my model.

tykus's avatar

Dunno man, can't reproduce your behaviour - the expected behaviour works for me; have you a base model or anything extra happening on your models?

richwilliamson's avatar

Oh my god! Just figured it out, you called it though I'd got my $fillable in a mess, I must have looked at that a hundred times!!!

protected $fillable = ['name, another_column, another_column']; // I'm an idiot!
2 likes

Please or to participate in this conversation.