6

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?

4

1 Answer 1

12

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>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Tried this and it works first time. You sir are a legend.
If your problem is resolved, mark this question as acceptable using the check symbol, It will mark your post as answered.
If my function is a get method i.e:, public function getReviews() how could I retrieve it in my view..??!!
please add the static keyword like public static function coolText

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.