Certainly! You're very close to having a working global helper—the problem is due to scoping and timing of global function definitions. In Laravel, to properly define a global helper, do not define it in service provider methods (like AppServiceProvider@boot). Instead, put it in a PHP file that is loaded before any other application logic and outside any class/method definition.
Step-by-step Solution:
1. Create a Helper File
Create a new file in your project, for example:
app/Helpers/helpers.php
Add your flash() function there:
<?php
if (! function_exists('flash')) {
function flash(): \App\Helpers\FlashHelper
{
return app('flash');
}
}
2. Register the Helper File in Composer
Edit your composer.json to autoload this file:
"autoload": {
"files": [
"app/Helpers/helpers.php"
],
// ... other autoload settings
}
Then, run:
composer dump-autoload
3. Register the FlashHelper in the Service Container
What you did in your AppServiceProvider is perfect for binding the class:
public function register()
{
$this->app->singleton('flash', fn () => new \App\Helpers\FlashHelper);
}
No need to put anything in the boot() method for this purpose.
4. Your FlashHelper Class
Your FlashHelper code is great! For completeness, make sure it's in the correct namespace/file:
File: app/Helpers/FlashHelper.php
<?php
namespace App\Helpers;
class FlashHelper
{
public function success(string $message): void
{
session()->flash('flash', [
'type' => 'success',
'message' => $message,
]);
}
public function error(string $message): void
{
session()->flash('flash', [
'type' => 'error',
'message' => $message,
]);
}
public function warning(string $message): void
{
session()->flash('flash', [
'type' => 'warning',
'message' => $message,
]);
}
public function info(string $message): void
{
session()->flash('flash', [
'type' => 'info',
'message' => $message,
]);
}
}
5. Usage
Now, anywhere in your Laravel code (controllers, views, etc), you can call:
flash()->success('Record saved successfully!');
6. Display the Flash Message in Your Blade View
In your Blade template:
@if(session('flash'))
<div class="alert alert-{{ session('flash.type') }}">
{{ session('flash.message') }}
</div>
@endif
Summary
- Define helpers in a regular PHP file, not a provider.
- Register the helper file with Composer's autoload.
- Bind your helper class in a service provider (as you did).
This matches the pattern used by many Laravel packages and is the cleanest approach.
References:
Let me know if you get stuck!