---
# System prepended metadata

title: PHP & Laravel 升級
tags: [backend, PHP]

---

# PHP & Laravel 升級
###### tags: `PHP` `backend`

### 目標
- PHP 7.2 -> ^8.1
- laravel 6.2 -> ^8.0

### 環境

- ubuntu 18.04

### 前置作業

為了預防直接正式機硬改會出問題，先用docker模擬相同的環境，測試到沒問題才在正式機實作


### PHP 升級

1. 先新增PHP的PPA
```shell
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php -y
```
2. 進行apt套件的升級
```shell
sudo apt update -y && sudo apt upgrade -y
```
3. 安裝PHP8.1版本所需的套件
```shell
sudo apt install php8.1 php8.1-gd php8.1-fpm php8.1-cli php8.1-curl php8.1-zip php8.1-mysql php8.1-mbstring php8.1-xml php8.1-bcmath
```

4. 更改nginx fastcgi的使用路徑
```shell
sudo vim /etc/nginx/sites-available/some-host.com
```
移動到檔案中的段落
```shell
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
```
改成
```shell
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
```
5. 重啟nginx和php-fpm
```shell
sudo systemctl restart nginx && sudo systemctl restart php8.1-fpm
```

### laravel 升級

這會遇到比較多的問題，因為有很多相容性套件也一併需要升級，不過官網寫得蠻清楚，照著改還蠻順利的。

1. 由於要升級到laravel 8，需要composer 2以上的api，所以若是composer 版本為1則進行升級
```shell
composer self-update
```

2. 對照官網提供的升級指南(附在參考資料中)，將composer.json改寫，以下提供幾個範例
    ```json
    "require": {
        "php": "^8.1",
        "dingo/api": "^2",
        "doctrine/dbal": "^3.6",
        "fideloper/proxy": "^4.0",
        "google/recaptcha": "^1.2",
        "laravel/framework": "^8.0",
        "laravel/socialite": "^5.0",
        "laravel/tinker": "^2.0",
        "maatwebsite/excel": "^3.1",
        "spatie/laravel-permission": "^4.0",
        "sunspikes/clamav-validator": "^2.1",
        "tymon/jwt-auth": "^1.0.0"
    },
    "require-dev": {
        "facade/ignition": "^2.0",
        "fakerphp/faker": "^1.9.1",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.0"
    },
    ```
3. 將原先的vendor砍了`rm -rf vendor`(我不確定不砍能不能成功)
4. `sudo composer update` 結束


#### 問題排解

- 遇到 `Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255]`

    這在升級laravel 7的時候會碰到，需要對`app/Exception/Handler.php`做修改
    修改很簡單，只要把原先`Exception`的物件改成`Throwable`即可
    ```php
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render($request, Throwable $exception)
    {
        return parent::render($request, $exception);
    }
    ```


### 結論

這次升級比我想像中的快很多，過程中也沒碰到什麼太災難的問題，整體來說，先用docker測試再去實作會令人安心上不少。



### 參考資料
- [Quick Guide - Upgrading to Laravel 9 and PHP 8.1](https://dev.to/adam_crampton/quick-guide-upgrading-to-laravel-9-and-php-81-2dbh)
- [laravel 8官網升級導引](https://laravel.com/docs/8.x/upgrade)