Tips in Laravel you may not know. (Part 3)

Tram Ho

1. Form validation – Only catch the first error

By default, Laravel Validation will return an array of all errors (if any). If you only want validation to stop right after the first error, use the bail rule:

2. Limit the update field

If you have a field that only wants to set a value once, doesn’t allow updates, you can set restrictions to the Model using the following tips:

3. Prepare data for form validation

If you want to modify the input data before validation, there is a method called prepareForValidation in the FormRequest class FormRequest supports this:

4. Compare dates with Carbon

If you have an events table with start_date and end_date fields, and you want to check if there are any events happening today:

5. Group by first letter

You can group Eloquent data under arbitrary conditions, this is an example grouping by the first letter of the username.

6. SoftDeletes and Query Builder

Note that SoftDeletes only works with Eloquent, not Query Builder.

Share the news now

Source : Viblo