7 laravel helper functions to make your life easier

laravel helper functions

Laravel provides a lot of global helper functions which are also used by the framework itself. These helpers functions can be used by us to make our work convenient. Laravel helper function also helps us to maintain code reusability by storing the most repetitive task on single global function.

There are many helpers functions for working with arrays and objects, URLs, paths, string and so on. In this article, we are going to include only 10 helper functions.

You can also create your own helper functions in laravel 5. You can find a nice article explaining the steps about creating custom helpers in this article.

1abort_if()

This new helper function was added in Laravel 5.2. Its was introduced to make the abort function prettier reducting the lines on conditional statement.

The syntax of basic usage:

The function accepts parameters as boolean, status code and message.

2abort_unless()

The function works direct opposite to abort_if() function. This will stop execution unless it satisfy certain condition.

The syntax of basic usage:

3data_get()

The function helps us to get value from array or object with dot notation. This accepts array as first argument, node names with dot notation as second and optionally default value as third parameter.

The basic usage:

4optional()

The 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.

5str_plural()

This function helps us to convert a string to plural form. It accepts a string as an argument. Optionally, it also accepts integer which defines the returning value.

6array_first()

The array_first function returns the first element of an array passing a given condition. We can also pass a third parameter which acts as default value when the condition fails.

7str_slug()

It helps to create a url friendly slug for routing. This will lower case the title and spaces are replaced by - or any other specified.

You can visit this laravel github repository for more information about how it works.

This is all for this session. Please remember that laravel provides a lot of helper functions to make our easier and fast. Be sure to check them. If you have any query regarding this article, please drop a comment below.