xtremer360

xtremer360

Full Stack Developer at 321

Kissimmee, FL

Member Since 4 Years Ago

Experience Points 130,925
Experience
Level
Lessons Completed 989
Lessons
Completed
Best Reply Awards 8
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

13 Dec
5 days ago

xtremer360 left a reply on Video On Model Property Testing

@talinon Thank you for your response as I have watched that series before however that doesn't answer provide insight as to what other devs do.

xtremer360 left a reply on Video On Model Property Testing

I've seen it done more than once but that helps. I've talked to a few people that are against because in their opinion it is testing the framework. To me, if it's not apart of the framework its not testing the framework. I think it is testing the parts of the application that you are constructing.

Can anyone else give their insight on this?

xtremer360 started a new conversation Video On Model Property Testing

At one point I saw a video here on Laracasts that shows Jeffrey Way writing a test for a property on a model. Does anyone know which video it was? The reason, why I'm asking, is that I'm having a discussion about doing such tests and would like to use it as a reference.

06 Dec
1 week ago

xtremer360 left a reply on Add Playing Time To Episode List?

This would be considered under Requests category.

05 Dec
1 week ago

xtremer360 started a new conversation Multiple Situations For Same Action

I have a form that will create a new team. When creating the team it can include an array of two players or the user can select two players from a multiselection dropdown. Is this ideal or should it be rethought how to handle this action?

03 Dec
2 weeks ago

xtremer360 left a reply on Modifying Form Data From Request

@snapey How would you do that?

xtremer360 left a reply on Modifying Form Data From Request

This is what I'm currently working on inside of a Staff model.

    {
        $baseData = ['started_at' => $this->started_at];
        dd($data);
        foreach ($data as $patientData) {
            $this->patients()->create(array_merge($patientData, $baseData), ['joined_on' => Carbon::now()]);
        }

        dd($this->patients);

        return $this;
    }```

xtremer360 left a reply on Modifying Form Data From Request

Right I've already validated the data. The problem is the field in my db is called height which is the total inches.

xtremer360 left a reply on Modifying Form Data From Request

What data is being validated? At the point of trying to calculate the height would have its data already validated. The feet and inches post values.

xtremer360 left a reply on Modifying Form Data From Request

I've heard that its best to not modify the request inside of model events and/or observers.

xtremer360 started a new conversation Modifying Form Data From Request

I've been told all types of possible solutions for this problem and haven't come to which direction I want to go. The following are suggestions have been made.

  • Validation Request (Feel that this problem isn't validating data)
  • Middlware (Manipulating post data like TrimStrings does.
  • A Normalizer class (Don't feel like adding another layer in my application at this time is the best way to go.

Situation

A have a form that you can add multiple patients at the same time. A user has stats like height but in the form the fields are feet and inches. What I'm wanting to do is before it saves the patients to the DB then to convert those values in the request to a height property that gets saved to the DB

Any opinions that can be discussed about this?

29 Nov
2 weeks ago

xtremer360 left a reply on Validation In Controller

@primordial I don't disagree with your statement however if you only have a couple of fields why create a new file just to move validation to a new file. Validation is acceptable to also keep in the controller but should be the first few lines in a controller method before any other code is executed.

22 Nov
3 weeks ago

xtremer360 left a reply on Form Validation In Select Box

@sanjayacloud Please provide us with more than "but it's not work" what type of data are you sending to the validator. At the top of the controller method that you are sending your post data to you can do dd(request()->all()) to show us what you are submitting with your form.

16 Nov
1 month ago

xtremer360 left a reply on Black Friday 2018 Not Working

@fiiine Where did you get this year's coupon from?

21 Sep
2 months ago

xtremer360 left a reply on Look Up Table For Use In A Seed File

@D9705996 I don't believe that will help me. I'm trying to set a value for each of the rows for the match types.

xtremer360 started a new conversation Look Up Table For Use In A Seed File

I have the following Eloquent call to my database that retrieves 10-12 rows. What I need to do for the purposes of a seeder is assign a value (int 1-100) to each of those rows so that I can declare the chance of one type being used more than the others. So as you can see from this snippet currently in my seed file it will just grab one of the types from the database however I want to give it a look up table to be able to say which types are more likely to be used than the others.

$match = $event->matches()->save(factory(Match::class)->create([
    'match_type_id' => MatchType::inRandomOrder()->first()->id,
]));
private function chance(int $percent)
{
    return rand(0, 100) < $percent;
}
13 Sep
3 months ago

xtremer360 left a reply on TravisCI Build DB Connection Times Out

Anyone have any further ideas on this?

12 Sep
3 months ago

xtremer360 started a new conversation Class Based Model Factories With States

I have the following two tests. One tests the length of how long wrestlers won championships and the other tests current champions (not lost) and past (lost) championships. If you wondering about the Fascade Factory I got it from the following link.

https://tighten.co/blog/tidy-up-your-tests-with-class-based-model-factories

I'm trying to figure out what I can do to the ChampionshipFactory class so that it can accept states for the championship. In the link I provided it shows how to add states however I have a use case of having states of current and past where current has a won_on date that would need to be the set based on the title's introduced_at field. Then the lost_on would be a time after the title was won. So I'm trying to figure out how I can get BOTH tests to pass.

/** @test */
    public function it_can_get_the_champion_with_the_longest_title_reign()
    {
        $wrestlerA = factory(Wrestler::class)->create();
        $wrestlerB = factory(Wrestler::class)->create();
        $wrestlerC = factory(Wrestler::class)->create();
        $title = factory(Title::class)->create();

        ChampionshipFactory::forWrestler($wrestlerA)->forTitle($title)->wonOn(Carbon::parse('2018-01-01'))->lostOn(Carbon::parse('2018-01-10'))->create();
        ChampionshipFactory::forWrestler($wrestlerB)->forTitle($title)->wonOn(Carbon::parse('2018-01-10'))->lostOn(Carbon::parse('2018-01-19'))->create();
        ChampionshipFactory::forWrestler($wrestlerC)->forTitle($title)->wonOn(Carbon::parse('2018-01-19'))->lostOn(Carbon::parse('2018-01-20'))->create();

        $champions = $this->repository->longestTitleReigns($title);

        $this->assertTrue($champions->contains($wrestlerA));
        $this->assertTrue($champions->contains($wrestlerB));
    }
/** @test */
    public function current_titles_held_returns_a_collection_of_active_titles()
    {
        $wrestler = factory(Wrestler::class)->create();
        $currentChampionshipA = ChampionshipFactory::states('current')->forWrestler($wrestler)->create();
        $currentChampionshipB = ChampionshipFactory::states('current')->forWrestler($wrestler)->create();
        $pastChampionship = ChampionshipFactory::states('past')->forWrestler($wrestler)->create();

        $currentTitlesHeld = $wrestler->currentTitlesHeld;

        $this->assertTrue($currentTitlesHeld->contains('id', $currentChampionshipA->title_id));
        $this->assertTrue($currentTitlesHeld->contains('id', $currentChampionshipB->title_id));
        $this->assertFalse($currentTitlesHeld->contains('id', $pastChampionship->title_id));
    }
<?php

use Carbon\Carbon;
use App\Models\Title;
use App\Models\Wrestler;
use App\Models\Championship;

class ChampionshipFactory
{
    private $wrestler;
    private $title = null;
    private $wonOn = null;
    private $lostOn = null;
    private $titleDefenses = 0;
    private $states = [];

    public function __construct()
    {
        $this->resetProperties();
    }

    public function states($states)
    {
        $this->states = $states;

        return $this;
    }

    public function create()
    {
        if (is_null($this->title)) {
            $this->title = factory(Title::class)->create();
            $this->wonOn = $this->title->introduced_at->copy()->addMonth();
        } elseif (!is_null($this->title) && is_null($this->wonOn)) {
            if ($this->title->champions()->exists()) {
                $dateLastChampionWon = $this->title->fresh()->currentChampion->pivot->won_on;
                $dateOfTitleChange = $dateLastChampionWon->copy()->addMonth();
                $this->title->fresh()->currentChampion->loseTitle($this->title, $dateOfTitleChange);
                $this->wonOn = $dateOfTitleChange;
            } else {
                $this->wonOn = $this->title->introduced_at->copy()->addMonth();
            }
        }

        $champion = factory(Championship::class)->states($this->states)->create([
            'wrestler_id' => $this->wrestler->id ?? factory(Wrestler::class)->create()->id,
            'title_id' => $this->title->id,
            'won_on' => $this->wonOn,
            'lost_on' => $this->lostOn,
            'successful_defenses' => $this->titleDefenses,
        ]);

        $this->resetProperties();

        return $champion;
    }

    public function forWrestler(Wrestler $wrestler)
    {
        $this->wrestler = $wrestler;

        return $this;
    }

    public function forTitle(Title $title)
    {
        $this->title = $title;

        return $this;
    }

    public function wonOn(Carbon $start)
    {
        $this->wonOn = $start;

        return $this;
    }

    public function lostOn(Carbon $end)
    {
        $this->lostOn = $end;

        return $this;
    }

    public function withSuccessfulTitleDefenses($count)
    {
        $this->titleDefenses = $count;

        return $this;
    }

    public function resetProperties()
    {
        if (!is_null($this->wrestler)) {
            $this->wrestler = null;
        }

        if (!is_null($this->title)) {
            $this->title = null;
        }

        if ($this->titleDefenses != 0) {
            $this->titleDefenses = 0;
        }

        if (! is_null($this->wonOn)) {
            $this->wonOn = null;
        }

        if (! is_null($this->lostOn)) {
            $this->lostOn = null;
        }
    }
}

11 Sep
3 months ago

xtremer360 left a reply on TravisCI Build DB Connection Times Out

Does anyone see anything that I have done wrong?

xtremer360 left a reply on TravisCI Build DB Connection Times Out

It appears no matter what I do I continue to get the following error.

1) Tests\Feature\Event\AddEventTest::users_who_have_permission_can_view_the_add_event_page
Illuminate\Database\QueryException: SQLSTATE[HY000] [2002] Connection timed out (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

.env.travis

APP_ENV=testing
APP_KEY=
APP_DEBUG=true

DB_CONNECTION=testing
DB_TESTING_HOST=127.0.0.1
DB_PORT=
DB_TESTING_DATABASE=ringside_testing
DB_TESTING_USERNAME=root
DB_TESTING_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync

phpunit.xml

<env name="DB_CONNECTION" value="testing"/>

.travis.yml

# Required to run your project under the correct environment.
language: php

# Versions of PHP you want your project run with.
php:
  - 7.1

services:
  - mysql  

# Commands to be run before your environment runs.
before_script:
  - cp .env.travis .env
  - mysql -e 'CREATE DATABASE ringside_testing;'
  - composer self-update
  - composer install --no-interaction
  - php artisan key:generate
  - php artisan migrate 

script:
  - vendor/bin/phpunit

cache:
  directories:
    - vendor  

config/database.php

'testing' => [
            'driver' => 'mysql',
            'host' => env('DB_TESTING_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_TESTING_DATABASE', 'forge'),
            'username' => env('DB_TESTING_USERNAME', 'forge'),
            'password' => env('DB_TESTING_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'InnoDB',
        ],

xtremer360 left a reply on TravisCI Build DB Connection Times Out

@pardeepkumar Thank you for your response, however as an aside do you know and can explain why I am receiving this error when it gets to my testsuite.

xtremer360 left a reply on TravisCI Build DB Connection Times Out

I have edited my original post to include more information about the problem.

10 Sep
3 months ago

xtremer360 started a new conversation TravisCI Build DB Connection Times Out

I'm trying to figure out why when I run my CI Build it says that my connection to the database times out.

The command "php artisan key:generate" exited with 0.
31.27s$ vendor/bin/phpunit
PHPUnit Pretty Result Printer 0.19.14 by Codedungeon and contributors.
==> Configuration:~/build/me/app/vendor/codedungeon/phpunit-result-printer/phpunit-printer.yml
PHPUnit 7.3.5 by Sebastian Bergmann and contributors.
 ==> Tests\Feature\Module\MyTest⚈
Time: 31.12 seconds, Memory: 24.00MB
There was 1 error:
1) Tests\Feature\Module\Test::my_test_method
Illuminate\Database\QueryException: SQLSTATE[HY000] [2002] Connection timed out (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

Caused by
Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000] [2002] Connection timed out
09 Sep
3 months ago
08 Sep
3 months ago

xtremer360 started a new conversation Getting Rid Of Call To Collect Helper Method.

Any ideas on what I can do so that I don't have to wrap values for $winners, $losers, and the assertion calls in a collect helper method?

/** @test */
    public function winners_and_losers_can_be_separated_based_off_decision_of_match()
    {
        $match = $this->createStandardMatch();
        $winners = collect($match->groupedWrestlersBySide()->first()->modelKeys());
        $losers = collect($match->wrestlers->modelKeys())->diff($winners);

        $response = $this->actingAs($this->authorizedUser)
                        ->from(route('results.edit', ['event' => $match->event->id]))
                        ->patch(route('results.update', ['event' => $match->event->id]), $this->validParams([
                            'matches' => [
                                [
                                    'winners' => $winners,
                                ],
                            ],
                        ]));

        tap($match->fresh(), function ($match) use ($response, $winners, $losers) {
            $this->assertEquals(collect($match->winners->modelKeys()), $winners);
            $this->assertEquals(collect($match->losers->modelKeys()), $losers);
        });
    }
12 Aug
4 months ago

xtremer360 started a new conversation Rephrasing Test.

Any suggestions on how to improve on the naming of the variables in this test or maybe I need to re-write the assertion. Problem is a championship consists of a wrestler and a title. The records in the database of a wrestler holding a title are referred to as a championship. But I'd like to figure out what I can do so that it makes more sense that the champion loses the title. A champion is a wrestler who holds the title. So a wrestler is a wrestler unless he has a title then he's a champion but the record of a wrestler and title is a championship. Hopefully, that makes sense.

/** @test */
    public function a_champion_can_lose_a_title()
    {
        $championship = factory(Championship::class)->create();

        $championship->loseTitle(Carbon::now());

        $this->assertNotNull($championship->fresh()->lost_on);
    }
20 Jul
4 months ago

xtremer360 left a reply on Testing Collections

Right. After trying to work with this some more it still appears to not have a better solution. So I'm still keeping it open. Are there any further ideas?

xtremer360 left a reply on Retrieving Biggest Date Difference Between Rows

Those are both excellent suggestions. I debated about this and for readability I ended up going a different route.

public function longestTitleReign(Title $title)
{
        $maxDateDiff = Champion::selectRaw('MAX(DATEDIFF(IFNULL(lost_on, NOW()), won_on)) AS diff')->value('diff');

        return Champion::with('wrestler')
            ->select('champions.lost_on', 'champions.won_on', 'wrestler_id')
            ->where('title_id', $title->id)
            ->whereRaw("DATEDIFF(IFNULL(lost_on, NOW()), won_on) = {$maxDateDiff}")
            ->get();
}
19 Jul
4 months ago

xtremer360 started a new conversation Retrieving Biggest Date Difference Between Rows

I'm trying to figure out how to structure my query so that in a table where I have 2 date fields. I want to get the records that have the greatest difference between both dates. If date #2 does not have a date then use the current date with Carbon::today or NOW() if need be.

So fields are the won_on date and lost_on date.

public function longestTitleReign(Title $title)
{
        return Champion::with('wrestler')
            ->select('champions.lost_on', 'champions.won_on', 'wrestler_id')
            ->where('title_id', $title->id)
            ->orderByTimeAsChampion('desc')
            ->get();
}
public function scopeOrderByTimeAsChampion(Builder $query, $direction = 'asc')
{
        return $query->orderByRaw('DATEDIFF(lost_on, NOW()) ' . $direction);
}
17 Jul
5 months ago

xtremer360 left a reply on Testing Collections

@JarekTkaczyk That is a great example. However what I'm testing is what is returned is managers that have been fired. There's nothing testing that pastManagers are the ones that have been fired.

xtremer360 left a reply on Testing Collections

I have a feeling it has to do with the hireManager and fireManager methods, they reload the currentManagers relationship each time.

xtremer360 left a reply on Help Me With Testing

@almokhtar_br Did you do this at the top of your test file?

use App\Post;

xtremer360 left a reply on Help Me With Testing

@almokhtar_br Can you show us your Post factory that you created?

xtremer360 left a reply on Testing Collections

So for some reason this is further of what is going on.

$currentManagers = $wrestler->currentManagers()->withPivot(['hired_on', 'fired_on'])->get();
dd($currentManagers->pluck('id'));

Gives me...

Illuminate\Support\Collection {#1264
  #items: array:2 [
    0 => 1
    1 => 2
  ]
}
$currentManagers = $wrestler->currentManagers;
dd($currentManagers->pluck('id'));

Gives me..

Illuminate\Support\Collection {#1303
  #items: array:3 [
    0 => 1
    1 => 2
    2 => 3
  ]
}

xtremer360 left a reply on Using "route Middleware" And "controller Middleware" Together

@Krunch They will both fire twice. Were you trying to apply the same middleware to a route and in the controller?

If its the same middleware then you should only need to choose route level or controller level.

xtremer360 left a reply on Testing Collections

@lostdreamer_nl

This is from a trait. That the Wrestler class uses.

<?php

namespace App\Traits;

use App\Exceptions\WrestlerAlreadyHasManagerException;
use App\Exceptions\WrestlerNotHaveHiredManagerException;

trait HasManagers
{
    abstract public function managers();

    /**
     * Checks to see if the wrestler has past managers.
     *
     * @return bool
     */
    public function hasPastManagers()
    {
        return $this->pastManagers->isNotEmpty();
    }

    /**
     * Returns all the past managers for a wrestler.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function pastManagers()
    {
        return $this->managers()->whereNotNull('fired_on')->withPivot('fired_on');
    }

    /**
     * Checks to see if the wrestler has any current managers.
     *
     * @return bool
     */
    public function hasCurrentManagers()
    {
        return $this->currentManagers->isNotEmpty();
    }

    /**
     * Checks to see if the wrestler has a specific manager.
     *
     * @return bool
     */
    public function hasManager($manager)
    {
        $this->load('currentManagers');

        return $this->currentManagers->contains($manager);
    }

    /**
     * Returns the wrestler's current managers.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function currentManagers()
    {
        return $this->managers()->whereNull('fired_on')->withPivot('fired_on');
    }

    /**
     * A wrestler hires a given manager.
     *
     * @param \App\Models\Manager $manager
     * @return bool
     */
    public function hireManager($manager, $date)
    {
        if ($this->hasManager($manager)) {
            throw new WrestlerAlreadyHasManagerException;
        }

        return $this->managers()->attach($manager->id, ['hired_on' => $date]);
    }

    /**
     * A wrestler fires a given manager.
     *
     * @param \App\Models\Manager $manager
     * @return bool
     */
    public function fireManager($manager, $date)
    {
        if (! $this->hasManager($manager)) {
            throw new WrestlerNotHaveHiredManagerException;
        }

        return $this->managers()->updateExistingPivot($manager->id, ['fired_on' => $date]);
    }
}

xtremer360 left a reply on Testing Collections

@lostdreamer_nl it still produces the same result for me. The problem is that the pastManager in the first test isn't getting fired. Therefore it still shows up in the currentManagers collection.

16 Jul
5 months ago

xtremer360 started a new conversation Testing Collections

For the following tests the bottom test all passes however in the first test it says that the last assertion does not pass saying that it should be True so I'm trying to understand what I'm doing wrong.

/** @test */
    public function it_can_retrieve_a_wrestlers_current_managers()
    {
        $wrestler = factory(Wrestler::class)->create();
        $currentManagerA = ManagerFactory::forWrestler($wrestler)->hiredOn(Carbon::today()->subMonths(5))->create();
        $currentManagerB = ManagerFactory::forWrestler($wrestler)->hiredOn(Carbon::today()->subMonths(2))->create();
        $pastManager = ManagerFactory::forWrestler($wrestler)->hiredOn(Carbon::today()->subWeeks(2))->firedOn(Carbon::yesterday())->create();

        $currentManagers = $wrestler->currentManagers;

        $this->assertTrue($currentManagers->contains($currentManagerA));
        $this->assertTrue($currentManagers->contains($currentManagerB));
        $this->assertFalse($currentManagers->contains($pastManager));
    }

    /** @test */
    public function it_can_retrieve_a_wrestlers_past_managers()
    {
        $wrestler = factory(Wrestler::class)->create();
        $pastManagerA = ManagerFactory::forWrestler($wrestler)->hiredOn(Carbon::today()->subMonths(5))->firedOn(Carbon::today()->subMonths(3))->create();
        $pastManagerB = ManagerFactory::forWrestler($wrestler)->hiredOn(Carbon::today()->subMonths(2))->firedOn(Carbon::today()->subWeeks(3))->create();
        $currentManager = ManagerFactory::forWrestler($wrestler)->hiredOn(Carbon::yesterday())->create();

        $pastManagers = $wrestler->pastManagers;

        $this->assertTrue($pastManagers->contains($pastManagerA));
        $this->assertTrue($pastManagers->contains($pastManagerB));
        $this->assertFalse($pastManagers->contains($currentManager));
    }
<?php

use App\Models\Manager;
use App\Models\Wrestler;
use Carbon\Carbon;

class ManagerFactory
{
    public $wrestler = null;
    public $hiredOn = null;
    public $firedOn = null;

    public function __construct()
    {
        $this->resetProperties();
    }

    public function create()
    {
        $manager = factory(Manager::class)->create([
            'hired_at' => $this->hiredOn->subWeeks(2)
        ]);

        $this->wrestler->hireManager($manager, $this->hiredOn);
        // dd($this->firedOn);

        if (! is_null($this->firedOn)) {
            $this->wrestler->fireManager($manager, $this->firedOn);
        }

        $this->resetProperties();

        return $manager;
    }

    public function forWrestler(Wrestler $wrestler)
    {
        $this->wrestler = $wrestler;

        return $this;
    }

    public function hiredOn(Carbon $date)
    {
        $this->hiredOn = $date;

        return $this;
    }

    public function firedOn(Carbon $date)
    {
        $this->firedOn = $date;

        return $this;
    }

    public function resetProperties()
    {
        if (! is_null($this->wrestler)) {
            $this->wrestler = null;
        }

        if (! is_null($this->hiredOn)) {
            $this->hiredOn = null;
        }

        if (! is_null($this->firedOn)) {
            $this->firedOn = null;
        }
    }
}

10 Jul
5 months ago

xtremer360 left a reply on Loading A Relationship Collection

Any further ideas from anyone that might know.

09 Jul
5 months ago

xtremer360 left a reply on Loading A Relationship Collection

@Braunson If I replace relationLoaded with whenLoaded it says whenLoaded does not exist for the query builder. I found the method in the documentation and I am using 5.6 however I don't see why it would say it doesn't exist.

xtremer360 started a new conversation Loading A Relationship Collection

I'm trying to test that a collection of past events are loaded to be shown in the view for a venue. As of right now with the code blocks below regardless if the first line of the show method is commented OR not the test passes. Should this be a concern for me?

/**
* Display the specified venue.
*
* @param  Venue $venue
* @return \Illuminate\Http\Response
*/
public function show(Venue $venue)
{
    // $venue->load('pastEvents');

    return response()->view('venues.show', ['venue' => $venue]);
}
 /** @test */
public function venues_past_events_are_eager_loaded_for_venue_page()
{
    $response = $this->actingAs($this->authorizedUser)
                                     ->get(route('venues.show', $this->venue->id));

    $this->assertTrue($response->data('venue')->relationLoaded('pastEvents'));
}

venue.show

@foreach($venue->pastEvents as $event)
@endforeach
08 Jul
5 months ago

xtremer360 left a reply on Improving Names For Test File

Any suggestions here?

xtremer360 started a new conversation Improving Names For Test File

Any suggestions on the naming of my test cases or how I can refactor my tests. I'm also trying to figure out how to modify the a_title_match_with_no_champion_can_crown_a_champion_depending_on_match_decision and a_title_match_with_a_set_champion_that_wins_a_title_match_keeps_the_title_and_increases_successful_defensesbecause of trying to figure out the set up of the MatchFactory methods to help ease in the test.

<?php

namespace Tests\Feature\Event;

use Tests\TestCase;
use App\Models\Wrestler;
use App\Models\Event;
use App\Models\MatchType;
use App\Models\MatchDecision;
use App\Models\Title;
use App\Models\Champion;
use MatchFactory;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UpdateEventMatchesWithResultsTest extends TestCase
{
    use RefreshDatabase;

    private $event;
    private $match;
    private $matchtype;
    private $response;

    public function setUp()
    {
        parent::setUp();

        $this->setupAuthorizedUser(['edit-event-results', 'update-event-results']);

        $this->event = factory(Event::class)->create();
        $this->matchtype = factory(MatchType::class)->create(['number_of_sides' => 2, 'total_competitors' => 2]);
        $this->match = MatchFactory::create(['event_id' => $this->event->id, 'match_number' => 1, 'match_type_id' => $this->matchtype->id], factory(Wrestler::class, 2)->create());
    }

    private function validParams($overrides = [])
    {
        return array_replace_recursive([
            'matches' => [
                [
                    'match_decision_id' => 1,
                    'winner_id' => 1,
                    'result' => 'Donec sed odio dui. Cras mattis consectetur purus sit amet fermentum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.'
                ]
            ]
        ], $overrides);
    }

    private function assertFormError($field)
    {
        $this->response->assertStatus(302);
        $this->response->assertRedirect(route('results.edit', ['event' => $this->event->id]));
        $this->response->assertSessionHasErrors($field);
    }

    /** @test */
    public function users_who_have_permission_can_view_the_event_results_page()
    {
        $response = $this->actingAs($this->authorizedUser)
                        ->get(route('results.edit', ['event' => $this->event->id]));

        $event = $this->event;

        $response->assertSuccessful();
        $response->assertViewIs('events.results');
        $response->assertViewHas('event', function ($viewEvent) use ($event) {
            return $viewEvent->id === $event->id;
        });
    }

    /** @test */
    public function users_who_dont_have_permission_cannot_view_the_edit_event_results_page()
    {
        $response = $this->actingAs($this->unauthorizedUser)
                        ->get(route('results.edit', ['event' => $this->event->id]));

        $response->assertStatus(403);
    }

    /** @test */
    public function guests_cannot_view_the_edit_event_results_page()
    {
        $response = $this->get(route('results.edit', ['event' => $this->event->id]));

        $response->assertStatus(302);
        $response->assertRedirect(route('login'));
    }

    /** @test */
    public function users_who_have_permission_can_update_a_regular_match_with_a_result()
    {
        $response = $this->actingAs($this->authorizedUser)
                        ->from(route('results.edit', ['event' => $this->event->id]))
                        ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                            'matches' => [
                                [
                                    'match_decision_id' => 1,
                                    'winner_id' => $this->event->matches->first()->wrestlers->first()->id,
                                    'result' => 'Maecenas faucibus mollis interdum. Etiam porta sem malesuada magna mollis euismod.',
                                ]
                            ]
                        ]));

        $response->assertRedirect(route('events.index'));
    }

    /** @test */
    public function winners_and_losers_can_be_separated_based_off_result_of_match()
    {
        $response = $this->actingAs($this->authorizedUser)
                        ->from(route('results.edit', ['event' => $this->event->id]))
                        ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                            'matches' => [
                                [
                                    'match_decision_id' => 1,
                                    'winner_id' => $this->event->matches->first()->wrestlers->first()->id,
                                    'result' => 'Maecenas faucibus mollis interdum. Etiam porta sem malesuada magna mollis euismod.',
                                ]
                            ]
                        ]));

        tap($this->event->matches->first()->fresh(), function ($match) use ($response) {
            $this->assertTrue($match->wrestlers->contains('id', $match->winner_id));
            $this->assertFalse($match->losers->contains('id', $match->winner_id));
            $this->assertTrue(
                $match->losers->keyBy('id')->has(
                    $match->wrestlers->except($match->winner_id)->modelKeys()
                )
            );
            $this->assertEquals('Maecenas faucibus mollis interdum. Etiam porta sem malesuada magna mollis euismod.', $match->result);
        });
    }

    /** @test */
    public function a_title_match_with_no_champion_can_crown_a_champion_depending_on_match_decision()
    {
        $event = factory(Event::class)->create();
        $match = MatchFactory::createTitleMatchWithNoChampion(['event_id' => $event->id, 'match_type_id' => $this->matchtype->id]);

        $response = $this->actingAs($this->authorizedUser)
                        ->from(route('results.edit', ['event' => $event->id]))
                        ->patch(route('results.update', ['event' => $event->id]), $this->validParams([
                            'matches' => [
                                [
                                    'match_decision_id' => MatchDecision::titleCanBeWonBySlug()->first()->id,
                                    'winner_id' => $event->matches->first()->wrestlers->first()->id,
                                ]
                            ]
                        ]));

        tap($event->matches->first()->fresh(), function ($match) use ($response) {
            $match->titles->each(function ($title, $key) use ($match) {
                $this->assertEquals($match->winner_id, $title->currentChampion->wrestler_id);
            });
        });
    }

    /** @test */
    public function a_title_match_with_a_set_champion_that_wins_a_title_match_keeps_the_title_and_increases_successful_defenses()
    {
        $event = factory(Event::class)->create(['date' => '2018-04-27 19:00:00']);
        $title = factory(Title::class)->create(['introduced_at' => $event->date->subMonths(5)]);
        $champion = factory(Champion::class)->create(['title_id' => $title->id, 'wrestler_id' => factory(Wrestler::class)->create(['hired_at' => $event->date->subMonths(4)])]);

        $match = MatchFactory::createTitleMatchWithChampion(
                            ['event_id' => $event->id, 'match_type_id' => $this->matchtype->id],
                            [$title],
                            [$champion->wrestler, factory(Wrestler::class)->create(['hired_at' => $event->date->subWeeks(2)])]
                        );

        $response = $this->actingAs($this->authorizedUser)
                        ->from(route('results.edit', ['event' => $event->id]))
                        ->patch(route('results.update', ['event' => $event->id]), $this->validParams([
                            'matches' => [
                                [
                                    'match_decision_id' => MatchDecision::titleCanBeWonBySlug()->first()->id,
                                    'winner_id' => $champion->wrestler->id,
                                ]
                            ]
                        ]));

        tap($event->matches->first()->fresh(), function ($match) use ($response) {
            $match->titles->each(function ($title, $key) use ($match) {
                $this->assertEquals($match->winner_id, $title->currentChampion->wrestler_id);
                $this->assertEquals(1, $title->currentChampion->successful_defenses);
            });
        });
    }

    /** @test */
    public function matches_must_be_an_array()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => 'a-string-not-an-array'
                            ]));

        $this->assertFormError('matches');
    }

    /** @test */
    public function it_fails_if_invalid_number_of_match_results_sent()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => $this->event->matches->times(3)->toArray(),
                            ]));

        $this->assertFormError('matches');
    }

    /** @test */
    public function each_match_decision_is_required()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'match_decision_id' => '',
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.match_decision_id');
    }

    /** @test */
    public function each_match_decision_must_be_an_integer()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'match_decision_id' => 'abc',
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.match_decision_id');
    }

    /** @test */
    public function each_match_decision_must_have_a_value_more_than_one()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'match_decision_id' => 0,
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.match_decision_id');
    }

    /** @test */
    public function each_match_decision_must_exist_in_the_database()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'match_decision_id' => 99,
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.match_decision_id');
    }

    /** @test */
    public function each_match_winner_is_required()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'winner_id' => '',
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.winner_id');
    }

    /** @test */
    public function each_match_winner_must_be_an_integer()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'winner_id' => 'abc',
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.winner_id');
    }

    /** @test */
    public function each_match_winner_must_have_a_value_more_than_one()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'winner_id' => 0,
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.winner_id');
    }

    /** @test */
    public function each_match_winner_must_exist_in_the_database()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'winner_id' => 99,
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.winner_id');
    }

    /** @test */
    public function each_match_winner_must_exist_in_the_match()
    {
        factory(Wrestler::class)->create(['id' => 3]);

        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'winner_id' => 3,
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.winner_id');
    }

    /** @test */
    public function each_match_result_is_required()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'result' => '',
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.result');
    }

    /** @test */
    public function each_match_result_must_be_a_string()
    {
        $this->response = $this->actingAs($this->authorizedUser)
                            ->from(route('results.edit', ['event' => $this->event->id]))
                            ->patch(route('results.update', ['event' => $this->event->id]), $this->validParams([
                                'matches' => [
                                    [
                                        'result' => [],
                                    ]
                                ]
                            ]));

        $this->assertFormError('matches.*.result');
    }
}

04 Jul
5 months ago

xtremer360 left a reply on Passing Data Around Inside Of Validation Closures

Any further ideas on what I can do so that I have access to the match number field for the winner_id field so it can validate?

03 Jul
5 months ago

xtremer360 started a new conversation Passing Data Around Inside Of Validation Closures

I'm trying to fun the following rules for a Form Request class and near the bottom in the closure, I need to make sure that the closure is ONLY running when the validation for the match_number passes. I'm also need to figure out after it passes how I can get access to the match_number value afte rit passes so that I can use it for the bottom closure inside of the winner_id rules.

public function rules()
    {
        // dd($this->all());
        return [
            'matches'                  => ['array'],
            'matches.*.match_number'   => [
                'required',
                'integer',
                'min:1',
                'distinct',
                function($attribute, $value, $fail) {
                    if (! Match::query()->where('match_number', $value)->where('event_id', request()->event->id)->exists()) {
                        return $fail("Match #{$value} does not exist for the event.");
                    }
                },
            ],
            'matches.*.match_decision_id' => ['required', 'integer', 'min:1', Rule::exists('match_decisions', 'id')],
            'matches.*.winner_id' => [
                'required',
                'integer',
                'min:1',
                Rule::exists('wrestlers', 'id'),
                function($attribute, $value, $fail) {
                    // dd('here');
                    dd($value);
                    if ($match = Match::query()->where('match_number', '?')->where('event_id', request()->event->id)->first()) {
                        if (! $match->wrestlers->contains('id', $value)) {
                            dd('not in match');
                            return $fail("The winner of match number {$match_number} was not involed in the match.");
                        }
                        // dd('in match');
                    }
                },
            ],
            'matches.*.result' => ['required', 'string'],
        ];
    }
02 Jul
5 months ago

xtremer360 started a new conversation RESTful Actions

Hi all. I"m trying to come up with a permission slug for handling an action performed in my system.

Let's say I have an even that was saved to the database which has many matches attached to the event. Each of those matches has data already saved to its table. I'm wanting to populate each match by only updating with specific fields that have not previously been updated such as the results of that match. If I'm working RESTfully which action would be best used for this flow.

Also, what would be a good idea for a permission name slug? Any ideas better than update-matches-with-results

28 Jun
5 months ago

xtremer360 left a reply on AssertContains Not Returning True For Object Inside Of Collection

Am I missing something as to why its saying its not in the collection when it very much is as shown in the dd()

xtremer360 left a reply on How To Show My Own Data ?

You could use Route model binding. For example in your route you can do the following.

Route::get('users/{id}', [email protected]_profile);

Then do this.

public function show_profile(User $id) {
}

This way you will have the user you need and you don't have to retrieve it.

xtremer360 started a new conversation AssertContains Not Returning True For Object Inside Of Collection

I'm trying to figure out why my assertions are not working. For some reason, it's saying the following.

Failed asserting that the collection contains the specified value.
Failed asserting that false is true.

HasTitlesTrait

return $this->championships()->whereNotNull('lost_on')->with('title')->get()->pluck('title');
/** @test */
    public function past_titles_held_returns_a_collection_of_past_titles()
    {
        $wrestler = factory(Wrestler::class)->create();
        $pastTitleA = TitleFactory::createReignForWrestlerBetweenDates($wrestler, Carbon::today()->subMonths(2), Carbon::today()->subMonths(1));
        $pastTitleB = TitleFactory::createReignForWrestlerBetweenDates($wrestler, Carbon::today()->subWeeks(3), Carbon::today()->subWeeks(2));
        $currentTitle = TitleFactory::createReignForWrestlerBetweenDates($wrestler, Carbon::yesterday(), NULL);

        $pastTitlesHeld = $wrestler->pastTitlesHeld();
        dump($pastTitleA)
        dd($pastTitlesHeld);

        $pastTitlesHeld->assertContains($pastTitleA);
        $pastTitlesHeld->assertContains($pastTitleB);
        $pastTitlesHeld->assertNotContains($currentTitle);
    }
use Illuminate\Database\Eloquent\Collection as EloquentCollection;

EloquentCollection::macro('assertContains', function ($value) {
            Assert::assertTrue($this->contains($value), 'Failed asserting that the collection contains the specified value.');
        });

        EloquentCollection::macro('assertNotContains', function ($value) {
            Assert::assertFalse($this->contains($value), 'Failed asserting that the collection does not contain the specified value.');
        });

Returned data from dump($pastTitleA) and dd($pastTitles)

App\Models\Title {#1183
  #presenter: "App\Presenters\TitlePresenter"
  #guarded: []
  #dates: array:1 [
    0 => "introduced_at"
  ]
  #connection: "sqlite"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:6 [
    "name" => "Dolor inventore eum impedit qui."
    "slug" => "dolor-inventore-eum-impedit-qui"
    "introduced_at" => "2018-04-14 00:00:00"
    "updated_at" => "2018-06-28 12:26:40"
    "created_at" => "2018-06-28 12:26:40"
    "id" => 1
  ]
  #original: array:6 [
    "name" => "Dolor inventore eum impedit qui."
    "slug" => "dolor-inventore-eum-impedit-qui"
    "introduced_at" => "2018-04-14 00:00:00"
    "updated_at" => "2018-06-28 12:26:40"
    "created_at" => "2018-06-28 12:26:40"
    "id" => 1
  ]
  #changes: []
  #casts: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #presenterInstance: null
  #forceDeleting: false
}
Illuminate\Support\Collection {#1255
  #items: array:2 [
    0 => App\Models\Title {#1271
      #presenter: "App\Presenters\TitlePresenter"
      #guarded: []
      #dates: array:1 [
        0 => "introduced_at"
      ]
      #connection: "sqlite"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [
        "id" => "1"
        "name" => "Dolor inventore eum impedit qui."
        "slug" => "dolor-inventore-eum-impedit-qui"
        "introduced_at" => "2018-04-14 00:00:00"
        "created_at" => "2018-06-28 12:26:40"
        "updated_at" => "2018-06-28 12:26:40"
        "deleted_at" => null
      ]
      #original: array:7 [
        "id" => "1"
        "name" => "Dolor inventore eum impedit qui."
        "slug" => "dolor-inventore-eum-impedit-qui"
        "introduced_at" => "2018-04-14 00:00:00"
        "created_at" => "2018-06-28 12:26:40"
        "updated_at" => "2018-06-28 12:26:40"
        "deleted_at" => null
      ]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #presenterInstance: null
      #forceDeleting: false
    }
    1 => App\Models\Title {#1272
      #presenter: "App\Presenters\TitlePresenter"
      #guarded: []
      #dates: array:1 [
        0 => "introduced_at"
      ]
      #connection: "sqlite"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [
        "id" => "2"
        "name" => "Corrupti id reprehenderit voluptas quia qui odio."
        "slug" => "corrupti-id-reprehenderit-voluptas-quia-qui-odio"
        "introduced_at" => "2018-05-24 00:00:00"
        "created_at" => "2018-06-28 12:26:40"
        "updated_at" => "2018-06-28 12:26:40"
        "deleted_at" => null
      ]
      #original: array:7 [
        "id" => "2"
        "name" => "Corrupti id reprehenderit voluptas quia qui odio."
        "slug" => "corrupti-id-reprehenderit-voluptas-quia-qui-odio"
        "introduced_at" => "2018-05-24 00:00:00"
        "created_at" => "2018-06-28 12:26:40"
        "updated_at" => "2018-06-28 12:26:40"
        "deleted_at" => null
      ]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #presenterInstance: null
      #forceDeleting: false
    }
  ]
}