tips/ 87 published

Tips

Small Laravel and PHP snippets, one idea each. The ones I reach for often enough to write down.

Laravel

Laravel: whereBelongsTo

New in Laravel v8.64. Use the whereBelongsTo method, which will automatically determine the proper relationship and foreign key for the given model.

Laravel

Eager load selected relationship columns

Eager Loading Specific Columns. You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:

Laravel

Conditionally compile CSS classes with Blade @class

The @class directive conditionally compiles a CSS class string. The directive accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression.

Laravel

Create a model when firstOrCreate finds no match

The firstOrCreate method will attempt to locate a database record using the given column/value pairs. If the model can't 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.

Laravel

Use firstOr with a fallback callback

The firstOr method will return the first result matching the query or, if no results are found, execute the given closure. The value returned by the closure will be considered the result of the firstOr method.

Laravel

Constrain route parameters with a regular expression

If you want to ensure that your Route parameter is a number, you can add a regex rule directly in the routes. For more detail: https://laraveldaily.com/laravel-route-filtering-with-regular-expressions/ https://laravel.com/docs/8.x/routingparameters-regular-expression-constraints

Showing 12 of 87

Laravel2 of 87

Eager load selected relationship columns

Eager Loading Specific Columns. You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:

Eager load selected relationship columns