Adding a helper file in Laravel

James Mills > Laravel > Adding a helper file in Laravel

Every now and then you will probably find yourself in the need to use a custom function in your Laravel application. I cannot think of one project which I have worked on where I haven’t needed to add a quick and easy custom function.

Our controllers don’t contain actions outside of the 7 resource actions (index, create, store, show, edit, update, destroy). For more details on this principle, review the docs or watch Cruddy by Design

So, what happens if you need a custom function here? You could refactor this out into its own class in a Helpers namespace, I have done this before too. However, sometimes you just want to use a function.

Example use case

One example we have is where we run a number of subdomains off our main application. We have app, api, admin and search. We store the root URL in the .env file as APP_URL=https://intentmatch.dev and then we have a helper function which we use to get the URL throughout our application.

<?php
if (!function_exists('applicationUrl')) {
/**
* Will return the fully qualified domain name for the correct environment etc
*
* @param string $sub_domain
* @param string $path
* @return string
*/
function applicationUrl($sub_domain = 'app', $path = null)
{
$related_link = parse_url(config('app.url'));
$final_url = $related_link['scheme'] . '://' . $sub_domain . '.' . $related_link['host'];
if (!is_null($path)) {
$final_url .= '/' . ltrim($path, '/');
}
return $final_url;
}
}

We keep functions like this in App/Helpers/HelperFunctions.php and we often have helper classes in this namespace too. The HelperFunctions.php file is dedicated to quick and easy functions.

Include in Composer.json

Your helper classes will load automatically because they are in the main Application namespace but you need to include the Helper file individually in your composer.json file so that it gets found. To do this just update your composer.json file and add the files round the autoload key.

"autoload": {
     "classmap": [
         "database
     ],
     "psr-4": {
         "App\": "app/"
     },
     "files": [
         "app/Helpers/HelperFunctions.php"
     ]
 }

Leave a Reply

Your email address will not be published. Required fields are marked *