将多个模型的属性存储到 laravel 中的单个数组

Storing attributes of a multiple models, to single array in laravel

我的控制器中有以下 eloquent,

$getJobs=JobTitle::where('department_id',DepartmentUser::where('user_id', $user->id)->first()->department_id)->get();

这让我关注 collection

Illuminate\Database\Eloquent\Collection {#2970 ▼
  #items: array:3 [▼
    0 => App\JobTitle {#2967 ▶}
    1 => App\JobTitle {#2968 ▶}
    2 => App\JobTitle {#2962 ▶}
  ]
  #escapeWhenCastingToString: false
}

一个模型元素看起来像这样

1 => App\JobTitle {#2968 ▼
      #connection: "mysql"
      #table: "job_titles"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #escapeWhenCastingToString: false
      #attributes: array:9 [▼
        "id" => 898
        "title" => "driver"
        "company_id" => 635
        "department_id" => 252
        "created_by" => null
        "created_at" => "2022-04-20 05:30:38"
        "updated_at" => "2022-04-20 05:30:38"
        "deleted_at" => null
        "archived_at" => null
      ]
      #original: array:9 [▶]
      #changes: []
      #casts: array:2 [▶]
      #classCastCache: []
      #attributeCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: array:3 [▶]
      #guarded: array:1 [▶]
      +archives: true
      #forceDeleting: false
    }

现在我想将所有职位 (title) 值存储到单个数组中

"title" => "driver"

在上述场景中,我有数组元素,因此我需要将所有三个相应的职位存储到一个数组中...

$jobs = ['driver', 'chef', 'engineer'];

我尝试添加一个 foreach,但出现以下错误,

@foreach ($getJobs as $getJob)
              dd ($getJob->title);
            @endforeach

ParseError syntax error, unexpected token "foreach"

实现此目标的最佳方法是什么?

您可以简单地循环 $getJobs 并在如下数组中收集标题名称:

<?php

$getJobs = JobTitle::where('department_id',DepartmentUser::where('user_id', $user->id)->first()->department_id)->get();

$titles = [];

foreach($getJobs as $job){
   $titles[] = $job->title;
}

dd($titles);