José , in Laravel, create a helpers.php
file in your app
folder and load it automatically by editing composer.json
:
"autoload": {
"classmap": [ ... ],
"psr-4": { "App\": "app/"
},
"files": [
"app/helpers.php" // <---- ADICIONE AQUI
] },
Then update the project composer by executing the command:
composer dump-autoload
Example
app/helpers.php
<?php
// ************************
// Criado em 05/02/2015
// Helper com utilidades criado por Felipe D.
// ************************
/**
* Retorna data e hora.
*
* @param bool $hora Se vai retornar hora também
* @return string
*/
function getData($hora)
{
// retorna, mas poderia ser "echo", whatever
return ($hora ? date("d/m/Y H:i") : date("d/m/Y")) ;
}
app/Http/Controllers/DataController.php
<?php
namespace App\Http\Controllers;
use App\Midia;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class DataController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
// Helpers podem ser chamados de QUALQUER lugar,
// inclusive pelas views, ex: usando {{ getData(true) }}
$data = getData(true);
// ou echo ou die ou carrega view, whatever
return $data;
}
}
As I said in the comment above, Helpers
can be called ANY place, including views. Here's how to call the getData
function above within a View
(using Blade):
<div>Data / Hora: {{ getData(true) }} </div>