5 laravel helper functions to make your life easier.Laravel has a fair amount of helpers to make the programmer’s day-to-day life easier. If you’ve been programming in Laravel for a long time, you may notice how the framework’s helpers make the programmer’s work more efficient and convenient.
In fact, there are quite a few helper functions, but today I will consider my favorites. Well, stop wasting words, let’s take a look at these Laravel helpers.
Table of Contents
data_get ()
This helper is from the laravel array helpers category.
The helper data_get()allows you to get data from an array/object by key, in the already familiar format – separating keys through a dot, as when calling views view(‘admin.users.index’).
Let’s consider the example of the original array:
$data = [
‘users’ => [
[‘name’ => ‘Alex’, ‘iq’ => 100500],
[‘name’ => ‘Dmitry’,’iq’ => 99]
]
];
The helper data_get($data, $key)takes 2 main arguments, where
data is the original array or object,
the key is the key by which we want to get the data.
And, wanting to get the name of the first user (from the array above), you can reverse it like this, explicitly specifying the index of the array element:
data_get($data, ‘users.0.name’); //Alex
Or, to get the field of iq all users:, data_get($data, ‘users.*.iq’)which results in an array of numbers:
Array ( [0] => 100500 [1] => 99 )
Nothing prevents you from doing more complex structures, with more complex nesting.
* – means getting the whole array, all elements
We work with objects in the same way:
$company = Company::with(‘reviews’)->findOrFail(1);
data_get($company, ‘reviews.*.review’); //Array ( [0] => All is good:) [1] => All is good:) [2] => All is good:) )
Also, it is important to know that this function takes 3 arguments, which indicates the default value if nothing was found:
data_get($data, ‘users.0.name’, ‘undefined’);
The helper data_get()allows you not to think about the type of the source data (this is an array, or an object), and allows, with the help of “syntactic sugar”, to shift the responsibility for type checking, searching for values and handling errors to the framework itself.
str_plural ()
It is a helper that allows you to convert a string to plural. This helper helps determine the correct ending for a word, depending on the number of its essence. As a general idea, this helper should automatically detect the ending for a word:apple: 1 apple, 2 apples...
The function takes two arguments, where is the number to be declined, depending on its amount – this is the number, which indicates the plurality of the number.str_plural($value, $count = 2)
$value
$count
Now, let’s check the work on the example of the word “apple” :
echo str_plural(‘apple’, 2); //apples
echo str_plural(‘apple’, 1); //apple
As you can see from the signature of the helper, the second argument is optional. Therefore, with the usual call of a function with one argument, we will always receive the plural (which is what the name of this function plural indicates – plural ):
echo str_plural(‘apple’); //apples
The opposite function is str_singular()one that converts the plural to the singular:str_singular(‘apples’); //apple
At the moment, only English localization is supported.
route ()
This laravel URL is a helper that generates an address by route name.
When generating an address by name of routes, changing their patterns, you do not have to re-write URLs in the code, since they will only be linked to their names.
Let’s look at routes as an example:
Route::get(‘users’)->name(‘users’);
Route::get(‘user/{id}’)->name(‘user’);
The function route()takes 3 argumentsroute($name, $parameters = [], $absolute = true)
Knowing this, it will be easy to create a link by route name:
route(‘users’); // http://localhost/users
route(‘user’, 1); // http://localhost/user/1
route(‘user’, [‘id’ => 1]); // http://localhost/user/1
route(‘user’, User::find(1); // http://localhost/user/1
route(‘user’, [‘id’ => 1, ‘like’ => 1]); // http://localhost/user/1?like=1
You can see that this helper is universal: it accepts parameters as a primitive value, array, or even an object. And, thanks to this, the second arguments can be passed not only route identifiers {id} , but also additional parameters that will be added to the URL .
And the last, third argument is the generation of an absolute path. If passed false, the paths will be absolute and will look like:/user/1
If an eloquent object is passed to the helper as the second argument, the framework will also recognize it and generate the correct URL. By default, it will substitute id(PRIMARY KEY) in its route, however, you can override this in the model itself by adding a method in which to specify the name of the field by which the route will be generated
public function getRouteKeyName()
{
return ‘alias’;
}
And the URL will be just as simple:
route(‘user’, User::find(1)); // http://localhost/user/username
abort_if ()
The framework already has a similar helper abort()that throws HttpExceptions . The function takes 2 main arguments abort($code, $message = ”), where
$codeis the http response code,
$message -.
And, when programming in laravel, you often have to use constructs like this:
if(!$user->isAdmin()) {
abort(403, ?’);
//abort(403);
}
It’s nice that Laravel developers took care of such a little thing, and created a wrapper over the abort () function, which simplifies to:
abort_if(!$user->isAdmin(), 403, ‘А?’);
And, similarly to the helper abort, the abort_iffirst argument takes a condition under which an exception will be thrown.
abort_if(true, 404); //
abort_if(false, 404); //
optional ()
This helper allows you to access the properties or methods of the passed object. The helper optional()allows you to call any properties of an object, ignoring errors, even if you pass it instead of an object null.
$advert = Advert::find(1);
$advert_parent = $advert->parent;
$parent = optional($advert_parent)->name;
// вместо
$parent = $advert->parent ? $advert->parent->name : null;
When making a call , it seems that if the variable is , we will get an error when trying to get the property. However, internally, this function does a lot of work that allows such calls to be made without worrying about the contents of the variable.optional($advert_parent)->name$advert_parentnull
This function is ideal for invoking data nesting in objects, especially those linked in Eloquent, where the result of the linked data is not always obvious .
Summary.
In this article, I’ve shown you 5 essential Laravel helpers that I use every day that make my life a lot easier. However, this is only a small part of what the framework provides.
I recommend that you familiarize yourself with all available built-in helpers, as well as actively use and implement them in development.
Now, having mastered these helpers, I am sure that your life has become a little easier.
For professional services or consultation from GCC Marketing Dubai please Contact Us or call us directly on 00971567300683