Different Ways to store data in laravel 10
How many ways exist to Store data into database in laravel?
In this post, we will learn how to store data into database in Different Ways in Laravel 10. So let's begin.
Model ( $model->property )
In this Model Create: we use the Eloquent Model to store the data and you can also give selected column name/attribute to insert data.
Model Create with $request->all() method
Note: If you save as shown below, make sure to add all the fields in your $fillable property in your Model ( Eg. Product.php Model )
Example for fillable property in your model:
Model Create with $request->only() method
Note: Add all the field names in the Model (app/Models/Product.php file)
The below code to save data is for specific fields only, where you can choose "FORM Input fields" using the $request->only() method and save data as shown below:
We can create and inject attributes to constructor of the model and save data using save() method with the object of the model.
Model using Fill() method and save()
We use the fill() method to build/add all the fields with data on Eloquent as shown below:
We can use Query Builder for saving data in database like this:
Save data using insert() with Model:
Here, this insert() method uses the Query builder method and it do not creates or save timestamp fields in database by default instead it keeps it NULL. but in create() method it save with timestamp.
Model with firstOrCreate() method to save data.
The firstOrCreate() method in Laravel's Eloquent ORM is used to retrieve the first record matching the specified attributes. If no matching record is found, it creates a new record in the database with the given attributes. Here's an example of how firstOrCreate() can be used in Laravel:
Model with firstOrNew() method to save data.
The firstOrNew() method in Laravel's Eloquent ORM is used to retrieve the first record matching the specified attributes. If no matching record is found, it will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise, it will give you the matched item. Here's an example of how firstOrNew() can be used in Laravel:
Model with updateOrCreate() method to save data.
The updateOrCreate() method in Laravel's Eloquent ORM is used to find a record that matches the given attributes. If found, it updates the record with the specified values; if not found, it creates a new record with the provided attributes. Here's an example demonstrating the usage of updateOrCreate():
Upsert() in Laravel: Updating Existing Records and Inserting New Data Dynamically.
In Laravel, the upsert() method allows you to perform an "upsert" operation, which means updating existing records or inserting new records based on a given set of conditions. It's particularly useful when dealing with bulk operations or when you want to update existing records or insert new ones based on certain criteria.
Thanks for reading...