Fork me on GitHub

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
2
3
4
5
6
7
8
9
$array = ['albums' => ['rock' => ['count' => 75]]];
$count = data_get($array, 'albums.rock.count'); // 75
$avgCost = data_get($array, 'albums.rock.avg_cost', 0); // 0
$object->albums->rock->count = 75;
$count = data_get($object, 'albums.rock.count'); // 75
$avgCost = data_get($object, 'albums.rock.avg_cost', 0); // 0

If you use a “wildcard” (*) in your dot notation, Laravel will return an array of results.

1
2
$array = ['albums' => ['rock' => ['count' => 75], 'punk' => ['count' => 12]]];
$counts = data_get($array, 'albums.*.count'); // [75, 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
2
3
4
5
6
7
8
9
10
tr_plural('dog'); // dogs
str_plural('cat'); // cats
str_plural('dog', 2); // dogs
str_plural('cat', 1); // cat
str_plural('child'); // children
str_plural('person'); // people
str_plural('fish'); // fish
str_plural('deer', 2); // deer

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
2
3
4
5
6
7
8
9
10
11
12
Route::get('burgers', 'BurgersController@index')->name('burgers');
route('burgers'); // http://example.com/burgers
route('burgers', ['order_by' => 'price']); // http://example.com/burgers?order_by=price
Route::get('burgers/{id}', 'BurgersController@show')->name('burgers.show');
route('burgers.show', 1); // http://example.com/burgers/1
route('burgers.show', ['id' => 1]); // http://example.com/burgers/1
Route::get('employees/{id}/{name}', 'EmployeesController@show')->name('employees.show');
route('employees.show', [5, 'chris']); // http://example.com/employees/5/chris
route('employees.show', ['id' => 5, 'name' => 'chris']); // http://example.com/employees/5/chris
route('employees.show', ['id' => 5, 'name' => 'chris', 'hide' => 'email']); // http://example.com/employees/5/chris?hide=email

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
2
3
abort_if(! Auth::user()->isAdmin(), 403);
abort_if(! Auth::user()->isAdmin(), 403, 'Sorry, you are not an admin');
abort_if(Auth::user()->isCustomer(), 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
2
3
4
5
6
7
8
9
10
11
12
13
// In "admin" specific controller
public function index()
{
if (! Auth::user()->isAdmin()) {
abort(403, 'Sorry, you are not an admin');
}
}
// better!
public function index()
{
abort_if(! Auth::user()->isAdmin(), 403);
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
// User 1 exists, with account
$user1 = User::find(1);
$accountId = $user1->account->id; // 123
// User 2 exists, without account
$user2 = User::find(2);
$accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
// Fix without optional()
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null
// Fix with optional()
$accountId = optional($user2->account)->id; // null

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.

https://laravel-news.com/5-laravel-helpers-make-life-easier