I would like to create helper functions to avoid repeating code between views in Laravel 5:
view.blade.php
Foo Formated text: {{ fo
Create custom helpers’ directory: First create Helpers directory in app directory. Create hlper class definition: Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code
namespace App\Helpers; defines the Helpers namespace under App namespace. class MyFuncs {…} defines the helper class MyFuncs. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string
Helpers service provide class
Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.
Run the following artisan command:
php artisan make:provider HelperServiceProvider
The file will be created in /app/Providers/HelperServiceProvider.php
Open /app/Providers/HelperServiceProvider.php
Add the following code:
HERE,
namespace App\Providers; defines the namespace provider
use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
public function boot(){…} bootstraps the application service
public function register(){…} is the function that loads the helpers
foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.
We now need to register the HelperServiceProvider and create an alias for our helpers.
Open /config/app.php
file
Locate the providers array variable
Add the following line
App\Providers\HelperServiceProvider::class,
Locate the aliases array variable
Add the following line
'MyFuncs' => App\Helpers\MyFuncs::class,
Save the changes Using our custom helper
We will create a route that will call our custom helper function Open /app/routes.php
Add the following route definition
Route::get('/func', function () {
return MyFuncs::full_name("John","Doe");
});
HERE,
return MyFuncs::full_name("John","Doe"); calls the static function full_name in MyFuncs class