Jaquarh
Jaquarh

Reputation: 6673

How can I loop a Eloquent Collection in PHP Laravel?

I am trying to use the Laravel Jetstream Teams for automated registration. Due to Jetstreams requiring a 'personal team' and my application requiring users to be apart of specific teams, I found a way around it to attach a user to a team and then switchTeam so their current team is loaded like their personal team would.

For this to work, I disabled manual registration, disabled the ability to create new teams and disabled the ability for people to leave teams. This saves the time of having to remove the personal teams out of Jetsteam.

On doing this, since the application automatically creates users (from a spreadsheet), I need to also assign the team to that user. I am trying to loop through each Team::all but the response is an array thus my array_filter is returning an error due to an object being given as the parameter.

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
}

Can anyone perhaps shine light on how I can approach this? I'm new to Laravel and unsure if there is a better method to loop through Eloquent Collections. Many thanks in advance.

Upvotes: 0

Views: 1670

Answers (2)

Ziad Adeela
Ziad Adeela

Reputation: 496

You can use the method filter to filter your collection as in the following link:

https://laravel.com/docs/8.x/collections#method-filter

You can find here also a lot of methods when dealing with collections

Upvotes: 1

mmabdelgawad
mmabdelgawad

Reputation: 2545

You can do

$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 ...

});

For more information about Laravel Collection Helper Methods Here

Upvotes: 1

Related Questions