Joseph, in Laravel, create a file helpers.php
in your briefcase app
and automatically load it by editing the composer.json
:
"autoload": {
"classmap": [ ... ],
"psr-4": { "App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADICIONE AQUI
] },
Then update the project’s Poser by running 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 by views. See how to call the function getData
above within a View
(using Blade):
<div>Data / Hora: {{ getData(true) }} </div>
Hello Felipe, thank you so much for your help. But a question continues, where will I call these functions that are in the helper file? I create accessors and mutators in the database model to change the string or send my string to the view and access these functions in the view itself or access the functions by the controller and send the string to the view already modified? I hope I was clear.
– José Badger
@Josébadger, I updated my answer. Now there is no mistake! haha
– Felipe Douradinho
Got it, man, thank you so much.
– José Badger