Monday, July 29, 2019

Laravel : 10 Hidden Laravel Eloquent Features You May Not Know

Laravel is a feature-rich framework. However, you cannot find all the available features in the official documentation. Here are some features that you may not know.
  1. Get original attributes
After mutating an Eloquent record you can get the original attributes by calling getOriginal()
2. Check if Model changed
Determine if the model or given attribute have been modified using isDirty()
You can also check if a particular attribute is changed.
3. Get changed attributes
Retrieve the changed attributes of a model using getChanges()
Note: Changes will reflect only if you save the model or sync the changes using syncChanges()
4. Custom deleted_at column
By default, Laravel handles soft deletes using deleted_at column. You can change this by explicitly defining the DELETED_AT property.
Or by defining an accessor.
5. Save models and relationships
You can save a model and its corresponding relationships using the push()method.
6. Reload fresh model
Reload a fresh model instance from the database using fresh()
7. Reload existing model
You can reload an existing model with fresh values from database using refresh()
Note: refresh() will also update the loaded relations of the existing model.
8. Check if models are the same
Determine if two models have the same ID and belong to the same table using is()
9. Clone a model
You can clone a model using replicate(). It will create a copy of the model into a new, non-existing instance.
10. Specify attributes in find() method
When using find() or findOrFail() methods you can specify the attributes to select as the second argument.

Laravel : Laravel Image Upload Made Easy