xtremer360

Full Stack Developer at 321

Experience

128,165

8 Best Reply Awards

  • Member Since 4 Years Ago
  • 966 Lessons Completed
  • 49 Favorites

21st September, 2018

xtremer360 left a reply on Look Up Table For Use In A Seed File • 4 weeks ago

@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 • 4 weeks ago

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;
}

13th September, 2018

xtremer360 left a reply on TravisCI Build DB Connection Times Out • 1 month ago

Anyone have any further ideas on this?

xtremer360 left a reply on Class Based Model Factories With States • 1 month ago

Any ideas to this?

12th September, 2018

xtremer360 started a new conversation Class Based Model Factories With States • 1 month ago

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;
        }
    }
}

11th September, 2018

xtremer360 left a reply on TravisCI Build DB Connection Times Out • 1 month ago

Does anyone see anything that I have done wrong?

xtremer360 left a reply on TravisCI Build DB Connection Times Out • 1 month ago

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 • 1 month ago

@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 • 1 month ago

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

10th September, 2018

xtremer360 started a new conversation TravisCI Build DB Connection Times Out • 1 month ago

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

9th September, 2018

xtremer360 left a reply on Getting Rid Of Call To Collect Helper Method. • 1 month ago

Any suggestions?

8th September, 2018

xtremer360 started a new conversation Getting Rid Of Call To Collect Helper Method. • 1 month ago

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);
        });
    }

12th August, 2018

xtremer360 started a new conversation Rephrasing Test. • 2 months ago

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);
    }

20th July, 2018

xtremer360 left a reply on Testing Collections • 3 months ago

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 • 3 months ago

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();
}

19th July, 2018

xtremer360 started a new conversation Retrieving Biggest Date Difference Between Rows • 3 months ago

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);
}

17th July, 2018

xtremer360 left a reply on Testing Collections • 3 months ago

@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 • 3 months ago

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 • 3 months ago

@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 • 3 months ago

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

xtremer360 left a reply on Testing Collections • 3 months ago

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 • 3 months ago

@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 • 3 months ago

@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 • 3 months ago

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

16th July, 2018

xtremer360 started a new conversation Testing Collections • 3 months ago

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;
        }
    }
}

10th July, 2018

xtremer360 left a reply on Loading A Relationship Collection • 3 months ago

Any further ideas from anyone that might know.

9th July, 2018

xtremer360 left a reply on Loading A Relationship Collection • 3 months ago

@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 • 3 months ago

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

8th July, 2018

xtremer360 left a reply on Improving Names For Test File • 3 months ago

Any suggestions here?

xtremer360 started a new conversation Improving Names For Test File • 3 months ago

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');
    }
}

4th July, 2018

xtremer360 left a reply on Passing Data Around Inside Of Validation Closures • 3 months ago

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?

3rd July, 2018

xtremer360 started a new conversation Passing Data Around Inside Of Validation Closures • 3 months ago

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'],
        ];
    }

2nd July, 2018

xtremer360 started a new conversation RESTful Actions • 3 months ago

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

28th June, 2018

xtremer360 left a reply on AssertContains Not Returning True For Object Inside Of Collection • 3 months ago

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 ? • 3 months ago

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 • 3 months ago

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
    }
  ]
}

25th June, 2018

xtremer360 started a new conversation HasManyThrough Relationship Troubles • 3 months ago

I think I may have misinterpreted the documentation for how to use the hasManyThrough relationship. I have the following table structure and I'm trying to get a collection of titles that the wrestler has had.

Wrestler: id, name Champion: id, wrestler_id, title_id, won_on, lost_on Title: id, name

So on Wrestler model I have this.

/**
     * A wrestler can hold many titles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function titles()
    {
        return $this->hasManyThrough(Title::class, Champion::class, 'id', 'id', 'id', 'id');
    }

/**
     * Retrieves a collection of titles currently held by wrestler.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function currentTitlesHeld()
    {
        return $this->titles()->whereNull('lost_on');
    }

24th June, 2018

xtremer360 left a reply on Creating Model Factory Methods • 3 months ago

@shez1983 I was thinking of moving that code to a method in a factory as per my original post. My question was should it be for a MatchFactory or WrestlerFactory.

xtremer360 left a reply on Creating Model Factory Methods • 3 months ago

What would be the best way to go?

xtremer360 left a reply on Creating Model Factory Methods • 3 months ago

Any suggestions?

23rd June, 2018

xtremer360 left a reply on Dynamic Table • 3 months ago

You could assign a type of an empty array to the fields prop then pass in the array of fields that you need to loop through in your vue template.

xtremer360 started a new conversation Creating Model Factory Methods • 3 months ago

I have this happening in about 4 different test methods as part of my set up for those tests and I'm trying to figure out what I can do to refactor. I've considered creating a ModelFactory method from it but not sure which one I should do.

$event = factory(Event::class)->create(['date' => '2017-11-09']);
$match = factory(Match::class)->create(['event_id' => $event->id]);
$sideNumber = mt_rand(0, $match->type->number_of_sides);
$match->addWrestler($this->wrestler, $sideNumber);

Should I create a MatchFactory and do MatchFactory::createForWrestlerOnDate($wrestler, $date) or should I do WrestlerFactory::createMatchForWrestlerOnDate($wrestler, $date)

19th June, 2018

xtremer360 left a reply on Refactoring Test Methods • 4 months ago

I know about states but I"m not sure how I could attach wrestlers for a match beacuse its a belongsToMany relationship for both.

$factory->define(App\Models\Match::class, function (Faker\Generator $faker) {
    return [
        'event_id' => factory(App\Models\Event::class)->lazy(),
        'match_number' => $faker->numberBetween(6, 10),
        'match_type_id' => factory(App\Models\MatchType::class)->lazy(),
        'stipulation_id' => factory(App\Models\Stipulation::class)->lazy(),
        'preview' => $faker->paragraphs(3, true)
    ];
});

xtremer360 left a reply on Refactoring Test Methods • 4 months ago

@BrandonSurowiec for the following code I thought about it but I also have a pivot table between a wrestler and a title that is contained in a TitleChampion model. I also have a factory for this model. I am not sure if using a factory for getting a title champion is the best so I"m wondering if you agree and would suggest keeping with your approach and just doing the state withChampion on the Title factory.

$factory->define(App\Models\Champion::class, function (Faker\Generator $faker) {
    return [
        'wrestler_id' => factory(App\Models\Wrestler::class)->lazy(),
        'title_id' => factory(App\Models\Title::class)->lazy(),
        'won_on' => Carbon::now(),
    ];
});

18th June, 2018

xtremer360 started a new conversation Refactoring Test Methods • 4 months ago

I'm trying to clean up some old code from a project and trying to figure out some ideas on renaming the test functions in a better way so that I nor others have to scratch their head to try to understand what I'm attempting to do. Also any suggestions on if there are areas in the test that I could modify.

/** @test */
    public function a_non_title_match_can_set_a_winner()
    {
        $wrestlerA = factory(Wrestler::class)->create();
        $wrestlerB = factory(Wrestler::class)->create();
        $match->addWrestlers([
            0 => [$wrestlerA],
            1 => [$wrestlerB]
        ]);

        $this->match->setWinner($wrestlerA, 'pinfall');

        $this->assertEquals($wrestlerA->id, $this->match->winner_id);
        $this->assertEquals($wrestlerB->id, $this->match->loser_id);
    }

    /** @test */
    public function a_title_match_champion_can_be_set_as_winner()
    {
        $wrestlerA = factory(Wrestler::class)->create();
        $title = factory(Title::class)->create();
        $title->setChampion($wrestlerA, Carbon::parse('2018-03-03'));

        $event = factory(Event::class)->create(['date' => '2018-03-05']);
        $match = factory(Match::class)->create(['event_id' => $event->id]);
        $wrestlerB = factory(Wrestler::class)->create();
        $match->addWrestlers([
            0 => [$wrestlerA],
            1 => [$wrestlerB]
        ]);
        $match->addTitle($title);

        $match->setWinner($wrestlerA, 'dq');

        $this->assertEquals($wrestlerA->id, $match->winner_id);
        $this->assertEquals($wrestlerB->id, $match->loser_id);
        $this->assertEquals($wrestlerA, $title->currentChampion);
    }

    /** @test */
    public function a_title_changes_hands_when_a_non_champion_wins_a_title_match()
    {
        $wrestlerA = factory(Wrestler::class)->create(['name' => 'Wrestler A']);
        $title = factory(Title::class)->create();
        $title->setChampion($wrestlerA, Carbon::parse('2018-03-03'));

        $event = factory(Event::class)->create(['date' => Carbon::parse('2018-03-05')]);
        $match = factory(Match::class)->create(['event_id' => $event->id]);
        $wrestlerB = factory(Wrestler::class)->create(['name' => 'Wrestler B']);
        $match->addWrestlers([
            0 => [$wrestlerA],
            1 => [$wrestlerB]
        ]);
        $match->addTitle($title);

        $match->setWinner($wrestlerB, 'pinfall');

        $title->refresh();
        $this->assertEquals($wrestlerB->id, $match->winner_id);
        $this->assertEquals($wrestlerA->id, $match->loser_id);
        $this->assertEquals($wrestlerB->id, $title->currentChampion->id);
    }

16th June, 2018

xtremer360 left a reply on Imploding Collections • 4 months ago

@adamprickett Thank you that is a great response. That is the solution I was looking for, however, I'm wondering if the first couple of lines in my presenter method should be placed in a separate place and only keep the return statement in the method.

public function players()
    {
        $groupedPlayers = $this->model->players->groupBy(function ($item, $key) {
            return $item->pivot->side_number;
        });

        return $groupedPlayers->map(function ($group) {
            return $group->pluck('name')->implode(' & ');
        })->implode(' vs. ');
    }

xtremer360 started a new conversation Imploding Collections • 4 months ago

I'm looking for a way that I can take a collection that contains groups of inner collections and imploding by the group but with the special characters on each group and then as well with the inner groups with a different text string.

If I take my grouped collection and run toArray() on it.

array:2 [
  0 => array:2 [
    0 => array:2 [
      "id" => 1
      "name" => "Player 1"
      ]
    ]
    1 => array:2 [
      "id" => 3
      "name" => "Player 2"
      ]
    ]
  ]
  1 => array:1 [
    0 => array:2 [
      "id" => 2
      "name" => "Player 3"
      ]
    ]
  ]
]

Final result:

Player 1 & Player 2 vs. Player 3

11th June, 2018

xtremer360 left a reply on Custom Rule Class • 4 months ago

Any suggestions?

xtremer360 started a new conversation Custom Rule Class • 4 months ago

I have a feeling that I have written the follow Rule class incorrectly and could use some guidance and what I've done wrong because I am not achieving my desired results.

What I'm trying to achieve is validate a form with my custom request class called MatchCreateFormRequest which I have included below. The section that is not correct is when I am trying to validate that a wrestler is qualified for a match at an event that the match belongs to.

Each event contains a date. Each wrestler has a hired_at date.

The requirement is the wrestler must have been hired before the event is scheduled to take place.

From my test all it says is there's no error missing from the session but there should be with that Rule.

Any suggestions on where I"m going wrong with this?

<?php

namespace App\Rules;

use Carbon\Carbon;
use Illuminate\Contracts\Validation\Rule;

class QualifiedForMatch implements Rule
{
    /**
     * @var \App\Models\Event
     */
    private $eventDate;

    /**
     * @var \App\Models\*
     */
    private $model;

    /**
     * Create a new rule instance.
     *
     * @param $eventDate
     */
    public function __construct($eventDate, $model)
    {
        $this->eventDate = $eventDate;
        $this->model = $model;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $model)
    {
        return $model->$attribute->lte(Carbon::parse($this->eventDate));
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'This '.strtolower(class_basename(get_class($this->model))).' is not qualified for the match.';
    }
}

<?php

namespace App\Http\Requests;

use App\Models\MatchType;
use App\Models\Wrestler;
use App\Models\Event;
use App\Rules\QualifiedForMatch;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Validator;

class MatchCreateFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->user()->hasPermission('store-match');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // dd($this->all());
        $date = Event::where('id', $this->event_id)->first()->date;

        $rules = [
            'matches' => 'array',
            'matches.*.match_number' => 'required|integer|min:1',
            'matches.*.match_type_id' => 'required|integer|exists:match_types,id',
            'matches.*.stipulations' => 'array',
            'matches.*.stipulations.*' => 'sometimes|distinct|integer|exists:stipulations,id',
            'matches.*.titles' => 'array',
            'matches.*.titles.*' => 'sometimes|distinct|integer|exists:titles,id',
            'matches.*.referees' => 'required|array',
            'matches.*.referees.*' => 'distinct|integer|exists:referees,id',
            'matches.*.preview' => 'required|string',
        ];

        if (is_array($this->matches)) {
            $i = 0;
            foreach ($this->matches as $match) {
                if (!is_null($match['match_type_id']) && is_integer($match['match_type_id']) && MatchType::where('id', $match['match_type_id'])->exists()) {
                    $total = (int) MatchType::where('id', $match['match_type_id'])->first()->total_competitors;

                    $rules["matches.{$i}.wrestlers"] = 'required|array|size:' . $total;
                    $i++;
                }

                dd($match['wrestlers']);
                foreach($match['wrestlers'] as $key => $wrestlerId) {
                    $exists = Wrestler::where('id', $wrestlerId)->exists();
                    if ($exists) {
                        $wrestler = Wrestler::where('id', $wrestlerId)->first();
                        $rules["matches.{$i}.wrestlers"] = [
                            'distinct',
                            'integer',
                            'exists:wrestlers,id',
                            new QualifiedForMatch($date, $wrestler)
                        ];
                    }
                }
            }
        }

        return $rules;
    }
}

10th June, 2018

xtremer360 left a reply on Laravel • 4 months ago

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.