You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub Action中laravel.yml无法切换api目录致composer.json找不到

解决GitHub Action中无法切换到Laravel api目录的问题

问题原因

GitHub Actions的每个run步骤都是独立的shell进程,单独执行cd api只会改变当前步骤的工作目录,后续步骤会自动回到仓库根目录,导致依赖安装、环境配置等操作找不到api目录下的文件。

解决方案

有两种可靠的方式解决这个问题:

方式1:使用working-directory指定工作目录

可以为整个job或者单个步骤设置working-directory,让步骤直接在目标目录下执行命令。

修改后的laravel.yml示例:

name: Laravel

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  laravel-tests:
    runs-on: ubuntu-latest
    # 为整个job指定默认工作目录为api
    working-directory: api

    steps:
    - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
      with:
        php-version: '8.2'
    - uses: actions/checkout@v4
    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"
    - name: Install Dependencies
      run: composer install
    - name: Generate key
      run: php artisan key:generate
    - name: Directory Permissions
      run: chmod -R 777 storage bootstrap/cache
    - name: Create Database
      run: |
        mysql -h localhost -u root --password=root -e "CREATE DATABASE laravel_test;"
        php artisan migrate --seed --env=testing
    - name: Execute tests (Unit and Feature tests) via PHPUnit/Pest
      env:
        DB_CONNECTION: mysql
        DB_HOST: localhost
        DB_PORT: 3306
        DB_DATABASE: laravel_test
        DB_USERNAME: root
        DB_PASSWORD: root
      run: php artisan test

如果不想为整个job设置,也可以给单个步骤添加working-directory,比如:

- name: Copy .env
  working-directory: api
  run: php -r "file_exists('.env') || copy('.env.example', '.env');"

方式2:将多命令合并到同一个run步骤

把需要在api目录执行的命令用&&连接,或者用多行命令格式,确保所有命令在同一个shell进程中执行:

- name: Setup Laravel environment and install dependencies
  run: |
    cd api
    php -r "file_exists('.env') || copy('.env.example', '.env');"
    composer install
    php artisan key:generate
    chmod -R 777 storage bootstrap/cache

注意事项

  • 不要单独用run: cd api这种步骤,它不会对后续步骤产生任何影响
  • 使用working-directory时,actions/checkout步骤不需要修改,因为它默认会把代码拉取到仓库根目录,后续步骤会自动切换到指定的子目录

内容的提问来源于stack exchange,提问作者Asjid Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:13:43