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

PhoeniX5's avatar

Laravel firstOrCreate with multiple attributes

Hi, when using firstOrCreate method with multiple attributes it keeps using the first attribute to find the record and I don't want that, I need to use multiple attributes to check a record if it doesn't exist in the table, I am using firstOrCreate with multiple attribute for finding the record like this :

$log_pn = Log_panne::firstOrCreate(['n_s' => $request->get('n_serie')], ['panne_id' => $panne_id]);
$log_pn->n_s = $request->get('n_serie');
$log_pn->panne_id = $panne_id;
$log_pn->save();

Is ther a way to do this using Laravel Eloquent ?

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

The firstOrCreate method takes two arrays, the first of which is all of the attributes to find an existing record, the second being any additional attributes that a newly created record should get (combined with the values in the first array). So you can specify multiple key/value pairs in both arrays

1 like
mstrauss's avatar

@phoenix5

@tykus answer above is right. So in your case, you would include all necessary items to check for the existence of the the models in the first argument and then, if a model cannot be found with those details, a new model will be created with them. So something like the below:

$log_pn = Log_panne::firstOrCreate(['n_s' => $request->get('n_serie'),'panne_id' => $panne_id]);

And then you wouldn't really need the balance of the below code as the model would already be saved to the DB with the items:

// don't need... 
$log_pn->n_s = $request->get('n_serie');
$log_pn->panne_id = $panne_id;
$log_pn->save();
1 like

Please or to participate in this conversation.