简体   繁体   中英

How can I call a function of a helper class in a view - Laravel 5.8?

I have a helper class DateHelper

在此输入图像描述

I have one fn in there

public static function getAgo($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;


    }

}

I want to use it in my view like this

{{ DateHelper::getAgo($log->createdAt) }}

I kept getting

Class 'DateHelper' not found (View: ...

I tried to include it on top of my index.blade.php like this

<?php use App\DateHelper; ?>

Can someone please help me ?

You can add an alias in your config/app.php :

'aliases' => [
    // ...
    'DateHelper' => App\DateHelper::class,
],

Then in your view you can simply do:

{{ DateHelper::getAgo($log->created_at); }}

If a use statement doesn't work in the view, you can always use inline namespacing:

{{ \App\DateHelper::getAgo($log->created_at) }}

Ensure the class is in the correct namespace and has the correct class/filename and you should be good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM