Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

firstOrNew with "or" statement

I have a table with columns like "name", "surname", "user_id", and I need to check if entry exists first by id, and then by name and surname together, if there is none, create it. How do I do it neatly, instead of making two update statements, and if both return 0 just create a new one (which seems too bulky)

I thought of using firstOrNew, but it seems that it only can work while matching all of the parameters.
Is there any method I’ve missed that would apply well to my situation?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could try something like this (assuming you want to create a model [saved to the database]):

$attributes = [
    'name' => ...,
    'surname' => ...,
];

$model = Model::where('id', $id)
    ->orWhere(fn ($q) => $q->where($attributes))
    ->firstOr(fn () => Model::create($attributes));

This would search for a record by id OR name and surname. If it doesn’t find one it will create a new record with the name and surname (assuming those attributes are fillable on the Model).

Laravel 8.x Docs – Eloquent – Retrieving Single Models / Aggregates firstOr

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading