xtremer360

xtremer360

Full Stack Developer at 321

Member Since 5 Years Ago

Kissimmee, FL

Experience Points
160,145
Total
Experience

4,855 experience to go until the next level!

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

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

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 33
160,145 XP
Mar
24
4 days ago
Activity icon

Replied to Laravel 6 - TDD App - Expected Status Code 403 But Received 200.

@ajsmith_codes You'll need to add either one of these two options. The reason you are getting that is that you have the route you are testing has a dependency of an authorized signed-in user. So you will need to create a user and log them in before access the route.

$this->actingAs($user = factory(User::class)->create())->get(...

OR

$this->be($user = factory(User::class)->create())->get(...
Mar
17
1 week ago
Activity icon

Replied to Mocking A Trait

Any help here would be appreciated.

Mar
14
2 weeks ago
Activity icon

Replied to Mocking A Trait

I have created a fixture to try and help with testing the trait, however, when I run my test with the updated test below it shows the builder object as having a null value from inside of the trait startedAt method. What am I doing wrong here for that to happen?

Is there a way I can access the builder property from inside the startedAt method from the Filters class?

<?php

namespace Tests\Fixtures;

use App\Filters\Concerns\FiltersByStartDate;
use App\Filters\Filters;

class ExampleFilters extends Filters
{
    use FiltersByStartDate;
}
<?php

namespace Tests\Unit\Filters\Concerns;

use Illuminate\Database\Query\Builder;
use Tests\Fixtures\ExampleFilters;
use Tests\TestCase;

/*
 * @group filters
 */
class FiltersByStartDateTest extends TestCase
{
    /* @var Tests\Fixtures\ExampleFilters */
    protected $subject;

    public function setUp(): void
    {
        $this->subject = app(ExampleFilters::class);
    }

    /** @test */
    public function models_can_be_filtered_by_their_start_date()
    {
        // $this->markTestIncomplete();

        $dateSet = ['2020-01-01 00:00:00'];

        $mock = \Mockery::mock(Builder::class)
            ->shouldReceive('whereHas', \Mockery::any())
            ->shouldReceive('whereDate')
            ->withArgs(['started_at', $dateSet])
            ->once()
            ->andReturn(true)
            ->getMock();

        $builderMockFromDate = $this->subject->startedAt($dateSet);

        $this->assertSame($builderMockFromDate, $mock);
    }
}

Activity icon

Replied to Mocking A Trait

Thank you but yes I don’t see how his post helps me. Do you have experience with mocking that could assist with this post?

Activity icon

Replied to Mocking A Trait

@sinnbeck is there a way to remove the bear answer so people can continue leaving helpful responses

Mar
13
2 weeks ago
Activity icon

Replied to Mocking A Trait

Problem is I have the whereHas('currentEmployment') inside the trait method. I would need to handle that somehow because I get this error below.

Mockery\Exception\BadMethodCallException: Method Mockery_0_Illuminate_Database_Query_Builder::whereHas() does not exist on this mock object
Activity icon

Started a new Conversation Mocking A Trait

The test method below is not correct and would like some assistance understanding how to work with dummy classes as I've created at the bottom of the test file. My goal is to unit test the trait below the test file. The reason why I'm trying to unit test the trait is that I have 5 different models that include the trait and unit testing the trait would allow me to just show that trait method works and just individually test the linkage between the models that use the trait.

I'm trying to figure out how to set up a mock so that my example class has a currentEmployment. At this point I'm not sure if its needed to actually create the employment record or not because I don't want to use the database for this test.

<?php

namespace Tests\Unit\Filters\Concerns;

use Illuminate\Database\Query\Builder;
use Tests\TestCase;

/*
 *
 * @group filters
 */
class FilterByStartDateTest extends TestCase
{
    protected $subject;

    public function setUp(): void
    {
        $this->subject = new Example();
    }

    /** @test */
    public function some_models_can_be_filtered_by_their_start_date()
    {
        $this->markTestIncomplete();

        $dateSet = ['2020-01-01 00:00:00'];

        $mock = \Mockery::mock(Builder::class)
            ->shouldReceive('whereBetween')
            ->withArgs(['started_at', $dateSet])
            ->once()
            ->andReturn(true)
            ->getMock();

        $builderMockFromDate = $this->subject->startedAt($dateSet);

        $this->assertSame($builderMockFromDate, $mock);
    }
}

class Example
{
}
<?php

namespace App\Filters\Concerns;

trait FiltersByStartDate
{
    /**
     * Filter a query to include models of a specific date started.
     *
     * @param  array  $startedAt
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function startedAt($startedAt)
    {
        if (isset($startedAt[1])) {
            $this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
                $query->whereBetween('started_at', [
                    $startedAt[0],
                    $startedAt[1]
                ]);
            });
        } else {
            $this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
                $query->whereDate('started_at', $startedAt[0]);
            });
        }

        return $this->builder;
    }
}

Mar
11
2 weeks ago
Activity icon

Replied to Empty Wheres Property For Mocked Builder

Does anyone have any suggestions on what I'm doing wrong here?

Mar
10
2 weeks ago
Activity icon

Replied to Empty Wheres Property For Mocked Builder

Any suggestions from anyone or is there any questions I can answer to help get further assistance.

Activity icon

Replied to Empty Wheres Property For Mocked Builder

This is my updated test and I'm getting the following error. Where should I be using Carbon for the dates and is there anything I'm not doing right with the rest of my code?

Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Illuminate_Database_Query_Builder::whereBetween('date', [0 => object(Illuminate\Support\Carbon), 1 => object(Illuminate\Support\Carbon)]). Either the method was unexpected or its arguments matched no expected argument list for this method

<?php

namespace Tests\Unit\Filters;

use App\Filters\Concerns\FiltersByStatus;
use App\Filters\EventFilters;
use Carbon\Carbon;
use Illuminate\Database\Query\Builder;
use Tests\TestCase;

/*
 * @group events
 */
class EventFiltersTest extends TestCase
{
    /** @var App\Filters\EventFilters */
    protected $subject;

    /**
     * Setup the test environment.
     *
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->subject = app(EventFilters::class);
    }

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

        $dateSet = [$now, $now->addDays(2)];

        $this->assertTrue(in_array('date', $this->subject->filters));

        $builderMock = $this->getBuilderMock(true, $dateSet);
        $this->subject->apply($builderMock);

        $builderMockFromDate = $this->subject->date(
            $dateSet
        );

        $this->assertInstanceOf(Builder::class, $builderMock);
        $this->assertSame($builderMockFromDate, $builderMock);
    }

    private function getBuilderMock($shouldCallWhereBetween, $dateSet)
    {
        $mock = \Mockery::mock(Builder::class);

        // Make sure we expect strings, not objects
        foreach ($dateSet as $arrIndex => $date) {
            $dateSet[$arrIndex] = Carbon::parse($date);
        }

        if ($shouldCallWhereBetween) {
            $mock->shouldReceive('whereBetween')
                ->withArgs($dateSet)
                ->once()
                ->andReturn(true);
        } else {
            $mock->shouldReceive('whereDate')
                ->andReturn(true);
        }

        return $mock;
    }
}
public function date($date)
{
    if (isset($date[1])) {
        $this->builder->whereBetween('date', [
            $date[0],
            $date[1],
        ]);
    } elseif (isset($date[0])) {
        $this->builder->whereDate('date', $date[0]);
    }

    return $this->builder;
}
Mar
09
2 weeks ago
Activity icon

Started a new Conversation Empty Wheres Property For Mocked Builder

I'm trying to find out I'm getting an empty array for my wheres property on the mocked Builder class. Does anyone see anything I'm doing wrong here?

<?php

namespace App\Filters;

use Carbon\Carbon;

class EventFilters extends Filters
{
    use Concerns\FiltersByStatus;

    /**
     * Registered filters to operate upon.
     *
     * @var array
     */
    public $filters = ['status', 'date'];

    /**
     * Filter a query to include events of a specific date.
     *
     * @param  array  $date
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function date($date)
    {
        if (isset($date[1])) {
            $this->builder->whereBetween('date', [
                Carbon::parse($date[0]),
                Carbon::parse($date[1])
            ]);
        } elseif (isset($date[0])) {
            $this->builder->whereDate('date', Carbon::parse($date[0]));
        }

        return $this->builder;
    }
}
/** @test */
    public function event_filters_include_filtering_by_date()
    {
        $this->assertTrue(in_array('date', $this->subject->filters));

        $this->subject->apply($this->getBuilderMock(true));

        $now = now();
        Carbon::setTestNow($now);

        $date = [$now, $now->addDays(2)];

        $builder = $this->subject->date($date);

        $this->assertAttributeContainsOnly('whereBetween', 'wheres', $builder);
    }

    private function getBuilderMock($shouldCallWhereBetween)
    {
        $mock = \Mockery::mock(Builder::mock);

        if ($shouldCallWhereBetween) {
            $mock->shouldReceive('whereBetween')
                ->andReturn(true);
        } else {
            $mock->shouldReceive('whereDate')
                ->andReturn(true);
        }

        return $mock;
    }
Mar
08
2 weeks ago
Activity icon

Replied to Trying To Test A Mock Of A Filters Class

@bobbybouwmann Is there something that can help me understand using the app helper because of the class taking on the Request class as a dependency?

Mar
07
3 weeks ago
Activity icon

Replied to Trying To Test A Mock Of A Filters Class

@bobbybouwmann I can't do that because $this->subject would not ber an object just the returned string representation of thhe class path.

Activity icon

Started a new Conversation Trying To Test A Mock Of A Filters Class

I'm attempting to try and unit test the class below. I don't know if this is the proper way to do it but this is what I"m attempting. The first assertion in each test fails due to these error messages.

Failed asserting that an array contains 'App\Filters\Concerns\FiltersByStatus'. Failed asserting that an array contains 'App\Filters\Concerns\FiltersByStartDate'.

What suggestions does anyone have to correct this error or perhaps better write the test for this?

<?php

namespace App\Filters;

class UserFilters extends Filters
{
    use Concerns\FiltersByStartDate,
        Concerns\FiltersByStatus;

    /**
     * Registered filters to operate upon.
     *
     * @var array
     */
    public $filters = ['status', 'started_at'];
}

<?php

namespace Tests\Unit\Filters;

use App\Filters\Concerns\FiltersByStartDate;
use App\Filters\Concerns\FiltersByStatus;
use App\Filters\UserFilters;
use Tests\TestCase;

class UserFiltersTest extends TestCase
{
    /** @var App\Filters\UserFilters */
    protected $subject;

    /**
     * Setup the test environment.
     *
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->subject = $this->mock(UserFilters::class);
    }

    /** @test */
    public function user_filters_include_filtering_by_status()
    {
        $this->assertUsesTrait(FiltersByStatus::class, $this->subject);
        $this->assertTrue(in_array('status', get_class($this->subject)->filters));
    }

    /** @test */
    public function user_filters_include_filtering_by_started_at_date()
    {
        $this->assertUsesTrait(FiltersByStartDate::class, $this->subject);
        $this->assertTrue(in_array('started_at', $this->subject->filters));
    }
}
Mar
05
3 weeks ago
Activity icon

Replied to How To Disable Casting During Testing

Yeah I took a second look to understand what the second param did. Makes sense. Thank you.

Activity icon

Replied to How To Disable Casting During Testing

@sti3bas Actually I jumped the gun a second. The assertion gives me null for the $user->getRawOriginal('status'). How could that be?

Activity icon

Replied to How To Disable Casting During Testing

Yes thank you @sti3bas for this solution.

Activity icon

Replied to How To Disable Casting During Testing

I know that. My question is how can I disable casting during testing.

Activity icon

Replied to How To Disable Casting During Testing

I'm using 7.2 I'll also add this to the original post.

UnexpectedValueException: Value 'example' is not part of the enum App\Enums\UserStatus

Activity icon

Replied to How To Disable Casting During Testing

The problem isn't with the assertion. The problem is that it doesn't successfully create the model. It errors on the creation of the model due to the cast.

Also notice in my test I am using getRawOriginal()

Activity icon

Started a new Conversation How To Disable Casting During Testing

I need to figure out a way to unit test that a user has a status property on the model. With this model, I have a custom enum cast object coming from the package listed below. Currently, my test fails at the creation of the user object. The reason being is that it is looking for a value of example as a valid enum valid. Since there is not then it errors. What

I want to do is being to add to the test to have it ignore that specific cast for the purpose of this test. How is that possible?

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

Error given from test.

UnexpectedValueException: Value 'example' is not part of the enum App\Enums\UserStatus

App\Models\User.php

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
    'status' => Status::class,
];

tests/Unit/Models/UserTest.php

public function a_user_has_a_status()
{
    $user = new User(['status' => 'example']);

    $this->assertEquals('example', $user->getRawOriginal('status'));
}
Feb
22
1 month ago
Activity icon

Replied to Validation Rules For Field Allowable Null And String

@sti3bas I like this solution, however, is there a cleaner way of writing that? I've also stumbled upon this package and wondered if this would be a good use case because this rule would be reused many times in my project.

https://github.com/illuminatech/validation-composite

Feb
21
1 month ago
Activity icon

Replied to Validation Rules For Field Allowable Null And String

I've even tried this and still have the same problems.

'started_at' => [
    'sometimes',
    'nullable',
    ....
]
Feb
20
1 month ago
Activity icon

Replied to Validation Rules For Field Allowable Null And String

With the provided validation rules and passing in null for the started_at field then it fails at the required rule.

'started_at' => [
    'sometimes',
    'required',
    'string',
    'date_format:Y-m-d H:i:s',
    new EmploymentStartDateCanBeChanged($this->route('manager')),
],
Activity icon

Started a new Conversation Validation Rules For Field Allowable Null And String

I'm trying to figure out how I need to structure this validation rules array for my started_at field because this is for an update model form. I need to be able to allow null ONLY in a specific case which I'm covering inside of my custom validation rule. So in other words if the field is filled then it needs to be a string and in the proper date format and then ran through the custom rule but I don't want it to fail if its null. I can't put nullable bercause then that would negate the string validation rule.

'started_at' => [
    'string',
    'date_format:Y-m-d H:i:s',
    new EmploymentStartDateCanBeChanged($this->route('referee'))
]
Feb
18
1 month ago
Activity icon

Started a new Conversation Subscription Business And Personal

How does it work if I pay for a monthly subscription for Laracasts and the company I just hired at is paying for a subscription on their team? Do I need to have them change the email on their team to send it to my personal email instead of my company email so I can continue to have the videos I watch AND any posts/replies on the discussion board I make can be continued from my personal account?

Feb
13
1 month ago
Activity icon

Replied to Flattening With Collect Helper Changes Collection To Empty

@sinnbeck Wouldn't I first have to turn each of the groups including the managers into collections to use merge()?

Activity icon

Replied to Flattening With Collect Helper Changes Collection To Empty

@sinnbeck What would be the fix for this problem then?

Activity icon

Replied to Flattening With Collect Helper Changes Collection To Empty

@sinnbeck After testing I still get an empty Illuminate\Support\Collection

Activity icon

Replied to Flattening With Collect Helper Changes Collection To Empty

@sinnbeck Problem is that all() returns a collection and for me $this->managers is an array.

Activity icon

Replied to Flattening With Collect Helper Changes Collection To Empty

@psylogic No because the $employees turns into an empty array so obviously trying to run values() on it is still an empty array.

Activity icon

Replied to Flattening With Collect Helper Changes Collection To Empty

I'll update the post but those all return an empty array.

Activity icon

Started a new Conversation Flattening With Collect Helper Changes Collection To Empty

I'm having problems with the collect helper method. I am passing an array with one object inside and trying to collect the items and flatten one level so that I can perform some actions on the collection as a whole and after it flattens then somehow it turns into an empty collection. $group1, $group2, and group3 all have values of empty arrays. [].

Has anyone seen this happen before?

dd($this->managers); // Shown in snippet below.

$employees = collect(
    $this->group1 ?? [],
    $this->group2 ?? [],
    $this->managers ?? [],
    $this->group3 ?? []
)->flatten(1);

This is the result of the dd above.

array:1 [
  0 => App\Models\Manager^ {#8401
    #guarded: []
    #casts: array:1 [
      "status" => "App\Enums\ManagerStatus"
    ]
    #connection: "sqlite"
    #table: "managers"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #attributes: array:6 [
      "first_name" => "Brittany"
      "last_name" => "Kassulke"
      "status" => "pending-employment"
      "updated_at" => "2020-02-13 14:05:54"
      "created_at" => "2020-02-13 14:05:54"
      "id" => 1
    ]
    #original: array:6 [
      "first_name" => "Brittany"
      "last_name" => "Kassulke"
      "status" => "pending-employment"
      "updated_at" => "2020-02-13 14:05:54"
      "created_at" => "2020-02-13 14:05:54"
      "id" => 1
    ]
    #changes: []
    #dates: array:1 [
      0 => "deleted_at"
    ]
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
    #cachedAttributes: []
    #forceDeleting: false
  }
]
Feb
07
1 month ago
Activity icon

Started a new Conversation Custom Relationship Collection Is Returning Empty Collection

Can someone explain to me why I'm getting the right collection for using the get() on the relationship but when I call it to get the returned collection I get an empty array?

public function a_bookable_tag_team_has_two_current_wrestlers()
    {
        $team = TeamFactory::new()->create();

        $this->assertCount(2, $team->playerHistory);
        dd($team->playerHistory()->current()->get()); // WORKS!!!!

        // DB::enableQueryLog();
        // dd($team->currentPlayers()->get()); // WORKS!!!!
        // dd($team->currentPlayers); // DOES NOT WORK (Gives empty array) !!!
        // dd(DB::getQueryLog());


        // $this->assertInstanceOf(Collection::class, $team->currentPlayers);
        $this->assertCount(2, $team->currentPlayers); // Count is 0 
    }
<?php

namespace App\Models;

use App\Eloquent\Concerns\HasCustomRelationships;
use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    /**
     * Get the players belonging to the team.
     *
     * @return App\Eloquent\Relationships\LeaveableBelongsToMany
     */
    public function playerHistory()
    {
        return $this->leaveableBelongsToMany(Player::class, 'tag_team_player', 'team_id', 'player_id');
    }

    /**
     * Get all current players that are members of the team.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
     */
    public function currentPlayers()
    {
        return $this->playerHistory()->current();
    }
<?php

namespace App\Eloquent\Concerns;

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

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

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

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

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

    public function current()
    {
        // $this->wherePivot('left_at', null);
        // $this->wherePivot('left_at', DB::raw('is null'));
        // $this->wherePivot('left_at', 'is', DB::raw('null'));
        // $this->wherePivot('left_at', '==', DB::raw('is null'));
        $this->whereNull('left_at');

        return $this;
    }

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

        return $this;
    }

}
Feb
05
1 month ago
Activity icon

Replied to Refactoring Custom Validation Rule

Any additional suggestions from anyone?

Feb
04
1 month ago
Activity icon

Replied to Refactoring Custom Validation Rule

Is there anything in the rule that could be split into multipole rules?

Feb
03
1 month ago
Activity icon

Replied to Refactoring Custom Validation Rule

@roborobok

'started_at' => ['nullable', 'string', 'date_format:Y-m-d H:i:s'],
'players' => ['nullable', 'array', 'max:2'],
'players.*' => [
    'bail', 'integer', 'exists:players,id', new CanJoinTeam($this->input('started_at'))
],
Activity icon

Started a new Conversation Refactoring Custom Validation Rule

I'm looking for suggestions on how I can refactor my custom validation rule. The passed in startedAt field comes from an input of the request. I don't know if I should be making this into separate custom validation rules or not.

<?php

namespace App\Rules;

use App\Models\Player;
use Illuminate\Contracts\Validation\Rule;

class CanJoinTeam implements Rule
{
    protected $startedAt;

    public function __construct(string $startedAt)
    {
        $this->startedAt = $startedAt;
    }

    public function passes($attribute, $value)
    {
        $player = Player::find($value);

        if ($player->isEmployed()) {
            if ($player->isSuspended() || $player->isRetired() || $player->isInjured()) {
                return false;
            }

            if ($player->currentEmployment->started_at->gt($this->started_at)) {
                return false;
            }

            if ($player->currentTeam()->exists()) {
                return false;
            }
        } else {
            if ($player->has('pendingEmployment')) {
                if ($player->pendingEmployment->started_at->gt($this->started_at)) {
                    return false;
                }
            }
        }

        return true;
    }
}
Jan
20
2 months ago
Activity icon

Commented on Tips For Simplifying Laravel Controllers

What is everyone’s thoughts on doing Route::view() when only returning a view from a route that was it removes the need for a controller?

Jan
15
2 months ago
Activity icon

Replied to PHP CS FIxer

Actually I found out that it was another extentsion that somehow got set to auto sort imports on save.

Activity icon

Replied to PHP CS FIxer

Thanks for your reply. I have it working so that when I use the extension to format the document it works according to the rules I’ve set, however I have the Format on Save option checked in the extension settings and it’s not going by the same rules

Activity icon

Started a new Conversation PHP CS FIxer

I'm trying to get php cs fixer plugin set kup properly for Visual Studio Code. I came across the a .php_cs.laravel.php file that is used for Laravel Shift for fixing common problems with their Laravel projects.

Should I place the .php_cs.laravel.php inside of my project files or place it inside of the .vscode directory as a global file. The reason why I ask is because I want to be able to use the same file for all of my Laravel specific projects.

https://gist.github.com/laravel-shift/cab527923ed2a109dda047b97d53c200

Jan
14
2 months ago
Activity icon

Started a new Conversation Different Formats For Accessor

Currently the code below all works as expected, however, I was curious if anyone notices any possible flaws and what they might suggest doing differently.

I'll go through and explain what each class is doing.

I'm using Spatie's Model View package and put together a class to send through either a new manager or a specific instance. When its passing in a new instance then it will essentially pass in null for the the started_at property since we are creating a new model. If we are passing in a specific instance then we need to call the started_at accessor to see if the manager has any employments and if so then grab the first one if not then it should return null meaning we are editing a manager that was saved but didn't have an employment declared when originally creating the manager. When displaying the started_at property on the manager form I want it to display as a datetime string.

Below I also have a datatable class from using Yajra's laravel-datatables package. When I retrieve all managers with an employment and l am editing the startd_at field so that it can format how the field displays, I am displaying it as a date string without the time.

With having to use the optional helper method in multiple places is there a better way?

<?php

namespace App\ViewModels;

use App\Models\Manager;
use Spatie\ViewModels\ViewModel;

class ManagerViewModel extends ViewModel
{
    /** @var $manager */
    public $manager;

    /**
     * Undocumented function
     *
     * @param App\Models\Manager $manager
     */
    public function __construct(Manager $manager = null)
    {
        $this->manager = $manager ?? new Manager;
        $this->manager->started_at = optional($this->manager->started_at ?? null)->toDateTimeString();
    }
}
<?php

namespace App\DataTables;

use App\Models\Manager;
use App\Filters\ManagerFilters;
use Yajra\DataTables\Services\DataTable;

class ManagersDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables($query)
            ->editColumn('started_at', function (Manager $manager) {
                return $manager->started_at->toDateString();
            })
    }
}
<?php

namespace App\Models\Concerns;

use App\Models\Employment;

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

    /**
     * Get the model's first employment date.
     *
     * @return string|null
     */
    public function getStartedAtAttribute()
    {
        return optional($this->employments->first())->started_at;
    }
}

Activity icon

Replied to Yajra Datatables Query Method Being Compatible Error

@nakov I had to install yajra/laravel-datatables-buttons which I wasn't aware of as well.

Activity icon

Replied to Refactoring Controller Update Method

Anyone have any additional suggestions?

Jan
13
2 months ago
Activity icon

Replied to Refactoring Controller Update Method

@jorpedito Can you explain why you think the updateOrCreate method is written wrong?

Activity icon

Started a new Conversation Refactoring Controller Update Method

I'm trying to determine if I can refactor my controller update method so that I can better employ a manager.

ManagersController

public function update(UpdateRequest $request, Manager $manager)
{
    $manager->update($request->except('started_at'));

    $startedAt = $request->input('started_at');
    $isEmployed = $manager->isEmployed();

    if ($startedAt && $isEmployed && Carbon::parse($startedAt)->lt($manager->currentEmployment->started_at)) {
        $manager->employ($request->input('started_at'));
    }

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

Manager Model

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

    return $this->touch();
}

public function canBeEmployed()
{
    if ($this->isEmployed()) {
        return false;
    }

    return true;
}

public function isEmployed()
{
    return $this->currentEmployment()->exists();
}
Jan
11
2 months ago
Activity icon

Replied to Disabling Instance Property Casts

@tykus Thanks for the quick reply. Maybe you can help me understand this because getOriginal() works however when I try it with getAttribute it uses the casting.