4 Steps to Create Helpers in Laravel:
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?
- 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.
- Make Code Cleaner: Helper functions help you organize your code and make it easier to understand.
- 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:
- Create a Helper File: Create a new PHP file in your
app/Helpers
directory. - Define the Function: Inside the file, write your function with a clear name and parameters.
- Make it Accessible: Use the
use
statement in your controllers or views to access the helper function.
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