[英]How can I loop a Eloquent Collection in PHP Laravel?
我正在嘗試使用 Laravel Jetstream Teams 進行自動注冊。 由於 Jetstreams 需要一個“個人團隊”,而我的應用程序要求用戶與特定團隊分開,我找到了一種方法來attach
用戶attach
到團隊,然后switchTeam
團隊,以便他們當前的團隊像他們的個人團隊一樣加載。
為此,我禁用了手動注冊,禁用了創建新團隊的功能並禁用了人們離開團隊的功能。 這節省了從 Jetsteam 中刪除個人團隊的時間。
這樣做時,由於應用程序自動創建用戶(從電子表格),我還需要將團隊分配給該用戶。 我試圖遍歷每個Team::all
但響應是一個數組,因此我的array_filter
由於對象被作為參數給出而返回錯誤。
protected function assignTeam(User $user)
{
$team = array_filter(Team::all(), function(Team $team) {
// teamToAssign dervies from Spreadsheet data
return strtoupper($team->name) === strtoupper($this->teamToAssign);
});
if(!empty($team)) // User error can exist in data
{
Team::find($team->id)->users()->attach($user, ['role' => 'participant']);
User::find($user->id)->switchTeam(Team::find($team->id));
return;
}
// TODO: Deal with user error
}
任何人都可以闡明我如何解決這個問題嗎? 我是 Laravel 的新手,不確定是否有更好的方法來循環遍歷Eloquent Collections
。 提前謝謝了。
你可以做
$teams = Team::all()->toArray(); // this will convert collection to array
// or
Team::all()->each(function (Team $team) { // this will allow you to loop through the collection
// TODO ...
});
Team::all()->filter(function (Team $team) { // this will allow you to filter unwanted instances
// TODO ...
});
有關 Laravel Collection Helper 方法的更多信息,請點擊此處
您可以使用方法過濾器來過濾您的集合,如以下鏈接所示:
https://laravel.com/docs/8.x/collections#method-filter
在處理集合時,您還可以在這里找到很多方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.