En este articulo aprenderemos a como crear helpers en Laravel 5 paso a paso.
Paso 1. Crear el helper en el directorio app/Helpers
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
class FormatTime {
public static function LongTimeFilter($date) {
if ($date == null) {
return "Sin fecha";
}
$start_date = $date;
$since_start = $start_date->diff(new \DateTime(date("Y-m-d") . " " . date("H:i:s")));
if ($since_start->y == 0) {
if ($since_start->m == 0) {
if ($since_start->d == 0) {
if ($since_start->h == 0) {
if ($since_start->i == 0) {
if ($since_start->s == 0) {
$result = $since_start->s . ' segundos';
} else {
if ($since_start->s == 1) {
$result = $since_start->s . ' segundo';
} else {
$result = $since_start->s . ' segundos';
}
}
} else {
if ($since_start->i == 1) {
$result = $since_start->i . ' minuto';
} else {
$result = $since_start->i . ' minutos';
}
}
} else {
if ($since_start->h == 1) {
$result = $since_start->h . ' hora';
} else {
$result = $since_start->h . ' horas';
}
}
} else {
if ($since_start->d == 1) {
$result = $since_start->d . ' día';
} else {
$result = $since_start->d . ' días';
}
}
} else {
if ($since_start->m == 1) {
$result = $since_start->m . ' mes';
} else {
$result = $since_start->m . ' meses';
}
}
} else {
if ($since_start->y == 1) {
$result = $since_start->y . ' año';
} else {
$result = $since_start->y . ' años';
}
}
return "Hace " . $result;
}
}
Paso 2. Crear el provider, ejecutando el comando:
php artisan make:provider FormatTimeServiceProvider
Paso 3. Incluir el método register en el provider:
public function register()
{
require_once app_path() . '/Helpers/FormatTime.php';
}
Paso 4. Entrar al directorio config/app.php y añadir el provider al array de providers:
App\Providers\FormatTimeServiceProvider::class,
Y añadir un alias de nuestro helper:
'FormatTime' => App\Helpers\FormatTime::class,
Ya podemos usar nuestro helper en cualquier parte de nuestro código, por ejemplo en una vista hariamos algo así:
{{ \FormatTime::LongTimeFilter($entrada->created_at) }}
Y con esto ya hemos aprendido a crear helpers en Laravel 5 de forma sencilla 🙂













