Home » Lists » Top 12 Useful Helpers For Laravel

Top 12 Useful Helpers For Laravel

Laravel framework tries to be more objective-oriented than other frameworks. It has a dependency injection feature that can help create and manage objects more efficiently. But it also has numerous global functions that make programming simpler. These functions are called helpers.

In this article we will take a better look at the top 15 useful helpers for Laravel. I will skip the most popular helpers, such as app(), config(), env(), response() and others, because I want to show less popular but no less useful ones.

Best Helpers For Laravel

1. tap()

The creator of Laravel Taylor Otwell likes this helper a lot. The tap() helper has been used many times in the Laravel source code. This helper accepts two arguments: any value and closure, and return the first argument as result. Thus, you can get certain value and immediately apply an action to it. For example, you can get the current user and change its email:

$user = tap($request->user(), function ($user) { $user->email = "haait@haait.net"; });

If you do not use this helper, then this code will take more lines. Here is one more way to use this helper. You can set only the first argument and call methods from the value in the chain. For example:

$user = tap($request->user())->update(["email" => "haait@haait.net"]);

As you know the update() method returns an integer. But the tap() helper will wrap the user object in the proxy class. The update() method is called from the proxy class. This class executes update() from the user model but ignores the value and returns the first argument of the tap() method.

2. compact()

If you use views in your application, you may want to pass some variables to the local template. Usually, this code is used for this:

$color = "yellow"; $size = "large"; return view("view_name") ->with("color", $color) ->with("size", $large);

But here is another way to do this. You can pass all required variables as an array into the second argument of the view() helper. And you can put some local variables in the array using a compact() helper. For example:

$color = "yellow"; $size = "large"; return view("view_name", compact("color", "large"));

It may be simpler than passing each variable manually.

3. collect()

Laravel has an excellent tool for managing arrays of data. This tool is collections. Eloquent uses collections by default for all arrays of data. But if you want to convert your own array into a collection, you can use the collect() helper. For example:

$data = ["one", "two", "three", "four"]; $collection = collect($data); $collection->add("orange");

Now, you can use all collections methods for this $collection instance.

4. dump()

You can print the value of any variable using the dd() helper. But in this case the execution of the application will be interrupted. If you want to print the value and continue program execution, use the dump() helper:

dump("test 1"); dump("test 2"); dump("test 3");

In the latest versions of Laravel the dump() helper outputs the file name and the line number where it has called. Now you will never forget where is this function placed.

5. fake()

Laravel uses the faker package to generate dummy data for testing purposes. Usually, it is available in factories. But you can also use it elsewhere. Now it becomes easier. Just use the fake() helper to access Faker. For example:

fake()->realText(100); fake()->number;

6. now()

You can use Carbon for working with dates. Earlier, you had to use Carbon::now() or Carbon::today() to get the current date. But since Laravel 9, you can use now() and today() helpers, which will return Carbon instances as well:

now() today()

7. optional()

This helper was designed to help deal with errors of accessing null objects. For example: “Call to a member function ‘xxxxx()’ on null” and “Cannot read property ‘xxxxxxxxxx’ of null”. The option helper accepts any variable as the first parameter and returns a proxy object that can be used to read values from the object that has been passed. If you pass null into optional(), all methods that you call will return null and will not raise exceptions. For example:

optional(Carbon::now())->format("Y-m-d"); optional(null)->format("Y-m-d");

8. blank()

This helper() can be used in if conditions to determine that the variable is empty. It ensures that the variable is null, the string is empty or contains only spaces, the collection or array has no elements etc. For example:

blank(""); blank(collect());

9. filled()

In contrast to the previous helper, this one checks that the variable is not empty. It is working in the same way. Let’s have a look at the example:

filled(""); filled(collect());

9. logger()

You can use the Illuminate\Support\Facades\Log facade to access the logger everywhere. You can also just call logger helper(). For example:

logger()->info("This is info line"); logger()->error("An error occurred");

Also, you can use the info() helper to write the info message to the log file:

info("This is an info line");

10. action()

Most likely, you are using the route() method to generate links based on the route name configured in routes/api.php or routes/web.php. But if you want, you can generate a URL using the controller class name and action name. In some cases it can be handy. For example:

$url = action([IndexArticleController::class, "index"]);

If the route requires query or routes parameters, you can set it in the third argument:

$url = action([DeleteArticleController::class, "index"], ["id" => 1]);

If the controller is invokable, you can pass just its name, without the method name:

$url = action(CreateArticleController::class);

11. rescue()

The rescue() helper accepts a closure as the first argument, calls it and catches all exceptions that are thrown during the execution. For example:

rescue(function () { throw new \RuntimeException("An error occurred"); });

If you want to get information about caught exceptions, set an additional closure in the second argument:

rescue( function () { throw new \RuntimeException("An error occurred"); }, function (\Throwable $e) { //do something with the exception } );

In any case the helper will catch all exceptions and they don’t interrupt the execution of the application.

12. app() and resolve()

If dependency injection is unavailable, you can use the app() helper to get the required package. It can be used in a few different ways. You can set the service as the first argument:

use Illuminate\Contracts\Hashing\Hasher; $hasher = app(Hasher::class);

You can use the app()->make() method:

$hasher = app()->make(Hasher::class);

Or you can use the array accessing syntax:

$hasher = app()[Hasher::class];

Note, that you shouldn’t use the app()->get() method because it only returns an instance of the object when it has been created earlier.

Also you can use the resolve() helper. It is just an alias for the app() helper:

$hasher = resolve(Hasher::class);

Wrapping Up

This article has collected useful helpers for Laravel that few know about. You can find more information about each of them in the official documentation. Also, you may want to create a custom helper. You can find information about it here. What less-known helpers do you use in your projects? Tell about it in the comment section below.

Leave a Comment