Outsource Laravel Development Partner - $3200/Month | Bacancy

5 Laravel Helpers to Make Your Life Easier

Published on by

5 Laravel Helpers to Make Your Life Easier image

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'); // 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

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/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

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 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);
}

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.

Chris Gmyr photo

Full-stack web developer and coffee enthusiast.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article
Livewire 4 Support in Laravel VS Code Extension v1.4.3 image

Livewire 4 Support in Laravel VS Code Extension v1.4.3

Read article