1

i have some custom function and i'm trying to use that into project, for example:

function makeText($str1, $str2){
    return $str1 . ' '. $str2;
}

and i want to use this function in view such as :

<div style='float:left;'>MakeText : {{makeText("Hello","World");}}</div>

makeText is only sample function, witch folder must be put functions method such as UF.php containes all functions and how to define this file to laravel and use it?

2 Answers 2

1

You could follow Laravel’s conventions and create a helpers.php file in your app directory. Be sure to auto-load it with Composer though:

"autoload": {
    "classmap": [
        //
    ],
    "files": [
        "app/helpers.php"
    ]
},

You can then use the function any where in your application, including views.

Sign up to request clarification or add additional context in comments.

Comments

1

Laravel gives you a few options. You can include your function definition inside of any of the files that get automatically included and achieve the result you want, such as /app/start/global.php, /bootstrap/start.php, /app/routes.php or many others. The problem with this approach is that, depending on the name of your function, there is a non-negligible likelihood that the name might conflict with one that is already taken (or may get taken later). Also, if you ever need to debug this function you will need to be able to find it later.

You can get around this issue by placing your function inside of a class, and then call that class a service. You can then inject that class into your controller via dependency injection and then pass that data to your view:

class MyService
{
    public function makeText($param1, $param2)
    {
        return $param1 . ' ' . $param2;
    }
}

class AController extends BaseController
{
    public function __construct(MyService $serv)
    {
        $this->serv = $serv;
    }

    public function aRoute()
    {
        return View::make('some.view')
            ->with('serv', $this->serv);
    }
}

And then in your view:

<div style='float:left;'>MakeText : {{ $serv->makeText("Hello","World"); }}</div>

This will help you prevent naming collisions because you can easily place MyService into any namespace that makes sense. It will also help you keep your code organized better.

Something this simple will probably not require a service provider, but as you add complexity to your project it would be an easy step to do once you need to.

Comments

Your Answer

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