Custom Helper Functions in Laravel

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.

class Stringhelpers {
// string helper functions

// Splits a string on a given setpoint, then returns what is before
// or after the setpoint. You can include or exclude the setpoint.
public static function split_string($string, $setpoint, $beforaft, $incorexc) {
	$lowercasestring = strtolower ( $string );
	$marker = strtolower ( $setpoint );
	if ($beforaft == 'before') {  // Return text before the setpoint
		if ($incorexc == 'exclude') {
			// Return text without the setpoint
			$split_here = strpos ( $lowercasestring, $marker );
		} else {
			// Return text and include the setpoint
			$split_here = strpos ( $lowercasestring, $marker ) + strlen ( $marker );
		$result_string = substr ( $string, 0, $split_here );
	} else {  // Return text after the setpoint
		if ($incorexc == 'exclude') {
			// Return text without the setpoint
			$split_here = strpos ( $lowercasestring, $marker ) + strlen ( $marker );
		} else {
			// Return text and include the setpoint
			$split_here = strpos ( $lowercasestring, $marker );
		$result_string = substr ( $string, $split_here, strlen ( $string ) );
	return $result_string;

// Finds a string between a given start and end point. You can include
// or exclude the start and end point
public static function find_between($string, $start, $end, $incorexc) {
	$temp = self::split_string ( $string, $start, 'after', $incorexc );
	return self::split_string ( $temp, $end, 'before', $incorexc );

// Uses a regular expression to find everything between a start
// and end point.
public static function find_all($string, $start, $end) {
	preg_match_all ( "($start(.*)$end)siU", $string, $matching_data );
	return $matching_data [0];

// Uses str_replace to remove any unwanted substrings in a string
// Includes the start and end
public static function delete($string, $start, $end) {
	// Get array of things that should be deleted from the input string
	$delete_array = self::find_all ( $string, $start, $end );
	// delete each occurrence of each array element from string;
	for($i = 0; $i < count ( $delete_array ); $i ++)
		$string = str_replace ( $delete_array, "", $string );
	return $string;

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:

	"classmap": [

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:

Route::get('/stringhelpers', function() {
	$string = 'We like to program in PHP and we like to use the Laravel Framework!';

	var_dump(Stringhelpers::split_string($string, 'like', 'after', 'include'));

	var_dump(Stringhelpers::split_string($string, 'program', 'before', 'exclude'));

	var_dump(Stringhelpers::find_between($string, 'like', 'program', 'include'));

	var_dump(Stringhelpers::find_between($string, 'like', 'program', 'exclude'));

	var_dump(Stringhelpers::find_all($string, 'we', 'to'));

	var_dump(Stringhelpers::delete($string, 'we', 'to'));

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!


string 'We like to program in PHP and we like to use the Laravel Framework!' (length=67)

string 'like to program in PHP and we like to use the Laravel Framework!' (length=64)

string 'We like to ' (length=11)

string 'like to program' (length=15)

string ' to ' (length=4)

array (size=2)
  0 => string 'We like to' (length=10)
  1 => string 'we like to' (length=10)

string ' program in PHP and  use the Laravel Framework!' (length=47)

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:



String Helper Library

{{ Form::open( ) }}
{{ Form::label('string', 'String: ') }} {{ Form::textarea('string', '', array('class' => 'form-control')) }}
{{ Form::label('start', 'Start: ') }} {{ Form::text('start', '', array('class' => 'form-control')) }}
{{ Form::label('end', 'End: ') }} {{ Form::text('end', '', array('class' => 'form-control')) }}
{{ Form::label('incorexc', 'Include or Exclude Markers (only for the find_between() method):') }} {{ Form::text('incorexc', '', array('class' => 'form-control')) }}
{{ Form::label('function', 'Run this function') }} {{ Form::select('function', array('fb' => 'find_between()', 'fa' => 'find_all()', 'd' => 'delete()')) }}
{{ Form::submit('Get Data', array('class' => 'btn btn-info')) }}
{{ Form::close() }}

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:

Route::get('/stringhelpers', function() {
	return View::make('stringhelpers/stringhelpers');

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.

Route::post('/stringhelpers', function() {
	$string = Input::get('string');
	$start = Input::get('start');
	$end = Input::get('end');
	$incorex = Input::get('incorexc');
	$function = Input::get('function');
	switch ($function) {
    case 'fb':
        $data['result'] = Stringhelpers::find_between($string, $start, $end, $incorex);
		$data['function'] = 'find_between()';
		$data['description'] = 'This function finds a string between a given start and end point.';
		$data['string'] = $string;
		$data['start'] = $start;
		$data['end'] = $end;
		return View::make('stringhelpers/result', $data);
    case 'fa':
        $data['result'] = Stringhelpers::find_all($string, $start, $end);
		$data['function'] = 'find_all()';
		$data['description'] = 'This function uses a regular expression to find everything between a start and end point.';
		$data['string'] = $string;
		$data['start'] = $start;
		$data['end'] = $end;
		return View::make('stringhelpers/result', $data);
    case 'd':
        $data['result'] = Stringhelpers::delete($string, $start, $end);
		$data['function'] = 'delete()';
		$data['description'] = 'This function uses str_replace to remove any unwanted substrings within in a string.';
		$data['string'] = $string;
		$data['start'] = $start;
		$data['end'] = $end;
		return View::make('stringhelpers/result', $data);

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:



String Helper Library

You just ran the {{ $function }} function on the string:

{{ $string }}.

{{ $description }}

The start point was {{ $start }} while the end point was {{ $end }}, and the result of this operation @if (is_array($result)) are the sub strings:

@else is the substring:

@endif @if (is_array($result)) @foreach ($result as $r) {{ $r }}
@endforeach @else {{ $result }} @endif @stop

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


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


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 submit
delete result


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!