Where to pass data to templates (blade files)?


In blade files, we can access data in different ways:

  • via a Controller, for example in /app/Controller/App.php:
    public static function postCategory() => {{ App::postCategory() }}
    public function postCategory() => {{ $post_category }}

  • via a file with App namespace in /app, for example in /app/categories.php:
    namespace App;
    function post_category() => {{ \App\post_category() }}

  • via a file without App namespace in /app, for example in /app/categories.php:
    function post_category() => {{ post_category() }}

What to choose? I never know where to define my functions.

Can you guide me?


The answer to this question is “whatever works best for you,” but the following are some observations based on my experience.

This is generally to be avoided; It pollutes the global namespace, increasing the likelihood that one of your function names may collide with the name of another function, leading to great lamentation, rending of garments, etc.

This avoids polluting the namespace, but it will very quickly become tiresome to type the namespace every time you need a function, and most editors and IDE’s I’ve used don’t like to consider things inside of blade brackets as PHP, so you’ll likely use nice helpful tools like autocomplete, etc. Also, you should if at all possible keep logic and function calls out of your templates: That stuff belongs in Controllers.

This is generally be best approach. It is the easiest to read and type in your views, and it helps keep your logic and templates separate. More specifically, I would use {{ $post_category }} over {{ App::postCategory() }}. If you’re structuring your controllers correctly, you should almost never need to be calling their methods in your views. If you find yourself doing that, ask yourself how you might refactor your code to avoid it.

1 Like

Thanks for your explanations, it’s very interesting!

So the best is to use functions (not static) in Controller files.

Is there a naming convention for the functions inside Controllers ?

public function postCategory() or just public function category() for example?

No, that’s up to you.

This topic was automatically closed after 42 days. New replies are no longer allowed.