Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 accessing custom functions in a view

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?

like image 610
RavensGate Avatar asked Feb 07 '15 11:02

RavensGate


1 Answers

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>
like image 150
Nicolas Beauvais Avatar answered Sep 29 '22 21:09

Nicolas Beauvais