Where to put a helper function? I have a utility / helper function that simply converts DB timestamp to users local time which will be used in various places.
Where should one put such code?
public function toLocalTime($timestamp){
$timezone = \Auth::user()->timezone;
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC')->setTimezone($timezone);
return Carbon::parse($date)->format('F dS Y, g:i:s A');
}
So it can be called from any Controller / API Resource.
I suppose a trait but just curious what the best place would be to place such code.
Thanks,
usually people create a helper file app/Helpers/helpers.php, and load it in composer.json file
"autoload": {
"files": ["app/Helpers/functions.php"]
}
composer du
Thanks for the quick reply!
What would a quick example of what that file might look like based on my code snip?
Basically as it is?
// functions.php file
use Auth;
use Carbon\Carbon;
function toLocalTime($timestamp){
$timezone = \Auth::user()->timezone;
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC')->setTimezone($timezone);
return Carbon::parse($date)->format('F dS Y, g:i:s A');
}
something like this, it doesn't have to be a class, just a simple file with a lot of functions, you could check how people from Laravel did
https://github.com/laravel/framework/blob/7.x/src/Illuminate/Foundation/helpers.php
Thanks, Thats basically what I am trying.
Only 1 last question is how to call it. From what I read in the docs "helpers" are for blade templates, where this is always going to be called from a Controller / API Resource, never in a blade.
Thanks again, much appreciated!
@movepixels that's why I mentioned composer.json file, you have to load this file, after you do that - all those function will be available globally in your project, in blade/controllers/resources, everywhere
"autoload": {
"files": ["app/Helpers/functions.php"]
}
after you add this to your composer.json file, you have to run composer dump-autoload, or composer du
I have added that to the composer file / compose du.
Just to the part of how do i call that function now.
???->toLocalTime($this->updated_at);
<?php
use Auth;
use Carbon\Carbon;
function toLocalTime($timestamp){
$timezone = \Auth::user()->timezone;
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC')->setTimezone($timezone);
return Carbon::parse($date)->format('F dS Y, g:i:s A');
}
Composer du
Results in -> [ErrorException]
The use statement with non-compound name 'Auth' has no effect
Ok this works!
<?php
use Carbon\Carbon;
function toLocalTime($timestamp){
$timezone = \Auth::user()->timezone;
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC')->setTimezone($timezone);
return Carbon::parse($date)->format('F dS Y, g:i:s A');
}
Called anywhere with
$local = toLocalTime($this->updated_at);
Thanks for the assistance!
Greatly appreciated :)
Please sign in or create an account to participate in this conversation.