0

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.

1
  • 2
    How about trying Laravel Collections filter method. Also, might want to use the first() method as well to get only one result Commented Oct 31, 2020 at 13:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.