xtremer360

xtremer360

Full Stack Developer at 321

Member Since 6 Years Ago

Kissimmee, FL

Experience Points
171,485
Total
Experience

3,515 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
1292
Lessons
Completed
Best Reply Awards
13
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 35
171,485 XP
Jul
03
1 month ago
Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

Thank you for all your help.

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@martinbean I understand that. Do you have any suggestions on what I should do?

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@snapey I'm wondering if I try and use the mutator approach with the feet and inches. Would I just unset the property? I'm having a hard time understanding what I would do with the mutator for those two fields. Can you explain that portion for me please?

public function setFeetAttribute($value)
{
        $this->attributes['feet'] = $value;
}

public function setInchesAttribute($value)
{
        $this->attributes['inches'] = $value;
}
Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

If I do $request->all() as the first line of my store method then it shows the height property with the correct value AND it removed the feet and inches properties, but when I call validated() on the request it gives me the true validated fields. Is there an alternative so that I can handle this problem?

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@martinbean I added the fields that needed to be fillable meaning the patients name and height and a few other fields and unfortunately it did not improve my results.

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@martinbean I'll go in and make it fillable to see if I get different results and report back.

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@martinbean I have the model set up as a guarded array as opposed to a fillable array.

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@snapey At this time I'm not looking to store the feet and inches in the database along side the height. I'd rather just maintain the one field in the database.

As far as the second option you provided. It could work however I was hoping to keep that logic contained in the request class.

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@bobbybouwmann I tried your solution and unfortunately came up with the same results were it still adds the feet and inches back into the validated fields. Is there a problem I'm having from my macro above?

Jul
02
1 month ago
Activity icon

Started a new Conversation Adding Fields To Validated That Aren't Directly Validated

I'm running into a problem where I'm trying to send all the validated request data to the create method for an Eloquent model. I found a macro that can help send all validated data except for any fields that shouldn't be send to the create method. The problem here is that I can't do this because of the afterValidationHook method in my request class. The reason why I can't is because when it goes to create the model its going to look for the feet and inches parameters and those don't exist in the database table.

Does anyone have any suggestions on what I could do here so that I could easily pass validated data minus the feet and inches but plus the height parameter added in the hook?

Patient::create($request->validatedExcept('started_at'));
<?php

namespace App\Http\Requests\Patients;

use App\Models\Patient;
use Illuminate\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'feet' => [
                'required',
                'integer',
                'min:5',
                'max:7'
            ],
            'inches' => [
                'required',
                'integer',
                'max:11'
            ],
            'started_at' => [
                'nullable',
                'string',
                'date_format:Y-m-d H:i:s'
            ],
            // More validated fields
        ];
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if ($validator->errors()->isEmpty()) {
                $this->merge(['height' => ($this->input('feet') * 12) + $this->input('inches')]);
                $this->offsetUnset('feet');
                $this->offsetUnset('inches');
            }
        });
    }
}

Request::macro('validatedExcept', function ($keys) {
    $keys = is_array($keys) ? $keys : func_get_args();

    $results = $this->validated();

    Arr::forget($results, $keys);

    return $results;
});
Activity icon

Awarded Best Reply on How To Know What Is Inside An Eloquent Object

@mirsahib Laravel provides a new little helper method dd() that will dump and die any variable passed to it. So below the variable being defined you can simply do dd($phone) and see what value is contained on that variable.

Edit: Why do you say dd() is not helpful?

Activity icon

Replied to How To Know What Is Inside An Eloquent Object

@mirsahib Laravel provides a new little helper method dd() that will dump and die any variable passed to it. So below the variable being defined you can simply do dd($phone) and see what value is contained on that variable.

Edit: Why do you say dd() is not helpful?

Jun
27
1 month ago
Activity icon

Awarded Best Reply on How To Send Email From A Specific User To Someone.

You could simply do Mail::to($whateverEmail)->send();. To do this the contact seller button would have to be form submit button and you could pass in possibly a hidden field with the seller id or some other property to be able to fetch which reseller is from your database. So with the endpoint that you would set up to receive that incoming request you could retrieve that value and then do Model::find($ifValueIsId) OR Model::where('field', $value)->first() and then use the $model->email inside of the to method on the Mail Facade.

Activity icon

Replied to How To Send Email From A Specific User To Someone.

You could simply do Mail::to($whateverEmail)->send();. To do this the contact seller button would have to be form submit button and you could pass in possibly a hidden field with the seller id or some other property to be able to fetch which reseller is from your database. So with the endpoint that you would set up to receive that incoming request you could retrieve that value and then do Model::find($ifValueIsId) OR Model::where('field', $value)->first() and then use the $model->email inside of the to method on the Mail Facade.

Jun
21
1 month ago
Activity icon

Replied to Class Based Factories

It creates a new activation record so in this case it would create an activation for the team and each of the players for the team.

Activity icon

Started a new Conversation Class Based Factories

I'm working with Christoph Rumpel's Laravel-Factories-Reloaded package which is a class based factories package. Inside of my TeamFactory class I am trying to create 9 players that will also have the playable method attached to each of them. Each player needs to have the same activationFactory applied as the team has.

$team = TeamFactory::new()->playable()->create();

TeamFactory


public function playable(ActivationFactory $activationFactory = null): TeamFactory
    {
        $clone = tap(clone $this)->overwriteDefaults([
            'status' => TeamStatus::PLAYABLE,
        ]);

        $clone = $clone->activated($activationFactory ?? $this->activationFactory);

        $clone->playerFactory = PlayerFactory::new()
            ->playable($activationFactory ?? $this->activationFactory)
            ->times(9);

        return $clone;
    }

public function activated(ActivationFactory $activationFactory = null)
    {
        $clone = clone $this;

        $clone->activationFactory = $activationFactory ?? ActivationFactory::new();

        return $clone;
    }
Jun
18
1 month ago
Activity icon

Started a new Conversation Validated Except For User Creation

I have a situation where I am attempting to create a model-based off request data that gets validated however I have an after validated hook in my request class that merges a new field and removes two existing fields from the request.

The problem I'm facing is that I created a validatedExcept method that will pass in all the validated data except for any specific fields. When I do this for the model creation below its still using the validated fields which makes sense. For example its still trying to send through feet and inches instead of height, since height is what is the name of the property for the patient. I just don't know what to do here.

Is there any other suggestion of handling the code below from my model creation other than having to write out $request->only(['fields-to-send-through'])

// Uses StoreReqeust from Patients namespace
$user = User::create($request->validatedExcept('started_at'));
<?php

namespace App\Http\Requests\Patients;

use App\Models\Patient;
use Illuminate\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->user()->can('create', Patient::class);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => [
                'required',
                'string',
                'min:3'
            ],
            'feet' => [
                'required',
                'integer',
                'min:5',
                'max:7'
            ],
            'inches' => [
                'required',
                'integer',
                'max:11'
            ],
            'weight' => [
                'required',
                'integer'
            ],
            'started_at' => [
                'nullable',
                'string',
                'date_format:Y-m-d H:i:s'
            ],
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'started_at' => 'date started',
        ];
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if ($validator->errors()->isEmpty()) {
                $this->merge(['height' => ($this->input('feet') * 12) + $this->input('inches')]);
                $this->offsetUnset('feet');
                $this->offsetUnset('inches');
            }
        });
    }
}

Jun
01
2 months ago
Activity icon

Commented on Flash Component

This is where I need further understanding. I need to understand when to include the message as a prop or what is inside the slot.

May
10
2 months ago
Activity icon

Replied to Mocking Authorization Can Method

No worries. If you find something that solves this issue, reply back.

Activity icon

Replied to Mocking Authorization Can Method

I'm still working on it but I'm closer. I'm going to try and figure this out as if I am not trying to get the venue from the route first. This way I can just test that it calls the update method off of the VenuePolicy.

Activity icon

Replied to Mocking Authorization Can Method

@drewdan It's coming back null because I don't have it set up to make the venue be an instance of a Venue through the requested route. Ah, that would make sense.

I just need to figure out how to set it up as an instance as that.

Activity icon

Replied to Mocking Authorization Can Method

I've never seen offsetSet before. The only methods I've seen before off of the app() helper is bind and instance. I've updated my test to the following which should pass but says the authorize returns false for some reason.

/** @test */
public function authorized_returns_true_when_authenticated_user_can_update_venue()
{
    $user = UserFactory::new()->make();

    $this->actingAs($user);

    $mock = $this->mock(VenuePolicy::class)->makePartial()->shouldReceive('update')->andReturn(true)->getMock();
    app()->offsetSet(VenuePolicy::class, $mock);

    $subject = new UpdateRequest();

    $this->assertTrue($subject->authorize());
}
Activity icon

Replied to Mocking Authorization Can Method

Can we not pull it out of the container with $this->app? I don't really know much about this and just asking questions based on your responses.

Activity icon

Replied to Mocking Authorization Can Method

@drewdan It appears it shoudl work and fixes the error I was getting however no idea why I'm getting the failure of the assertion. It says the asserion is coming out False instead of True.

 /** @test */
    public function authorized_returns_true_when_authenticated_user_can_update_venue()
    {
        $user = UserFactory::new()->make();

        $this->actingAs($user);

        $subject = new UpdateRequest();

        $this->mock(VenuePolicy::class)->shouldReceive('update')->andReturn(true);

        $this->assertTrue($subject->authorize());
    }
public function authorize()
    {
        $venue = $this->route('venue');

        if (! Auth::check()) {
            return false;
        }

        return Auth::user()->can('update', $venue);
    }
Activity icon

Replied to Mocking Authorization Can Method

@drewdan I see there are two authorizabletraits. One fromIlluminate\Foundation\Auth\Access;and another fromIlluminate\Contracts\Auth\Access`

Activity icon

Replied to Mocking Authorization Can Method

@drewdan I'm confused then. I"m trying to test that the the authorize method has a call to a specific method on a policy.

Activity icon

Replied to Mocking Authorization Can Method

I've updated my test and the actual request class to have the following, however, I'm receiving the following error stack.

Illegal offset type in isset or empty

  at vendor/laravel/framework/src/Illuminate/Container/Container.php:435
    431|      * @return void
    432|      */
    433|     protected function removeAbstractAlias($searched)
    434|     {
  > 435|         if (! isset($this->aliases[$searched])) {
    436|             return;
    437|         }
    438| 
    439|         foreach ($this->abstractAliases as $abstract => $aliases) {

      +2 vendor frames 
  3   tests/Unit/Http/Requests/Venues/UpdateRequestTest.php:60
      Illuminate\Foundation\Testing\TestCase::mock(Object(Tests\Unit\Http\Requests\Venues\UpdateRequestTest))
$this->mock($loggedInUser)->shouldReceive('can')->withArgs(['update', $user])->andReturn(true);
return Auth::user()->can('update', $venue);
Activity icon

Replied to Mocking Authorization Can Method

Is there a way I can do the partial mock of just saying that when it hits that can method that it will have a arg of update and return true?

Activity icon

Replied to Mocking Authorization Can Method

What I'm wanting to make sure is that it checks that the authenticated user has a call to the can method with the update parameter so that I can check the policy method separately.

Activity icon

Replied to Mocking Authorization Can Method

Possibly but I'm still a beginner in Mockery. So I don't know what all I can take advantage of with partial mocks.

Activity icon

Replied to Mocking Authorization Can Method

Which doesn't make sense because I'm logged in a user.

Activity icon

Replied to Mocking Authorization Can Method

Its saying that $this->user() is null

Activity icon

Replied to Mocking Authorization Can Method

Does anyone have any suggestions on what I'm doing wrong in my test?

May
09
3 months ago
Activity icon

Replied to Error In Using Laravel 7 Component Function As Variable.

Well it says $client is an object so you would have to do $client->name

Activity icon

Started a new Conversation Mocking Authorization Can Method

I'm trying to unit test a form request class authorize method which I've included below. I'm wanting to do it this way so that I can check the policy update method separately and that way I know that what comes out of there is based on the user role and such. Does anyone see anything wrong with doing it in this manner? Also am I mocking the correct class here?

public function authorized_returns_true_when_authenticated_user_can_update_venue()
{
    $user = UserFactory::new()->make();

    $loggedInUser = $this->actingAs($user);

    Mockery::mock($loggedInUser)->shouldReceive('can')->withArgs(['update', $user])->andReturn(true);

    $subject = new UpdateRequest();

    $this->assertFalse($subject->authorize());
}
public function authorize()
{
    $venue = $this->route('venue');

    if (! Auth::check()) {
        return false;
    }

    return $this->user()->can('update', $venue);
}
May
05
3 months ago
Activity icon

Replied to Generating Test With Mocking Query

@bugsysha This is true however what I"m trying to do is test that there are 3 different components with different data associated with those 3 different components. All 3 components return 3 different collections back to its associated view.

May
02
3 months ago
Activity icon

Replied to Very Hard An About Laravel Project ?

My initial thought is just send a message to the Log. You didn't give enough information on what you are wanting to do with the information. Are you needing to store it in the database?

Activity icon

Replied to Generating Test With Mocking Query

I'm wanting to test that this specific component is running a speciific query for the component.

Activity icon

Replied to Generating Test With Mocking Query

I think this is better fit for a feature test which is not the type of test I'm trying to do.

Activity icon

Replied to Generating Test With Mocking Query

So that works with the Livewire component?

Activity icon

Replied to Eloquent Search

Spatie has a package you could look into using. Just a suggestion.

https://github.com/spatie/laravel-query-builder

Activity icon

Replied to Eloquent Search

Get rid of temporary variables. If having long lines is a problem then you can make each perameter of the methods a separate line.

Activity icon

Replied to Generating Test With Mocking Query

@bugsysha I'm trying to figure out how I can test to make sure the right query is being ran inside of the component.

Activity icon

Started a new Conversation Generating Test With Mocking Query

I have the main feature request test partly written. On my users.index page it renders 3 different Livewire components that are paginated user datatables. One for active, one for inactive, and unactivated. I'm wanting to test each individual Livewire component.

The problem I'm having is that I was trying to run a query inside of the test and make sure I return the right data. The query is the same as the one inside the active users component but I want to make sure that it looks to make sure the right methods are being called because the test could change and the right data could still be returned isn't testing that the same query runs inside of the component.

I think I need mockery for this situation but not 100% sure. What does anyone else think?

<?php

namespace Tests\Feature\Users;

use App\Enums\Role;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ViewUsersListSuccessConditionsTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function an_administrator_can_view_users_page()
    {
        $this->actAs(Role::ADMINISTRATOR);

        $response = $this->indexRequest('users');

        $response->assertOk();
        $response->assertViewIs('users.index');
    }
}
<?php

namespace App\Http\Livewire\Titles;

use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;

class ActiveUsers extends Component
{
    use WithPagination;

    public $perPage = 10;

    public function render()
    {
        return view('livewire.users.active-users', [
            'activeUsers' => User::active()->paginate($this->perPage)
        ]);
    }
}
<?php

namespace Tests\Integration\Livewire\Users;

use App\Http\Livewire\Users\ActiveUsers;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\Factories\UserFactory;
use Tests\TestCase;

class ActiveUsersTest extends TestCase
{
    use RefreshDatabase;

    /** @var \Illuminate\Support\Collection */
    protected $users;

    protected function setUp(): void
    {
        parent::setUp();

        $active = UserFactory::new()->count(3)->active()->create();
        $unactivated = UserFactory::new()->count(3)->unactivated()->create();
        $inactive = UserFactory::new()->count(3)->inactive()->create();

        $this->users = collect([
            'active'            => $active,
            'unactivated'       => $unactivated,
            'inactive'          => $inactive,
            'all'               => collect()
                                    ->concat($active)
                                    ->concat($unactivated)
                                    ->concat($inactive)
        ]);
    }

    /** @test */
    public function active_users_component_should_return_correct_view()
    {
        $component = Livewire::test(ActiveUsers::class);

        $this->assertEquals(
            'livewire.users.active-users',
            $component->lastRenderedView->getName()
        );
    }

    /** @test */
    public function active_users_component_should_pass_correct_data()
    {
        $component = Livewire::test(ActiveUsers::class);

        $mockUser
            ->shouldReceive('active')
            ->once()
            ->shouldReceive('paginate')
            ->once()
            ->andReturn($this->users->get(['active']));


        // Same query ran in livewire component
        $activeUsers = User::active()->get();

        $component->assertViewHas('activeUsers');
        $this->assertCount(3, $activeUsers);

        //  Not actually testing related to the component 
        // but the query results itself.
        $this->assertEquals(
            $this->users->get('active')->pluck('id')->toArray(),
            $activeUsers->pluck('id')->sort()->values()->toArray()
        );
    }
}
Apr
26
3 months ago
Activity icon

Replied to Seeding With Carbon Dates

@bobbybouwmann That works great. Thank you.

Activity icon

Replied to Seeding With Carbon Dates

@bobbybouwmann Can I do that with the $-i++?

Activity icon

Replied to Seeding With Carbon Dates

@bobbybouwmann Well my goal is to create 30 players 5 years ago and then every following month create 5 more players all with a started and end date for their employment. The only thing I want to make sure is that if the calculated random number of years employed added to their started at date is in the future then it should not have a ended at date.

Activity icon

Replied to Seeding With Carbon Dates

@bobbybouwmann So to me that would mean this below? Woulnd't that always be true?

if ($started < $i + $started->copy()->addMonth(rand(1,11))
Apr
25
3 months ago
Activity icon

Replied to Seeding With Carbon Dates

My end goal is to combine both of these loops somehow so that it can better handle creating the right amount of players and know what their started and ended dates should be correctly.

/**
 * We need to create 30 players at this time X years ago but since by
 * the time we reach the current date these players should be
 * released so we need to make them released and figure out
 * their started and ended employment date.
 */
for ($j = 1; $j <= 30; $j++) {
    $started = $dateToStart;
    $ended = now()->subYears($randomNumberOfYearsEmployed)->subMonths(rand(1, 11));
    PlayerFactory::new()
        ->released(
            EmploymentFactory::new()
                ->started($started)
                ->ended($ended)
        )
        ->create(['name' => 'Player '.$eNum]);

    $eNum ++;
}

/**
 * We need to create 5 players at this time x years ago for each
 * additional month but since by the time we reach the current
 * date these players should be released so we need to
 * make them released and figure out their started
 * and ended employment date.
 * FIXME: Please!
 */
for ($i = 1; $i <= 12*$diffInYears; $i++) {
    for ($j = 1; $j <= 5; $j++) {
        $started =  $dateToStart->copy()->addMonth($i);
        $ended =  $started->copy()->addMonth(rand(1, 11));
        PlayerFactory::new()
            ->released(
                EmploymentFactory::new()
                    ->started($started)
                    ->ended($ended)
            )
            ->create(['name' => 'Player '.$eNum]);

        $eNum ++;
    }
}
Activity icon

Replied to Seeding With Carbon Dates

@bobbybouwmann This works amazingly better, however, the ended at date will eventually hit a date where its the current date or later. This is not the desired result.

/**
* We need to create 5 players at this time x years ago for each
* additional month but since by the time we reach the current
* date these players should be released so we need to
* make them released and figure out their started
* and ended employment date.
*/
for ($i = 1; $i <= 12*$diffInYears; $i++) {
    for ($j = 1; $j <= 5; $j++) {
        $startDate =  $dateToStart->copy()->addMonth($i);
        $endDate =  $startDate->copy()->addMonth(rand(1, 11));
        PlayerFactory::new()
            ->released(
                EmploymentFactory::new()
                    ->started($startDate)
                    ->ended($endDate)
            )
            ->create(['name' => 'Player '.$eNum]);

        $eNum ++;
    }
}