laravel-helpers-make-life-easier
在没有充分的知识作为前提的情况下, 即使行了万里路, 也不过是邮差而已。There are a ton of helper methods in Laravel that make development more efficient. If you work with the framework, I encourage you to see what helpers you can introduce in your day-to-day work. In this blog post, I’d like to point out a few of my favorites.
data_get
The data_get() helper allows you to get a value from an array or object with dot notation. This functions similarly to array_get() as well. The optional third parameter can be used to supply a default value if the key is not found.
1 | $array = ['albums' => ['rock' => ['count' => 75]]]; |
If you use a “wildcard” (*) in your dot notation, Laravel will return an array of results.
1 | $array = ['albums' => ['rock' => ['count' => 75], 'punk' => ['count' => 12]]]; |
str_plural
The str_plural() helper converts a string to its plural form. Currently, only English is supported. The optional second parameter will allow the helper to choose the plural or singular form. The helper is also smart enough to help with “uncountable” or special case words.
1 | tr_plural('dog'); // dogs |
route
The route() helper generates a URL for the specified named route. The optional second argument will accept additional route parameters. If additional parameters aren’t named Laravel will try it’s best to match them to the attributes on the route then will add any remaining parameters to the end of the URL.
1 | Route::get('burgers', 'BurgersController@index')->name('burgers'); |
abort_if
The abort_if() helper throws an exception if the given expression evaluates to true. The optional third parameter will accept a custom response text, and the optional fourth argument will accept an array of headers.
1 | abort_if(! Auth::user()->isAdmin(), 403); |
So many of us have done something similar to the below example, and the abort_if() helper can cut it down to one line.
1 | // In "admin" specific controller |
optional
The optional() helper allows you to access properties or call methods on an object. If the given object is null, properties and methods will return null instead of causing an error.
1 | // User 1 exists, with account |
The optional() helper is ideal when using objects you might not own or calling nested data within Eloquent relationships that may, or may not, be available.