Best Practices for Custom Helpers in Laravel 5

后端 未结 20 2297
暖寄归人
暖寄归人 2020-11-22 06:40

I would like to create helper functions to avoid repeating code between views in Laravel 5:

view.blade.php

Foo Formated text: {{ fo

20条回答
  •  故里飘歌
    2020-11-22 07:29

    There are some great answers here but i think this is the simplest. In Laravel 5.4 (and prob earlier versions too) you can create a class somewhere convenient for you, eg App/Libraries/Helper.php

    class Helper() {
        public function uppercasePara($str) {
            return '

    ' .strtoupper($str). '

    ; } }

    Then you can simply call it in your Blade template like this:

    @inject('helper', \App\Libraries\Helper)
    {{ $helper->drawTimeSelector() }}
    

    If you don't want to use @inject then just make the 'uppercasePara' function as static and embed the call in your Blade template like this:

    {{ \App\Libraries\Helper::drawTimeSelector() }}
    

    No need for aliases. Laravel resolves the concrete class automatically.

提交回复
热议问题