Custom Helper Functions in Laravel

In creating our PHP String Helper Functions, we were able to define four useful string helper functions to use in our projects. Recall we had a split_string() function, a find_between() function, a find_all() function, and a delete() function. They’re really cool and helpful for quick and dirty string manipulation. Let’s say we want to make use of these functions in Laravel, how can we do that? Well that is exactly what we’ll find out in this tutorial, starting now!


1. Create a Class to contain your functions

First up we need to turn our collection of functions into a class. This way we can simply autoload the class and we’ll have access to the functions we want right away. Here is the class file for this example. We’ll call it Stringhelpers.php and the name of the class will also be Stringhelpers.

Note! We did make a few small changes to this class as compared to its function based file from the prior lesson. The constants have been removed, and any calls to functions within the same class are now prefixed with the self:: operator. This is to tell PHP that we want to use a function that is a part of this class. Otherwise, if we try to use the functions in our code without first using self:: we will get an error.


2. Create a libraries folder

In the app folder of your Laravel project, we can create a libraries folder so we have a place to hold our library code. Take the code from step 1 and save it to a file named Stringhelpers.php in this folder. In our folder that would be C:wampwwwblogapplibraries since in our earlier adventures we had already created a blog application.


3. Configure the global.php

Edit start/global.php and add app_path().'/libraries' to the ClassLoader::addDirectories array.
That file is in C:wampwwwblogappstart and should look like this once complete:


4. Edit composer.json

We’ll need to edit composer.json to add "app/libraries" to the autoload array. You can learn all about autoloading with composer in our examination of Composer. In the root directory C:wampwwwblog of your Laravel application you will find the composer.json file. Open this file up and add "app/libraries" to the autoload array. It might look something like this upon completion:


5. Run composer dump

If you are using windows and have composer installed, the easiest way to do this is to right click on your Laravel project folder and select ‘Use Composer Here‘. This will open up a command prompt in your Laravel project directory and you can now just type ‘composer dump‘. You’ll see it generate some autoload files for you just like this:

composer dump


6. Try out your new functionality!

Now comes the fun part, we get to test our code in a small application! First, we’ll just dump some basic logic into a closure in the routes.php file so we can quickly see if the functions are working. The routes file will look like this:

This says that when we visit http://you.rock/stringhelpers, we’ll initialize a basic string which will contain the text We like to program in PHP and we like to use the Laravel Framework! Then we’ll call our helper functions via static methods and var_dump the result to the screen. Let’s do it!

http://you.rock/stringhelpers

Well look at that! The functions are working! That is really cool, but let’s clean things up just a little bit by creating a view with a form so that we have a place where we can easily submit text and operate on that text using our new functions.

Create the Form Using Blade

Let’s create a form so that we can collect a string, and accept any arguments that our functions might need to run. Place the following code into a file named stringhelpers.blade.php and place it into the stringhelpers folder in the views directory:

Update Our Routes File

Now we’ll need to update our routes.php file. Before, we were simply returning some data to the screen when hitting the route http://you.rock/stringhelpers so we could see if our newly included library of helper functions were working. Now we are going to change it up. When we hit http://you.rock/stringhelpers, we now want to make a view using the code from above. This part of the routes.php file will now look like so to accomplish this:

Easy! Just for grins, let’s hit that route now!

string helper laravel blade form

b,b,b,b,b BOO YEAH! That form is styling baby! Now, I know we are chomping at the bit to put some data into that form and test it out, but don’t go hitting that Get Data button just yet – you may incite the wrath and fury of Laravel’s Exception handling class since we haven’t yet added any logic to the routes.php file in order to handle the form submission. Let’s go ahead and do that now.

There is a fair amount of logic happening here, yet it is pretty straightforward. Let’s walk through it:

  • We know when a form is submitted in Laravel, it uses the post method. As such, we use Route::post for this route.
  • Next we use the Input Façade to capture all of the form input and place that data in variables we can use.
  • Now we have to determine which helper function will run. We’ll do this in a switch statement.
  • Finally, we’ll use the View Façade to make a view, and pass the resulting $data to it, based on which branch of the switch statement runs.

Excellent! We’re almost ready to rock and roll, but we need a view for the result. Go ahead and put the following snippet into a file called result.blade.php:

Ok Friends, its Go Time! Let’s test out the functions via our form one at a time.

find_between()

Here you can see we input a fairly lengthy string, we then use the word string as a start point, functions as an end point, and include these in the return value.
find between submit include
find between result include


For this example we use the word string as a start point, functions as an end point, and exclude these in the return value.
find between submit exclude
find between submit exclude

find_all()

For the remaining tests, we’ll use the same start and end point of string and functions, while leaving the last field blank since we do not need that parameter for these function calls.
find all submit
find all result

delete()

delete submit
delete result

Conclusion

Laravel has an incredible amount of useful tools and built in helper functions as well. We hope to dive into the native helpers of Laravel soon. When we visit the official laravel documentation, we see a plethora of helper functions for Arrays, Paths, Strings, URLs, as well as several Miscellaneous helpers. There are times however when we might want to create our own helpers, or import existing libraries we are familiar with. In this lesson we took action to create our own laravel custom helper functions. It’s a fairly straightforward process where we create the class file we want, place it into a libraries folder within the app folder, configure the global.php file, add the libraries folder to the compser.json file, and then run composer dump. Running composer dump generates the autoload files automatically and once we complete these steps, we can start using these custom helper functions in Laravel right away. The helper functions here are fairly basic, but the outline or process to follow will work for any size or type of helper class that you may want to load into laravel. This makes for a very flexible development architecture that is super fun to use!