I would like to make it possible to add custom functions that I can use within a view. For instance I want to make it possible to call a function that will display data. I do not want to do this from the controller as I'm trying to make this as customisable as possible.
Apparently someone sent me information on possible creating a service provider and injecting this into the base of the app?
You can create a custom helper function directly in bootstrap/app.php
but there are better ways.
If you just want simple functions like Laravel's helpers, create a helpers.php
file in your app directory and require it in your bootstrap/app.php
file, then you can create all the custom function you want in it, for example:
<?php
function coolText($text) {
return 'Cool ' . $text;
}
and call it in your view:
<div>{{ coolText($someVar) }}</div>
For something more advanced you can create a Helper class in your app directory, bind it in your AppServiceProvider.php
and add any method of your choice in this class.
app/Helpers.php
<?php namespace Helpers;
class Helpers
{
public function coolText($text)
{
return 'Cool ' . $text;
}
}
You can inject this class in your view or create a Facade for this class to access it in your view:
<div>{{ Helpers::coolText($someVar) }}</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With