Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have

the default created_at date keep printing out as an MySQL format : 2015-06-12 09:01:26. I wanted to print it as my own way like 12/2/2017, and other formats in the future.


I created

a file called DataHelper.php and store it at /app/Helpers/DateHelper.php - and it looks like this

<?php

namespace App\Helpers;

class DateHelper {

    public static function dateFormat1($date) {
        if ($date) {
            $dt = new DateTime($date);

        return $dt->format("m/d/y"); // 10/27/2014
      }
   }
}

I want

to be able to called it in my blade view like

DateHelper::dateFormat1($user->created_at)

I'm not sure what to do next.

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

like image 354
code-8 Avatar asked Jun 12 '15 13:06

code-8


People also ask

What is helper function in Laravel?

What is a Helper Function? A helper function usually comes in handy if you want to add a feature to your Laravel application that can be used at multiple locations within your controllers, views, or model files. These functions can be considered as global functions.


2 Answers

  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. :)

like image 74
code-8 Avatar answered Oct 19 '22 14:10

code-8


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}}; 
like image 13
Emeka Mbah Avatar answered Oct 19 '22 14:10

Emeka Mbah