2
votes

I develop this code to view Tehran time and date with php:

$fmt = new IntlDateFormatter("fa_IR@calendar=persian", IntlDateFormatter::FULL,
    IntlDateFormatter::FULL, 'Asia/Tehran', IntlDateFormatter::TRADITIONAL);

    echo "Date: " . $fmt->format(time()) . "\n";

this code works fine but, I want to use it in a function in my controller in Laravel.

Route:

Route::get('/date', [
'as' => 'date', 'uses' => 'HomeController@date'
]);

Controller :

public function date() {
    $fmt = new IntlDateFormatter("fa_IR@calendar=persian", IntlDateFormatter::FULL,
    IntlDateFormatter::FULL, 'Asia/Tehran', IntlDateFormatter::TRADITIONAL);

    echo "Date: " . $fmt->format(time()) . "\n";
}

And the result is :

Class 'App\Http\Controllers\IntlDateFormatter' not found

I know that there is not IntlDateFormatter class in Laravel but I except that use php class here. what is my mistake?

3
add more code and explanation pleaseHasan Tareque
Try to use as \IntlDateFormatterAlankar More

3 Answers

1
votes

You need to import the namespace your Class lies in.

Remember that the app\folder is PSR-4 loaded, so if for example your class is defined in a file called IntlDateFormatter.php, you need to put this file somewhere in your app\. Then in your controller you import the class:

// in your controller 
namespace App\Http\Controllers;

use App\{your class location}\IntlDateFormatter;
0
votes

Thanks for response, I forgotted to add

use IntlDateFormatter;

So the not found error solved by adding that.

0
votes

Here is an example of using custom classes in Laravel:

<?php
namespace YourProject\Services;
class IntlDateFormatter{
  public static function dateFormat(){
    /*Do your date formatting here and return desired result*/
  }
}

I asume you save this file inside app directory. Next in config/app.php inside aliases array, add

'IntlDateFormatter'     => Artisanian\Services\IntlDateFormatter::class,

This way you can easily call dateFormat function as follow:

\IntlDateFormatter::dateFormat();

Either in your controller or in your view.

I hope this help.

Good luck.