---
# System prepended metadata

title: '[laravel]自訂Helper'
tags: [laravel]

---

# [laravel]自訂Helper
###### tags: `laravel`

參考資料:
https://tutsforweb.com/creating-helpers-laravel/

## 新建AppHelper
app\Helpers\AppHelper.php
```php
<?php

function ttt(){
    return 'ttt';
}

```


## 修改composer.json
composer.json
```json=
{
    "name": "laravel/laravel",


    //...
    "autoload": {
    //加上這段
        "files": [
            "app/Helpers/AppHelper.php"
        ],
    //加上這段
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    //...
}
```

## 執行composer dump-autoload
```c!
$ composer dump-autoload
```

以後在AppHelper.php的所有function就可以被全域呼叫了.


---
若是將Helper寫成class也行:

```php!
<?php
class AppHelper{
  public static function ttt(){
    return 'ttt';
  }
}
```

在controller跟Model呼叫Helper class:
```php
//要加這句引用
use App\Helpers\AppHelper;

...
    AppHelper::ttt();
```

在blade中呼叫Helper class:
https://stackoverflow.com/questions/34710626/php-laravel-use-helper-class-in-all-views
```htmlmixed!
{!! App\Helpers\AppHelper::ttt() !!}
```

>若helper裡只有function不需如此麻煩,直接呼叫function name即可.

