Laravel has some pretty awesome helpers. You've probably used them several times throughout your application. For instance to get the current URL you can use the url()
helper, or to return a user back to the previous page you can use the back()
helper.
These helpers really are... Well, helpful. But, there are some special conditions when I need my own custom global helpers and implementing this functionality is much easier than you might think. Let's walk through it.
Open up your applications app/Providers/AppServiceProvider.php
which looks like this:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
}
We are going to create a new function inside of the AppServiceProvider called loadHelpers()
which wil load all of our PHP helper files.
protected function loadHelpers()
{
foreach (glob(__DIR__.'/../Helpers/*.php') as $filename) {
require_once $filename;
}
}
Then we'll call the loadHelpers()
function inside of our register()
method. So our final app/Providers/AppServiceProvider.php
file will look like the following:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->loadHelpers();
}
protected function loadHelpers()
{
foreach (glob(__DIR__.'/../Helpers/*.php') as $filename) {
require_once $filename;
}
}
}
Great! That's most of the heavy lifting. Next we need to create a new helper. We can create a new file located at app/Helpers/string-helpers.php
Any PHP file that you add to the
app/Helpers/
folder will automatically be loaded. So, you can feel free to organize your helper files however you'd like. FYI, you will not have aHelpers
folder by default, you will need to create it.
<?php
if ( !function_exists('greeting') )
{
function greeting($name){
return 'Howdy ' . $name;
}
}
The helper file above creates a new function called greeting()
which takes in a name and returns a string. Pretty simple stuff, but this is just an example of a helper function
That's it! We now have a new helper function called greeting()
. Here's an example of it's use inside of the routes/web.php
Route::get('hello', function(){
echo greeting('John');
});
When we visit the above route we will call our greeting()
helper and we will get the output of Howdy John on our screen.
This was just a simple example of creating a helper function; however, I'm sure that your functions will be much cooler than the one above. Hope this article helps.
Happy coding :D
Comments (0)