Reputation: 58662
I've a class with a bunch of Date Helpers functions in it. I stored it at app\Helpers\DateHelper.php
<?php
namespace App;
use DateTime;
class DateHelper {
public static function day_ago($date) {
if ($date) {
$ts = time() - strtotime(str_replace("-","/", $date ));
if($ts>31536000) $val = round($ts/31536000,0).' year';
else if($ts>2419200) $val = round($ts/2419200,0).' month';
else if($ts>604800) $val = round($ts/604800,0).' week';
else if($ts>86400) $val = round($ts/86400,0).' day';
else if($ts>3600) $val = round($ts/3600,0).' hour';
else if($ts>60) $val = round($ts/60,0).' minute';
else $val = $ts.' second';
if($val>1) $val .= 's';
return $val;
}
}
}
"autoload": {
"classmap": [
"database",
"app/Helpers"
],
"psr-4": {
"App\\": "app/"
},
"files": ["app/Helper.php"]
},
Then, I run composer install
I got
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
> php artisan clear-compiled
> php artisan optimize
Generating optimized class loader
Then, I added to the alias array like this:
'DateHelper' => 'app\Helpers\DateHelper',
Then, I used it:
{{ DateHelper::day_ago($n->created_at) }}
Now, I keep getting Class 'DateHelper' not found
.
How do I properly add it ?
Upvotes: 3
Views: 1360
Reputation: 33068
Your alias is wrong. The alias is meant to be the fully qualified class name with namespace, not the directory it's in.
'DateHelper' => 'App\DateHelper',
I would suggest following PSR-4 standards. It would save time and minimize confusion.
Additionally, so this doesn't happen again, it would be better to use syntax like the following...
'DateHelper' => App\DateHelper::class,
That way, you can be absolutely sure the class exists.
Upvotes: 3
Reputation: 7303
A typical example for a helper file in Laravel:
helper.php
file in your app
directory. helper.php
file in your composer.json
file. composer dump-autoload
If you are creating a directory for the helper files, then namespace the helperfiles.
"autoload": {
"classmap": [
"database",
],
"psr-4": {
"App\\": "app/",
"Helpers\\": "app/helpers/" //This is if you are using the directory
},
"files": ["helper.php"] //This is if it's just a php file.
},
i.e :
//app/helpers/helperClass.php
<?php namespace Helpers;
class helperClass{
public function showDate()
{
//return
}
}
In your controller, when you use the helper function, import the class.
i.e:
use Helpers/helperClass;
//If you've creates an alias for this, use it here.
use helperClass; //(This is from the config/app.php file)
If it's a view, use it like: {{ \Helpers\helperClass::showDate() }}
Upvotes: 1