xtremer360

xtremer360

Full Stack Developer at 321

Member Since 5 Years Ago

Kissimmee, FL

Experience Points
153,395
Total
Experience

1,605 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
1179
Lessons
Completed
Best Reply Awards
9
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 31
153,395 XP
Nov
29
1 week ago
Activity icon

Replied to Looking For A Better Assertion

@bobbybouwmann I know I've extended this post out, however, I'm trying to figure out I can feature test the employ method with having the check if the manager is employed. I'm starting to wonder if that's a good place for it.

<?php

namespace Tests\Feature\Admin\Manager;

use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Manager;
use Illuminate\Foundation\Testing\RefreshDatabase;

/**
 * @group managers
 * @group admins
 * @group roster
 */
class CreateManagerSuccessConditionsTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Valid parameters for request.
     *
     * @param  array $overrides
     * @return array
     */
    private function validParams($overrides = [])
    {
        return array_replace([
            'first_name' => 'John',
            'last_name' => 'Smith',
            'started_at' => now()->toDateTimeString(),
        ], $overrides);
    }

    /** @test */
    public function an_administrator_can_view_the_form_for_creating_a_manager()
    {
        $this->actAs('administrator');

        $response = $this->createRequest('manager');

        $response->assertViewIs('managers.create');
        $response->assertViewHas('manager', new Manager);
    }

    /** @test */
    public function an_administrator_can_create_a_manager()
    {
        $now = now();
        Carbon::setTestNow($now);

        $this->actAs('administrator');

        $response = $this->storeRequest('manager', $this->validParams());

        $response->assertRedirect(route('managers.index'));
        tap(Manager::first(), function ($manager) use ($now) {
            $this->assertEquals('John', $manager->first_name);
            $this->assertEquals('Smith', $manager->last_name);
        });
    }

    /** @test */
    public function an_administrator_can_employ_a_manager_during_creation()
    {
        $now = now();
        Carbon::setTestNow($now);

        $this->actAs('administrator');

        $this->storeRequest('manager', $this->validParams(['started_at' => $now->toDateTimeString()]));

        tap(Manager::first(), function ($manager) use ($now) {
            $this->assertDatabaseHas('employments', [
                'employable_id' => $manager->id,
                'employable_type' => get_class($manager),
                'started_at' => $now->toDateTimeString()
            ]);
        });
    }

    /** @test */
    public function an_administrator_can_create_a_manager_without_employing()
    {
        $now = now();
        Carbon::setTestNow($now);

        $this->actAs('administrator');

        $this->storeRequest('manager', $this->validParams(['started_at' => null]));

        tap(Manager::first(), function ($manager) use ($now) {
            $this->assertDatabaseMissing('employments', [
                'employable_id' => $manager->id,
                'employable_type' => get_class($manager),
                'started_at' => $now->toDateTimeString()
            ]);
        });
    }
}

<?php

namespace App\Http\Controllers\Managers;

use App\Models\Manager;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreManagerRequest;

class ManagersController extends Controller
{
    /**
     * Create a new manager.
     *
     * @param  \App\Http\Requests\StoreManagerRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(StoreManagerRequest $request)
    {
        $manager = Manager::create($request->except('started_at'));

        if ($request->filled('started_at')) {
            $manager->employ($request->input('started_at'));
        }

        return redirect()->route('managers.index');
    }
}

app/Models/Concerns/CanBeEmployed.php

<?php

namespace App\Models\Concerns;

use App\Models\Employment;
use App\Exceptions\CannotBeEmployedException;


trait CanBeEmployed
{
    /**
     * Get all of the employments of the model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function employments()
    {
        return $this->morphMany(Employment::class, 'employable');
    }

    /**
     * Employ a model.
     *
     * @param  Carbon|string $startedAt
     * @return bool
     */
    public function employ($startedAt = null)
    {
        if ($this->checkIsEmployed()) {
            throw new CannotBeEmployedException;
        }

        $startDate = $startedAt ?? now();
        $this->employments()->updateOrCreate(['ended_at' => null], ['started_at' => $startDate]);

        return $this->touch();
    }
}

Nov
25
2 weeks ago
Activity icon

Replied to Looking For A Better Assertion

@bobbybouwmann So you would agree with me doing the following, or is there somethign else that could even be more helpful.

/** @test */
    public function a_super_administrator_can_employ_a_manager_during_creation()
    {
        $now = now();
        Carbon::setTestNow($now);

        $this->actAs('super-administrator');

        $this->storeRequest('manager', $this->validParams(['started_at' => $now->toDateTimeString()]));

        tap(Manager::first(), function ($manager) use ($now) {
            $this->assertDatabaseHas('employments', ['employable_id' => $manager->id, 'employable_type' => get_class($manager), 'started_at' => $now->toDateTimeString()]);
        });
    }

    /** @test */
    public function a_super_administrator_can_create_a_manager_without_employing()
    {
        $now = now();
        Carbon::setTestNow($now);

        $this->actAs('super-administrator');

        $this->storeRequest('manager', $this->validParams(['started_at' => null]));

        tap(Manager::first(), function ($manager) use ($now) {
            $this->assertDatabaseMissing('employments', ['employable_id' => $manager->id, 'employable_type' => get_class($manager), 'started_at' => $now->toDateTimeString()]);
        });
    }
Activity icon

Replied to Looking For A Better Assertion

@bobbybouwmann I do cover testing that exception in other tests because that employ method can be accessed in an actual employController which is an invokable controller. With the store method the manager can't already be hired so it will never pass the checkIsEmployed if statement.

Nov
24
2 weeks ago
Activity icon

Started a new Conversation Looking For A Better Assertion

What I'm debating is assertions in the last two test methods. Currently, I have it trying to retrieve the currentEmployment but I don't have anything that specifically says currentEmployment involved in the employ method.

Does anyone have any better ideas on how I should be testing against for making sure that the employment was created correctly? I've also debated on whether or not to use the assertDatabaseHas but not sure if that's the best solution either.

This is a feature level and does in fact pass however I don't think it depicts exactly what the edge case test is describing.

<?php

namespace Tests\Feature\SuperAdmin\Managers;

use Tests\TestCase;
use App\Models\Manager;
use Illuminate\Foundation\Testing\RefreshDatabase;

/**
 * @group managers
 * @group superadmins
 * @group roster
 */
class CreateManagerSuccessConditionsTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Valid parameters for request.
     *
     * @param  array $overrides
     * @return array
     */
    private function validParams($overrides = [])
    {
        return array_replace([
            'first_name' => 'John',
            'last_name' => 'Smith',
            'started_at' => now()->toDateTimeString(),
        ], $overrides);
    }

    /** @test */
    public function a_super_administrator_can_view_the_form_for_creating_a_manager()
    {
        $this->actAs('super-administrator');

        $response = $this->createRequest('manager');

        $response->assertViewIs('managers.create');
        $response->assertViewHas('manager', new Manager);
    }

    /** @test */
    public function a_super_administrator_can_create_a_manager()
    {
        $this->actAs('super-administrator');

        $response = $this->storeRequest('manager', $this->validParams());

        $response->assertRedirect(route('managers.index'));
        tap(Manager::first(), function ($manager) {
            $this->assertEquals('John', $manager->first_name);
            $this->assertEquals('Smith', $manager->last_name);
        });
    }

    /** @test */
    public function a_super_administrator_can_employ_a_manager_during_creation()
    {
        $this->actAs('super-administrator');

        $this->storeRequest('manager', $this->validParams(['started_at' => now()->toDateTimeString()]));

        tap(Manager::first(), function ($manager) {
            $this->assertEquals(now()->toDateTimeString(), $manager->currentEmployment->started_at);
        });
    }

    /** @test */
    public function a_super_administrator_can_create_a_manager_without_employing()
    {
        $this->actAs('super-administrator');

        $this->storeRequest('manager', $this->validParams(['started_at' => null]));

        tap(Manager::first(), function ($manager) {
            $this->assertEquals(null, $manager->currentEmployment);
        });
    }
}
/**
     * Create a new manager.
     *
     * @param  \App\Http\Requests\StoreManagerRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(StoreManagerRequest $request)
    {
        $manager = Manager::create($request->except('started_at'));

        if ($request->filled('started_at')) {
            $manager->employ($request->input('started_at'));
        }

        return redirect()->route('managers.index');
    }
/**
     * Employ a model.
     *
     * @param  Carbon|string $startedAt
     * @return bool
     */
    public function employ($startedAt = null)
    {
        if ($this->checkIsEmployed()) {
            throw new CannotBeEmployedException;
        }

        $startDate = $startedAt ?? now();
        $this->employments()->updateOrCreate(['ended_at' => null], ['started_at' => $startDate]);

        return $this->touch();
    }
Oct
18
1 month ago
Activity icon

Commented on Widget Workshop

Also to add if you have to assign private properties on a class and don't want the Widget to pass along the constructor for the viewData you can add this check inside of the foreach of the buildViewData method.

if ($method->isConstructor()) {
   continue;
}
Oct
10
1 month ago
Activity icon

Started a new Conversation Blog Post And Project Sharing Attachments And Categories

I'm attempting to map out my personal blog site with the right migrations and models. I have posts that each have either one or multiple categories and attachments which can be an image or a video. I also have projects that can either have one or multiple categories as well and one or multiple attachments attached to the project.

My question is my description above with how a project and a blog post can both have multiple attachments and categories assigned to them the correct way to set up my migrations.

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    ...
    $table->timestamps();
});

Schema::create('attachments', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->morphs('attachable');
    $table->string('path');
    $table->timestamps();
});

Schema::create('projects', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->morphs('categorable');
    $table->string('name');
    $table->timestamps();
});
Oct
05
2 months ago
Activity icon

Replied to Laravel Mutator Not Working Correctly

@falloutboi Remember it will NEVER hit that if statement when you are returning the first_name property always.

Sep
25
2 months ago
Activity icon

Started a new Conversation Custom Relationship Returning Collection Instead Of Single Model

I created a custom relationship to handle situations for a polymorphic many to many relationship. My problem is if I have a model that has this trait attached and I want to grab the currentGroup they are attached to if they are it then returns a collection instead of a single model instance. I attempted to add ->first() to the end of the QB inside of the current method of the relationship class but it still returns the collection. What am I doing wrong here?

<?php

namespace App\Models\Concerns;

use App\Models\Member;
use App\Models\Group;

trait CanBeGroupMember
{
    /**
     * Get the group history the member has belonged to.
     *
     * @return App\Eloquent\Relationships\LeaveableMorphToMany
     */
    public function groupHistory()
    {
        return $this->leaveableMorphToMany(Group::class, 'member')->using(Member::class);
    }

    /**
     * Get the current group the member belongs to.
     *
     * @return App\Eloquent\Relationships\LeaveableMorphToMany
     */
    public function currentGroup()
    {
        return $this->groupHistory()->where('status', 'active')->current();
    }

    /**
     * Get the previous groups the member has belonged to.
     *
     * @return App\Eloquent\Relationships\LeaveableMorphToMany
     */
    public function previousGroups()
    {
        return $this->groupHistory()->detached();
    }
}
<?php

namespace App\Eloquent\Concerns;

use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Relations\Pivot;

trait IsLeaveableBelongsToMany
{
    /**
     * The cached copy of the currently attached pivot models.
     *
     * @var Collection
     */
    private $currentlyAttached;

    public function detach($ids = null, $touch = true)
    {
        $query = $this->newPivotQuery();
        // If associated IDs were passed to the method we will only delete those
        // associations, otherwise all of the association ties will be broken.
        // We'll return the numbers of affected rows when we do the deletes.
        if (! is_null($ids)) {
            $ids = $this->parseIds($ids);
            if (empty($ids)) {
                return 0;
            }
            $query->whereIn($this->relatedPivotKey, (array) $ids);
        }

        $results = $query->update(['left_at' => now()]);
        if ($touch) {
            $this->touchIfTouching();
        }
        return $results;
    }

    /**
     * Sync the intermediate tables with a list of IDs or collection of models.
     *
     * @param  \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array  $ids
     * @param  bool   $detaching
     * @return array
     */

    public function sync($ids, $detaching = true)
    {
        $changes = [
            'attached' => [], 'detached' => [], 'updated' => [],
        ];

        // First we need to attach any of the associated models that are not currently
        // in this joining table. We'll spin through the given IDs, checking to see
        // if they exist in the array of current ones, and if not we will insert.
        $current = $this->getCurrentlyAttachedPivots()
                        ->pluck($this->relatedPivotKey)->all();

        $detach = array_diff($current, array_keys(
            $records = $this->formatRecordsList($this->parseIds($ids))
        ));

        // Next, we will take the differences of the currents and given IDs and detach
        // all of the entities that exist in the "current" array but are not in the
        // array of the new IDs given to the method which will complete the sync.
        if ($detaching && count($detach) > 0) {
            $this->detach($detach);

            $changes['detached'] = $this->castKeys($detach);
        }

        // Now we are finally ready to attach the new records. Note that we'll disable
        // touching until after the entire operation is complete so we don't fire a
        // ton of touch operations until we are totally done syncing the records.
        $changes = array_merge(
            $changes,
            $this->attachNew($records, $current, false)
        );

        // Once we have finished attaching or detaching the records, we will see if we
        // have done any attaching or detaching, and if we have we will touch these
        // relationships if they are configured to touch on any database updates.
        if (count($changes['attached']) ||
            count($changes['updated'])) {
            $this->touchIfTouching();
        }

        return $changes;
    }

    /**
     * Get the pivot models that are currently attached.
     *
     * @return \Illuminate\Support\Collection
     */
    protected function getCurrentlyAttachedPivots()
    {
        return $this->currentlyAttached ?: $this->newPivotQuery()->whereNull('left_at')->get()->map(function ($record) {
            $class = $this->using ? $this->using : Pivot::class;

            return (new $class)->setRawAttributes((array) $record, true);
        });
    }

    protected function baseAttachRecord($id, $timed)
    {
        return Arr::add(
            parent::baseAttachRecord($id, $timed),
            'joined_at',
            now()
        );
    }

    public function current()
    {
        $this->wherePivot('left_at', null);

        return $this;
    }

    public function detached()
    {
        $this->wherePivot('left_at', '!=', null); //Laravel translates this to `IS NOT NULL`

        return $this;
    }

}

Sep
23
2 months ago
Activity icon

Replied to Unit Testing A Model

@martinbean

So do you mean I should remove the following from the model?

if (!$this->is_employed) || $this->is_retired) {
    throw new CannotBeRetiredException;
}
Activity icon

Started a new Conversation Unit Testing A Model

I'm trying to unit test my models and currently have a method that will retire a player from the system. I'm trying to find out if I should have my checks on the status of the player in the policy or in the model because it changes how I approach my unit testing for the player.

What suggestions or ideas do people have?

Policy

/**
     * Determine whether the user can retire a player.
     *
     * @param  App\Models\User  $user
     * @param  App\Models\Player  $player
     * @return bool
     */
    public function retire(User $user, Player $player)
    {
        if (!$player->is_employed || $player->is_retired) {
            return false;
        }

        return $user->isSuperAdministrator() || $user->isAdministrator();
    }

Model

/**
     * Retire a model.
     *
     * @return \App\Models\Retirement
     */
    public function retire()
    {
        if (!$this->is_employed) || $this->is_retired) {
            throw new CannotBeRetiredException;
        }

        $this->retirements()->create(['started_at' => now()]);
        $this->touch();
    }
Aug
22
3 months ago
Activity icon

Replied to Refactoring To Datatable Classes

@jlrdw No worries on the misunderstanding. Some of the references for the package have sites that I think are temporarily down because I can't access any of them.

Is there anyone that has used this package and created their own classes that extend the package datatables class and modified the class so that they can handle all of the logic in one place.

Aug
21
3 months ago
Activity icon

Replied to Refactoring To Datatable Classes

@jlrdw I've updated with my full controller method.

Activity icon

Replied to Refactoring To Datatable Classes

How would I apply a scope for this?

Activity icon

Started a new Conversation Refactoring To Datatable Classes

I'm trying to figure out how I can refactor this little bit of controller code to individual classes that can be used instead. The package I am using is Yajra Laravel Datatables package.

/**
     * View a list of users.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\DataTables\UsersDataTable  $table
     * @param  \App\Filters\UserFilters  $requestFilter
     * @return \Illuminate\View\View
     */
    public function index(Request $request, UsersDataTable $table, UserFilters $requestFilter)
    {
        $this->authorize('viewList', User::class);

        if ($request->ajax()) {
            $query = User::with('employment');
            $requestFilter->apply($query);

            return $table->eloquent($query)
                ->addColumn('action', 'users.partials.action-cell')
                ->filterColumn('name', function ($query, $keyword) {
                    $sql = "CONCAT(users.first_name, ' ', users.last_name)  like ?";
                    $query->whereRaw($sql, ["%{$keyword}%"]);
                })
                ->filterColumn('id', function ($query, $keyword) {
                    $query->where($query->qualifyColumn('id'), $keyword);
                })
                ->toJson();
        }

        return view('users.index');
    }
Aug
16
3 months ago
Activity icon

Started a new Conversation Yajra Datatables

I'm using the following package to better display a rendered table of users for my project. The problem is what I would like to do is extract the logic inside of the ajax check to a new Datatable class that extends the package's default Datatable class. The methods that I'm looking at for the class doesn't exactly line up with what I'm doing.

https://github.com/yajra/laravel-datatables

https://yajrabox.com/docs/laravel-datatables/master/editor-tutorial

public function index(IndexUserRequest $request, DataTables $table, UserFilters $requestFilter)
    {
        $this->authorize('viewList', User::class);

        if ($request->ajax()) {
            $query = User::with('employment');
            $requestFilter->apply($query);

            return $table->eloquent($query)
                ->addColumn('action', 'users.partials.action-cell')
                ->filterColumn('id', function ($query, $keyword) {
                    $query->where($query->qualifyColumn('id'), $keyword);
                })
                ->toJson();
        }

        return view('users.index');
    }
Aug
13
3 months ago
Activity icon

Replied to Filter Statuses Array

I ended up going with this in the view.

@foreach (\App\Enums\PlayerStatus::toArray() as $key => $value)
    <option value="{{ $value }}">
        {{ trans('enums.' . \App\Enums\PlayerStatus::class . '.' . constant("\App\Enums\PlayerStatus::$key")) }}
    </option>
@endforeach
Activity icon

Replied to Filter Statuses Array

I am actually using the following package.

https://github.com/mad-web/laravel-enum

What I want to do is have it loop over all of the enums defined in the PlayerStatusEnum file and display the label inside of the value of the option but then display the lang. However, I'm struggling to try and get the lang value shown for the option.

@foreach (\App\Enums\PlayerStatus::toArray() as $key => $value)
    <option value="{{ $value }}">{{ __('enums.'.\App\Enums\PlayerStatus::class.'.'.\App\Enums\PlayerStatus.'::'.$key) }}</option>
@endforeach

lang/en/enums.php

PlayerStatus::class => [
    PlayerStatus::BOOKABLE => 'Bookable',
],
Activity icon

Started a new Conversation Filter Statuses Array

Hey all I'm trying to figure out what's the best way to go for this situation. The code below is coming from a filter form that allows the user to select any possible status to filter the list of players query. So I'm wondering if it would be worth creating a method for the Player model that returns an array of statuses. These statuses are NOT stored in the database, however, each status has an associated scope inside of the Player model. Another reason why I thought it would be a good idea to create a method that returns the array of possible statuses is that when the user submits the form that can filter by the status I have a validation Rule::in() that has the array of statuses.

What are thoughts on this?

@foreach ($statuses as $status)
    <option value="only_{{ strtolower($status) }}">{{ $status }}</option>
@endforeach 

old version looks like this.

<option value="only_bookable">Bookable</option>
<option value="only_pending_introduction">Pending Introduction</option>
<option value="only_retired">Retired</option>
<option value="only_injured">Injured</option>
<option value="only_suspended">Suspended</option>
Jul
28
4 months ago
Activity icon

Replied to Trying To Sync And Update Child Models

Any ideas on this problem?

Jul
26
4 months ago
Activity icon

Replied to Trying To Sync And Update Child Models

I have made a few changes and still running into an issue.

    /**
     * Scope a query to only include current coaches.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     */
    public function scopeCurrentCoaches($query)
    {
        return $query->whereHasMorph('coaches', Coach::class, function ($query) {
            $query->whereNull('left_at');
        });
    }

    /**
     * Scope a query to only include current players.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     */
    public function scopeCurrentPlayers($query)
    {
        return $query->whereHasMorph('players', Player::class, function ($query) {
            $query->whereNull('left_at');
        });
    }
/**
     * Get all coaches that have been members of the team.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
     */
    public function coaches()
    {
        return $this->morphedByMany(Coach::class, 'member')->using(Member::class)->withPivot(['joined_at', 'left_at']);
    }

    /**
     * Get all players that have been members of the stable.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
     */
    public function players()
    {
        return $this->morphedByMany(Player::class, 'member')->using(Member::class)->withPivot(['joined_at', 'left_at']);
    }

So now I have the following.

$currentTeamCoaches = $team->currentCoaches()->get()->pluck('id');
$currentTeamPlayers = $team->currentPlayers()->get()->pluck('id');

So now I am having a problem trying to run the scope.

+exception: Symfony\Component\Debug\Exception\FatalThrowableError^ {#5387
      -originalClassName: "TypeError"
      #message: "Argument 1 passed to Illuminate\Database\Eloquent\Builder::getBelongsToRelation() must be an instance of Illuminate\Database\Eloquent\Relations\MorphTo, instance of Illuminate\Database\Eloquent\Relations\MorphToMany given, called in /Users/jeffreydavidson/Projects/Ringside/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php on line 215"`
Activity icon

Started a new Conversation Trying To Sync And Update Child Models

I'm trying to figure out how I can minimize this code block. What I'm trying to do is keep a record of all old and current coaches and players for a specific team. I am currently trying to figure out how I can utilize the updateExistingPivot correctly and the syncWithoutDetatching correctly as well.

I"m only wanting to update the players and coaches that are now referred to as former coaches and players. Would I need a whereIn()? I don't know if that can be done with a pivot?

$newTeamCoaches = $request->input('coaches');
$newTeamPlayers = $request->input('players');

$currentTeamCoaches = $team->players()->current()->get()->pluck('id');
$currentTeamPlayers = $team->coaches()->current()->get()->pluck('id');

$formerTeamCoaches = $currentTeamCoaches->diff(collect($newTeamCoaches));
$formerTeamPlayers = $currentTeamPlayers->diff(collect($newTeamPlayers));

$team->coaches()
    ->updateExistingPivot($formerTeamCoaches, ['left_at' => now()]);

$team->players()
    ->updateExistingPivot($formerTeamPlayers, ['left_at' => now()]);

$team->coaches()->syncWithoutDetaching($newTeamCoaches);
$team->players()->syncWithoutDetaching($newTeamPlayers);
public function scopeCurrent($query)
{
    return $query->whereNull('left_at');
}
Jul
08
5 months ago
Activity icon

Started a new Conversation Data Providers Are They Worth It

I am trying to decide if using data providers for my tests is the best way to go.

Below I have an example of a test where an administrator can update an inactive user to be active. I have a data provider that I can apply to this test that returns an array of two different types of administrator roles. This array of roles are roles that have the ability to perform this action.

I understand for this simple test it would be just as easy to create a new test that assures the same functionality passes for the two different admin types however this starts to get bigger as different conditions are met on whether or not the user can be activated at all.

On the other end of the spectrum, I have 20+ tests that feature endpoint testing that tests form validation fails with passing the post parameters. Those tests all say that a specific role is logged in during those tests but both types of admin roles have the same type of results.

I'm seeking advice as to if many people reach for data providers a lot with situations like this or not or if there are some better alternatives. I've heard that some people will separate out the same tests into separate directories with a directory for each role but seems like a copy and paste for the same test with one minor change. Plus when criteria changes or another role is added you'd have to go in and create an additional directory with more copied tests.

What do you all think?

/** @test */
    public function an_administrator_can_activate_an_inactive_user()
    {
        $this->actAs('administrator');
        $user = factory(User::class)->states('inactive')->create();

        $response = $this->put(route('users.activate', $user));

        $response->assertRedirect(route('users.index'));
        tap($user->fresh(), function ($user) {
            $this->assertTrue($user->is_active);
        });
    }
Jun
09
6 months ago
Activity icon

Replied to How To Order A Product Only Once In Laravel?

I think I've missed the question here. Did you include one?