5 Laravel Helpers to Make Your Life Easier
Published on by Chris Gmyr
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.
$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.
$array = ['albums' => ['rock' => ['count' => 75], 'punk' => ['count' => 12]]];$counts = data_get($array, 'albums.*.count'); // [75, 12]
The data_get()
helper allows you to find elements in your arrays and objects using the same syntax, which is excellent since you don’t have to check what type of variable you have before using it.
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.
str_plural('dog'); // dogsstr_plural('cat'); // cats str_plural('dog', 2); // dogsstr_plural('cat', 1); // cat str_plural('child'); // childrenstr_plural('person'); // peoplestr_plural('fish'); // fishstr_plural('deer', 2); // deer
The str_plural()
helper will allow you to remove code similar to this: {{ $count == 1 ? 'dog' : 'dogs' }}
. There is also a str_singular()
helper available. If you’re interested in learning more about how this works, most of the heavy lifting is done by Doctrine’s Inflector Class.
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.
Route::get('burgers', 'BurgersController@index')->name('burgers');route('burgers'); // http://example.com/burgersroute('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/1route('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/chrisroute('employees.show', ['id' => 5, 'name' => 'chris']); // http://example.com/employees/5/chrisroute('employees.show', ['id' => 5, 'name' => 'chris', 'hide' => 'email']); // http://example.com/employees/5/chris?hide=email
For my rule of thumb if the route only has one parameter I’ll pass the second argument as a single variable:
route('burgers.show', 1)
. However, if there is more than one parameter then I like to be explicit and pass a named array:route('employees.show', ['id' => 5, 'name' => 'chris'])
. This will help Laravel match the arguments to the parameters and cut down on any unexpected results.
By passing false
to the optional third parameter, you can have the helper return a relative URL instead of an absolute one.
route('burgers.show', 1, false); // /burgers/1
Routing for sub-domains works as straightforward as adding another attribute
Route::domain('{location}.example.com')->group(function () { Route::get('employees/{id}/{name}', 'EmployeesController@show')->name('employees.show');}); route('employees.show', ['location' => 'raleigh', 'id' => 5, 'name' => 'chris']); // http://raleigh.example.com/employees/5/chris
You can also pass an Eloquent model directly to route()
route('burgers.show', Burger::find(1)); // http://example.com/burgers/1
This works because the base Model
class implements the UrlRoutable
interface. The default behavior uses the primary key of the model, but you can override this by adding a getRouteKeyName()
method to your model.
class Burger extends Model{ public function getRouteKeyName() { return 'slug'; }}
Then your usage would become
Route::get('burgers/{slug}', 'BurgersController@show')->name('burgers.show'); route('burgers.show', Burger::find(1)); // http://example.com/burgers/everyones-favorite-burger
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.
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.
// In "admin" specific controllerpublic function index(){ if (! Auth::user()->isAdmin()) { abort(403, 'Sorry, you are not an admin'); }} // better!public function index(){ abort_if(! Auth::user()->isAdmin(), 403);}
Note: If you’re strictly doing this check access control, you should take a peek at using authorization gates. Once you have the gate in place you can then wrap your admin and customer specific routes, so you don’t need to have abort
checks in your codebase – or at least not as many.
optional()
Laravel's 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.
// 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.
What’s next?
These five examples are only a small selection of what Laravel helpers have to offer. I’d encourage you to get familiar with all of the available helpers and start implementing them into your codebase.
If you’d like to create custom helpers for your project Laravel News has a great article about how to do so.