Google Web Stories

4 Easy Steps to Create Helper in Laravel

4 Steps to Create Helpers in Laravel:

In Laravel, custom helper functions allow you to create reusable code that can be accessed globally throughout your website. Using custom helper functions improves efficiency and keeps your codebase clean. By using these functions, you can reduce redundancy and enhance the clarity of your code.

What are Helper Functions in Laravel?

Think of helper functions as handy tools that you can use to do common tasks quickly and easily in your Laravel projects. Laravel comes with some built-in helper functions, but you can also create your own to make your code more efficient and readable.

Why Use Helper Functions?

  1. Save Time: Instead of writing the same code over and over, you can create a helper function to do it once and reuse it whenever needed.
  2. Make Code Cleaner: Helper functions help you organize your code and make it easier to understand.
  3. Centralized Changes: If you need to change how a certain task is done, you only need to update the helper function, and the change will be reflected everywhere.

How to Create a Helper Function:

  1. Create a Helper File: Create a new PHP file in your app/Helpers directory.
  2. Define the Function: Inside the file, write your function with a clear name and parameters.
  3. Make it Accessible: Use the use statement in your controllers or views to access the helper function.
1. Create a file named “CustomHelper.php” into the app\Helpers folder and Write the below code or as per your requirements:



use App\Models\Order;
use App\Models\Review;
use App\Models\Wishlist;
use App\Models\Property;

class CustomHelper
{

public function GetBrokerName($id){
$user=User::find($id);
return $user[‘name’];
}
}

2. Now add the file link into composer.json file like:

"files": [
"app/Helpers/CustomHelper.php"
]

3. Create a file named as “CustomHelperServiceProvider.php” into app/Providers folder and Write the below code:


bind('CustomHelper', function() {
return new CustomHelper;
});
}

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{

}
}

4. Now add the provider into config/app.php like:

/*
* Other Providers...
*/
App\Providers\CustomHelperServiceProvider::class,

5. Now you can access the functions which you have written in the CustomHelper.php into xyz.blade.php like:

@php $brokerName = app('CustomHelper')->GetBrokerName($customer->broker_id); echo $brokerName; @endphp

Scroll to Top
Heating koi pond water 12 pointers.