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
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article