29
loading...
This website collects cookies to deliver better user experience
dd()
, abort()
and session()
. But as your projects start to grow, you'll likely find that you'll want to add your own.helpers.php
file inside our app
folder. As a side note, this location is down to personal preference really. Another common place I've seen the file placed is inside an app/Helpers/helpers.php
file. So, it's down to you to choose a directory that you feel works best for you.helpers.php
file like so:<?php
if (! function_exists('seconds_to_hours')) {
function seconds_to_hours(int $seconds): float
{
return $seconds / 3600;
}
}
seconds_to_hours()
function registered, this would prevent us from registering our own function with the same name. To get around this, we could just simply change the name of our own function to avoid any clashes.composer.json
file so that our file is loaded at runtime on each request and is available for using. This is possible because Laravel includes the Composer class loader in the public/index.php
file.composer.json
file, you should have a section that looks like this:"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"files": [
"app/helpers.php"
],
autoload
section of your composer.json
file should now look like this:"autoload": {
"files": [
"app/helpers.php"
],
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
composer.json
file, we'll need to run the following command to dump our autload file and create a new one:composer dump-autoload
seconds_to_hours(331);
TimeServiceClass
that contained a secondsToHours()
method that did the same as our new function. If we were to use the service class in our Blade view, we might have to do something like this:{{ \App\Services\TimeService::secondsToHours(331) }}
app/helpers.php
file; some related to money, some related to time and some related to user settings. We could start by splitting those functions out into separate files such as: app/Helpers/money.php
, app/Helpers/time.php
and app/Helpers/settings.php
. This means that we can now delete our app/helpers.php
file because we don't need it anymore.composer.json
file in a similar way to before so that it nows loads our 3 new files:"autoload": {
"files": [
"app/Helpers/money.php",
"app/Helpers/settings.php",
"app/Helpers/time.php",
],
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
composer dump-autoload