

This technique requires Mass Assignment to be set up, either using the fillable or guarded properties to dictate which fields may be passed into the create call.įor this example the following would work (as a property of the User class): /** This returns the User for the specified email if found, otherwise creates and returns a new user with the combined array of email, firstName, and lastName.

I Know I can achieve this using laravel collection map and group by ,but I prefer using a single query.

If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument. I want to find the total sells of Individual Product and then sum sells of each product while fetching categories. The firstOrCreate method will attempt to locate a database record using the given column / value pairs. I find it odd that there is no version of this function which allows you to use a. It's explained in the documentation as follows: Takes an input array and returns a new array without duplicate values. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().Īs of Laravel 5.3 it's possible to do this in one step with firstOrCreate using a second optional values parameter used only if a new record is created, and not for the initial search. Introduction Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. setting a name or some mandatory field), you should use firstOrNew(). If you want to modify the model instance before it is saved for the first time (e.g. Otherwise it will give you the matched item.Ĭhoosing between one or the other depends on what you want to do.
