What is the best practice to create a custom helper function in php Laravel 5?

家住魔仙堡 提交于 2019-11-28 20:32:06
  1. Within your app/Http directory, create a helpers.php file and add your functions.
  2. Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"].
  3. Run composer dump-autoload

That should do it. :)

Since your Helper method is static you could add your helper class to config/app alias just like a Facade, like so:

'aliases' => [
    //'dateHelper'=> 'App\Helpers\DateHelper', //for Laravel 5.0
    'dateHelper'=> App\Helpers\DateHelper::class, //for Laravel 5.1
] 

Then later in your view:

{{dateHelper::dateFormat1($user->created_at)}}

However, if you are also looking for a way to do this without a helper class. You may consider using Mutators and Appends in your model:

class User extends Model{
   protected $fillable = [
     'date'
   ];

   protected $appends = [
     'date_format_two'
   ];


   public function getDateAttribute($value){
        $dt = new DateTime($value);
        return $dt->format("m/d/y"); // 10/27/2014
   }

    //date
    public function getDateFormatTwoAttribute($value){
        $dt = new DateTime($value);
        return $this->attributes['date_format_two'] = $dt->format("m, d ,y"); // 10,27,2014
    }
} 

Later you can do

$user = User::find(1);

{{$user->date}}; 
{{$user->date_format_two}}; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!