xtremer360

xtremer360

Member Since 4 Years Ago

Kissimmee, FL

Full Stack Developer at 321

Experience Points 140,275
Experience Level 29

4,725 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 1060
Lessons
Completed
Best Reply Awards 9
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

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

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

19 Apr
1 week ago

xtremer360 left a reply on Theme Assets To Compile With Mix

@ashraam How should I handle the Mix side of things?

xtremer360 started a new conversation Theme Assets To Compile With Mix

I have just recently purchased a new theme to brand with my application and I am trying to consider the best way to go about storing the assets that are needed to make the theme work. There are vendor specific assets as well as theme specific assets. My plan is to then decide if I'm going to just add all files into one file or try and create a vendor compiled script or what not.

Any suggestions on what I should do?

17 Apr
1 week ago

xtremer360 left a reply on Checking Keys For An Associate Array Form Request

Below I have included my request data as well as the request class for validating the request. I have also included the custom validation rule. I have included the bail in what I think is the correct location however it's still giving me an error because it's saying that the following.

+exception: ErrorException {#4160
      #message: "Trying to get property 'number_of_sides' of non-object"
      #code: 0
      #file: "./app/Rules/CorrectMatchSidesCount.php"
}
array:1 [
  "matches" => array:1 [
    0 => array:3 [
      "match_type_id" => null
      "competitors" => array:2 [
        0 => array:1 [
          "wrestlers" => array:1 [
            0 => 1
          ]
        ]
        1 => array:1 [
          "wrestlers" => array:1 [
            0 => 2
          ]
        ]
      ]
      "preview" => "This is an example match preview."
    ]
  ]
]
<?php

namespace App\Http\Requests;

use App\Models\MatchType;
use App\Rules\CorrectMatchSidesCount;
use Illuminate\Foundation\Http\FormRequest;

class StoreMatchesRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $event = $this->route('event');

        return $this->user()->can('addMatches', $event);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'matches' => ['required', 'array', 'min:1'],
            'matches.*' => ['required', 'array'],
            'matches.*.match_type_id' => ['bail', 'required', 'integer', 'exists:match_types,id'],
            'matches.*.competitors' => ['required', 'array'],
            'matches.*.competitors.*.wrestlers' => ['required_without:matches.*.competitors.*.tagteams', 'array'],
            'matches.*.competitors.*.wrestlers.*' => ['required_with:matches.*.competitors.*.wrestlers', 'integer', 'exists:wrestlers,id'],
            'matches.*.competitors.*.tagteams' => ['required_without:matches.*.competitors.*.wrestlers', 'array'],
            'matches.*.competitors.*.tagteams.*' => ['required_with:matches.*.competitors.*.tagteams', 'integer', 'exists:tagteams,id'],
            'matches.*.preview' => ['required', 'string'],
            'matches.*' => [new CorrectMatchSidesCount],
        ];

        return $rules;
    }
}

16 Apr
1 week ago

xtremer360 left a reply on Checking Keys For An Associate Array Form Request

Is it possible to do this?

xtremer360 left a reply on Checking Keys For An Associate Array Form Request

@martinbean The only problem with that is there a way to apply an additional validation rule by attaching a custom Rule to a field. What I mean is for the CorrectMatchSIdesCount rule I need that to be executed only when match_type_id field passes because it has to pass. before the rule can work as expected.

14 Apr
1 week ago

xtremer360 left a reply on Checking Keys For An Associate Array Form Request

@martinbean @mvd I added the following validation rules however I"m trying to figure out I can have the CorrectMatchSidesCount validation rule be run only when all validation has passed because it requires a valid match type to work correctly

'matches' => ['required', 'array', 'min:1'],
'matches.*' => ['required', 'array'],
'matches.*.match_type_id' => ['required', 'int', 'exists:match_types,id'],
'matches.*.competitors' => ['required', 'array'],
'matches.*.competitors.*.wrestlers' => ['required_without:matches.*.competitors.*.tagteams', 'array'],
'matches.*.competitors.*.wrestlers.*' => ['required_with:matches.*.competitors.*.wrestlers', 'int', 'exists:wrestlers,id'],
'matches.*.competitors.*.tagteams' => ['required_without:matches.*.competitors.*.wrestlers', 'array'],
'matches.*.competitors.*.tagteams.*' => ['required_with:matches.*.competitors.*.tagteams', 'int', 'exists:tagteams,id'],
'matches.*.preview' => ['required', 'string'],
'matches.*' => [new CorrectMatchSidesCount],
13 Apr
1 week ago

xtremer360 left a reply on Adding Custom Rule To After Validation Hook In Custom Request Class

This is two fields that have validation rules attached. For the custom rule class must have the match_type_id field completely validate before it can be checked.

'matches.*.match_type_id' => ['required', 'int', 'exists:match_types,id'],
'matches.*' => [new CorrectMatchSidesCount], 
11 Apr
2 weeks ago

xtremer360 left a reply on Checking Keys For An Associate Array Form Request

@mvd These are the rules that I am wanting to apply to my request. Some of them are covered however some ar not due to having the after validation hook. I'm thinking that some of the code that is inside of the after validation is for validation so I need to figure out how I can do some of the logic needed in the regular rules array.

If you are willing to take a look at the below rules and see what you can suggest.

  1. Matches are required and must be an array and minimum size of 1.
  2. Each match must be an array and must contain a match_type_id, competitors, and preview.
  3. Match type must is required, must be an integer, and must exist in the match_types table.
  4. Competitors are required, must be an array and the size of the array must equal the value of the Match Type number_of_sides property that was provided after the match type is found.
  5. Each competitors side must have a valid key of either wrestlers or tagteams.
  6. Each of those competitor types if present must be an array.
  7. Each competitor in the competitor types arrays and will each have an integer and exists rule for their respective database tables.
10 Apr
2 weeks ago

xtremer360 started a new conversation Checking Keys For An Associate Array Form Request

What I'm trying to do is check that all the keys that get passed inside of the competitors array are valid keys. What should be accepted is wrestlers for now but I know that will change later on. Does anyone have a better way to write that check what is valid?

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreMatchesRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'matches' => ['required', 'array'],
            'matches.*' => ['required', 'array'],
            'matches.*.competitors' => ['required', 'array'],
            'matches.*.competitors.*' => ['required', 'array'],
        ];

        return $rules;
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            foreach ($this->matches as $key => $match) {
                $type = MatchType::find($match['match_type_id']);

                if ($type === null) {
                    continue;
                }

                if ($match['competitors'] === null || !is_array($match['competitors'])) {
                    continue;
                }

                foreach ($match['competitors'] as $side => $competitorType) {
                    if (array_intersect(array_keys($competitorType), ['wrestlers']) !== array_keys($competitorType)) {
                        $validator->errors()->add("matches.{$key}.competitors.*", 'Something is wrong with this field!');
                    }
                }

                if (!$this->matchHasCorrectSidesCount($match, $type)) {
                    $validator->errors()->add("matches.{$key}.competitors", 'Something is wrong with this field!');
                }

                if (!$this->matchHasCorrectCompetitorCount) {
                    $validator->errors()->add("matches.{$key}.competitors", 'Something is wrong with this field!');
                }
            }
        });
    }
}

08 Apr
2 weeks ago

xtremer360 started a new conversation Adding Custom Rule To After Validation Hook In Custom Request Class

Can someone tell me how I can apply the CorrectCompetitorCount to an input array field?

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        // return CorrectCompetitorCount();          
    });
}
03 Apr
3 weeks ago

xtremer360 left a reply on Validation Rule For An Array Key

Is there anyone that has had to check keys of a post array?

xtremer360 started a new conversation Size Validation Rule On Array Based On Other Field

I'm running into a situation where I have two fields where one needs to be completely validated before it can proceed to the second field. The reasoning is due to using the value of field1 to retrieve a property off of a Model that would be used for field2's validation. I'm doing the following validation in a form request class.

My question is what can I do so that I can take care of the size rule after regular validation of the two fields are successful?

$sizeNeeded = Model::where($this->input('field1_id')->first()->number_of_sides;

'field1' => ['required', 'integer', 'exists: tablename, id'],
'field2' => ['required', 'array', 'size:'.$sizeNeeded],
02 Apr
3 weeks ago

xtremer360 left a reply on Duplication On Merged Inner Arrays

How can I do that for my request validation?

xtremer360 started a new conversation Duplication On Merged Inner Arrays

I'm trying to figure out how I can validate that there is not a duplicate value for group1 that is inside of mainArray. So it would match all of the groups that would be inside of mainArray and if there are duplicates then error.

Any idea how to do that?

mainArray [
    'subArray1' = [
        'group1' => [1,2,3],
    ],
        'subArray2' => [
        'group1' => [1,4,5]
    ]
]

xtremer360 left a reply on Attaching A Polymorphic Many-to-Many Relationship

Well if I do make that change, then, in my response there is no error however if I try and do this then I get the following error.

tap($event->fresh()->matches->first(), function ($match) {
    dd($match->competitors);
});
General error: 1 ambiguous column name: main.match_competitors.id (SQL: select "match_competitors".*, "match_competitors"."match_id" as "pivot_match_id", "match_competitors"."competitor_id" as "pivot_competitor_id", "match_competitors"."competitor_type" as "pivot_competitor_type" from "match_competitors" inner join "match_competitors" on "match_competitors"."id" = "match_competitors"."competitor_id" where "match_competitors"."match_id" = 1 and "match_competitors"."competitor_type" = App\Models\MatchCompetitor)
01 Apr
3 weeks ago

xtremer360 started a new conversation Attaching A Polymorphic Many-to-Many Relationship

I have a Match model and a MatchCompetitor model. The MatchCompetitor model is the associated model for the match_competitors table with fields match_id, competitor_type, competitor_id, and side_number. For the Match model, I have the following relationship defined. However, when I'm trying to save competitors it is not saving the match_id.

public function competitors()
{
    return $this->morphToMany(MatchCompetitor::class, 'competitor', 'match_competitors', null, 'competitor_id');
}
$matchObject->competitors()->attach($player1, ['side_number' => $sideNumber]);

I'm getting the dreaded Not Null constraint failed but it should be applying the match_id through the relationship.

30 Mar
3 weeks ago

xtremer360 started a new conversation Validation Rule For An Array Key

I'm trying to figure out what I would do for a validation rule so that type2 cannot be in any of the groups of students. I know of the Rule::In but not sure how I can validate against a key.

'courses.*.students.*.*' => [Rule::in(['type2'])],

Can someone tell me what I'm doing wrong?

array:1 [
  "courses" => array:1 [
      1 => array:3 [
      "teacher_id" => 1
      "students" => array:2 [
        0 => array:2 [
          "type1" => array:1 [
            0 => 1
          ]
          "type2" => array:1 [
            0 => 1
          ]
        ]
        1 => array:1 [
          "type1" => array:1 [
            0 => 2
          ]
        ]
      ]
      "preview" => "This is an example match preview."
    ]
  ]
]
29 Mar
4 weeks ago

xtremer360 started a new conversation AssertStringNotContainsString() Error After Composer Update

I had run composer update and now when I use assertSee and assertDontSee then I get the error message provided below. Is this something anyone has encountered recently?

/** @test */
    public function an_administrator_can_view_all_archived_events()
    {
        $this->actAs('administrator');
        $archivedEvents = factory(Event::class, 3)->states('archived')->create();
        $scheduledEvent = factory(Event::class)->states('scheduled')->create();

        $response = $this->get(route('events.index', ['state' => 'archived']));
        dd($archivedEvents[0]->name);
        $response->assertOk();
        $response->assertSee(e($archivedEvents[0]->name));
        $response->assertSee(e($archivedEvents[1]->name));
        $response->assertSee(e($archivedEvents[2]->name));
        $response->assertDontSee(e($scheduledEvent->name));
    }
Error: Call to undefined method Illuminate\Foundation\Testing\Assert::assertStringNotContainsString()
20 Mar
1 month ago

xtremer360 left a reply on Morph One With View Specific

Is there something I should do with the code that is specific to a passage view?

$wrappedContent = wordwrap($type->text, 50, "\r\n");
$explodedLines = explode("\r\n", $wrappedContent);

$lineNumbers = count($explodedLines);
19 Mar
1 month ago

xtremer360 left a reply on Morph One With View Specific

@martinbean Thanks for your response. Well inside of my quizzes.show I have this. So I'm trying to load a dynamic blade file. Reason being the only difference is the content per type. So is the way I am currently trying to do this with the blade views is wrong?

@extends('layouts.passage')

@section('pageTitle', $quiz->title)

@section('content')

    <div id="passage-container" class="container">
        <div id="passage-row" class="row no-gutters">
            <div class="col-lg-6 passage-col mb-5 mb-lg-0">
                <div class="scroll">
                    <div class="passage p-5">
                        <h1 class="h5 text-center mb-5">
                            {{$quiz->title}}
                        </h1>
                        <div class="wrap">
                            @include('quizzes.types'.$type)
                        </div><!-- wrap -->
                    </div><!-- padding -->
                </div><!-- scroll -->
            </div>
            <div class="col-lg-6 passage-col">
                <div class="scroll">
                    <div class="p-5">
                        <quiz-questions id="{{$quiz->id}}"></quiz-questions>
                    </div><!-- padding -->
                </div><!-- scroll -->
            </div>
        </div>
    </div>


@endsection

passage.blade.php

@if( $quiz->id !== 1 )
    <div class="line-numbers">
        @for( $i=1; $i<$lineNumbers; $i++ )
            <span class="{{ ( $i === 4 ) ? 'line' : ''  }}">{{ ( $i === 4 ) ? 'Line' : $i  }}</span>
        @endfor
    </div>
@endif
<div class="passage-text">
    {!!$passage->text!!}
</div><!-- passage text -->

xtremer360 started a new conversation Morph One With View Specific

I'm trying to figure out how I can implement a morphOne specific view based on the type of quiz it trying to be shown.

Is there a better way to go about this?

public function show(Request $request, Quiz $quiz)
    {
        $type = $quiz->quizzable;

        switch($type->getMorphClass()) {
            case 'App\Models\Passage':
                $wrappedContent = wordwrap($type->text, 50, "\r\n");
                $explodedLines = explode("\r\n", $wrappedContent);

                $lineNumbers = count($explodedLines);
        }

        $questions = $quiz->questions->load('choices');
        $question = $quiz->questions->first();
        $total = $questions->count();
        $data = ['passage' => $passage, 'total' => $total, 'questions' => $questions];

        if ($request->ajax()) {
            return response()->json($data);
        }

        return view('quizzes.show', compact('questions', 'quiz', 'type', 'lineNumbers'));
    }
15 Mar
1 month ago

xtremer360 started a new conversation Logging In User Types

I have a single sign-in route that is reachable by any of three user types. A teacher, student, admin. I have a User model, Student, and Teacher models with users, teachers, and students tables. Both the teacher's table and students table has a user_id. We are also using the Spatie role and permissions package. What I’m wanting to do is fix my actAs() method so that it can log in a new model based on the state I pass in. Suggestions on what I should do so that I can make sure I'm logging in a student or a teacher or admin.

/**
     * Creates a user with a given state and logs them into the system.
     *
     * @param  array  $states
     * @param  array  $attributes
     * @return \App\Models\User  $user
     */
    public function actAs($states = [], $attributes = [])
    {
        $user = ($states instanceof User) ? $states : factory(User::class)->states($states)->create($attributes);
        $this->actingAs($user);

        return $user;
    }
10 Mar
1 month ago
09 Mar
1 month ago

xtremer360 started a new conversation Assertions With Datetime Of MorphByMany Relationships

Hi all. I'm trying to figure out what my assertion would look like for test below.

Currently, my Stable factory when created will create a default wrestler for its group. As you can see with the test below after the wrestler is created for the stable I am retrieving the current wrestler(s) for the stable. The reason for the ->whereNull('left_at') constraint is because I need to constrain it to wrestlers that are currently in the stable. Then after that line, I am creating two new stable wrestlers to join the stable.

I run the patch request to the update method for a stable and pass along an array of ids of the new wrestlers to join the stable. In the update method, I have also provided I am trying to update the current collection of wrestlers in the stable as who was passed in and marking those wrestlers that were previously in the stable as having left the stable.

What I am wanting to achieve is with my assertion try and test that those wrestlers that are no longer in the stable as having left. What is making this difficult is because if this isn't the first time a wrestler doesn't join and leave the stable. I don't want it updating that first occurrence with the current date timestamp.

Any suggestions on how I should construct my assertion? Also, any suggestions on how I could refactor to hiding some of the controller code behind a method or two as that is a practice I subscribe to. Hiding eloquent calls to the models responsible.

/** @test */
    public function wrestlers_in_a_stable_that_are_not_included_request_are_marked_as_left()
    {
        $this->actAs('administrator');
        $stable = factory(Stable::class)->create();
        $formerWrestlers = $stable->wrestlers()->whereNull('left_at')->get();
        $newStableWrestlers = factory(Wrestler::class, 2)->create();

        $response = $this->patch(route('stables.update', $stable), $this->validParams([
            'wrestlers' => $newStableWrestlers->modelKeys(),
        ]));

        tap($stable->fresh()->wrestlers()->whereNull('left_at')->get(), function ($stableWrestlers) use ($formerWrestlers) {
            $this->assertEquals($stableWrestlers->modelKeys(), $formerWrestlers->modelKeys());
        });
    }
public function update(UpdateStableRequest $request, Stable $stable)
    {
        $stable->update($request->except('wrestlers', 'tagteams'));

        $newStableWrestlers = $request->input('wrestlers');
        $newStableTagTeams = $request->input('tagteams');

        $currentStableWrestlers = $stable->wrestlers()->whereNull('left_at')->get()->pluck('id');
        $currentStableTagTeams = $stable->tagteams()->whereNull('left_at')->get()->pluck('id');

        $formerStableWrestlers = $currentStableWrestlers->diff(collect($newStableWrestlers));
        $formerStableTagTeams = $currentStableTagTeams->diff(collect($newStableTagTeams));

        $stable->wrestlers()->updateExistingPivot($formerStableWrestlers, ['left_at' => now()]);
        $stable->tagteams()->updateExistingPivot($formerStableTagTeams, ['left_at' => now()]);

        $stable->wrestlers()->syncWithoutDetaching($newStableWrestlers);
        $stable->tagteams()->syncWithoutDetaching($newStableTagTeams);

        return redirect()->route('stables.index');
    }
// Stable Model
/**
     * Get all wrestlers that have been members of the stable.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
     */
    public function wrestlers()
    {
        return $this->morphedByMany(Wrestler::class, 'member');
    }
03 Mar
1 month ago

xtremer360 left a reply on Where Clauses For Existing

Maybe doing something like this is closer I don't know but the query is still not working correctly. I'm wanting to make sure $modelA is not included in any other active groups other than the group that is passed in. I am not sure if whereDoesntHave is the right method to call on the model.

The error I am getting is from adding onto the query with isActive() where isActive is a method on the group model.

if (! $modelA->whereDoesntHas('groups', function ($query) {
    $query->isActive();
})->whereNotIn([$this->group->id])) {
            return false;
}
02 Mar
1 month ago

xtremer360 left a reply on Where Clauses For Existing

Does this help explain to anyone?

xtremer360 left a reply on Get The Distance Between Two Times

I think there is a diff() method for Carbon instances that is made public.

xtremer360 left a reply on Where Clauses For Existing

I don't know if whereHas is what I should use because I want to make sure that the model is not apart of any other active groups other than the current group they are in.

Following code comes from a custom Rule class with passing in a group inside to the constructor.

if (! $modelA->whereHas('groups', function ($query) {
    $query->isActive();
})) {
    return false;
}

xtremer360 left a reply on Where Clauses For Existing

I think I need whereHas but I don't even see it in the docs.

xtremer360 left a reply on Where Clauses For Existing

Is contains the best to use here or would whereHas be better?

xtremer360 started a new conversation Where Clauses For Existing

I have trying to come up with an eloquent query where it checks to make sure that a model is not associated to an additional group entity that is active other than the one past in.

ModelA is apart of Group1 and that group is active.

I want to do a check to make sure ModelA is not apart of another GroupB which is active as well.

The following isn't right because I can't use where on boolean. Anyone know what I should do for this query.

$modelA->groups->contains($this->group)->where()->isActive().
27 Feb
1 month ago

xtremer360 left a reply on Use ->update() Without Updating Timestamps

That would mean that on your post table migration you do not have an updated_at column. Can you share with us your migration file?

26 Feb
2 months ago

xtremer360 left a reply on Array Validation Rules Based Off Sizes

@gertjanroke I took a look at the documentation and put this together however I question how to add the conditions of the sizes of the arrays.

'array1' => Rule::requiredIf(function () {
    return count($this->array2) <= 1;
}),
'array1' => ['required', 'array', 'size:2'],
'array2' => Rule::requiredIf(function () {
    return count($this->array1) <= 2;
}),
'array2' => ['required', 'array', 'size:2'],

xtremer360 left a reply on Array Validation Rules Based Off Sizes

Does anyone have any ideas or is this way too complex?

xtremer360 started a new conversation Array Validation Rules Based Off Sizes

I have two arrays in my request.

Array1 is required if array2 has a size of 1 or 0. If array2 has 0 in its size then array1 must have at least 3 in its size. If array2 has 1 as its size then array1 must have at least 1 as its size.

For array2 is required if array1 has a size of less than 3. If array1 has a size of 0 then array2 must have a size of 2. If array1 has a size of 1 or 2 then array2 must have a minimum size of 1.

array1' => ['required', 'array', 'size:2'],
'array1.*' => ['bail', 'integer', new CanJoinTeam],
'array2' => ['required', 'array', 'size:2'],
'array2.*' => ['bail', 'integer', new CanJoinTeam,```
21 Feb
2 months ago

xtremer360 left a reply on Interfaces And Parent Controllers

Think of Model as just an Entity just to protect my application specific names. I do have the Suspendable Interface.

xtremer360 started a new conversation Interfaces And Parent Controllers

I have the following files and wondered if anyone had any suggestions on what to do because I have a test that isn't passing but I need to make sure that I am doing the right thing to get this to work.

Currently my error is this.

ErrorException: Declaration of App\Http\Controllers\ResourceOneSuspensionsController::store(App\Model, $model) should be compatible with App\Http\Controllers\Suspensi
onsController::store($suspendee)
\App\Controllers\SuspensionsController
\App\Controllers\ResourceOneSuspensionsController
\App\Controllers\ResourceTwoSuspensionsController
\App\Controllers\ResourceThreeSuspensionsController
\App\Controllers\ResourceFourSuspensionsController
<?php

namespace App\Http\Controllers;

use App\Interfaces\Suspendable;

class SuspensionsController extends Controller
{
    /**
     * Suspend a model.
     *
     * @param  \App\Interfaces\Suspendable  $suspendee
     * @return \lluminate\Http\RedirectResponse
     */
    public function store($suspendee)
    {
        $this->authorize('suspend', $suspendee);

        abort_if($suspendee->isSuspended(), 403);

        $suspendee->suspend();

        $route = Str::plural($suspendee->getRouteKeyName());

        return redirect()->route("{$route}.index", ['state' => 'suspended']);
    }
}
<?php

namespace App\Http\Controllers;

use App\Model;
use Illuminate\Http\Request;

class ResourceOneSuspensionsController extends SuspensionsController
{
    public function store(Model $model)
    {
        return parent::store($model);
    }

    public function destroy(Model $model)
    {
        return parent::destroy($model);
    }
}
29 Jan
2 months ago

xtremer360 left a reply on Disable Exception Handling In Laravel Tests

Try

$this->withoutExceptionHandling();
28 Jan
2 months ago

xtremer360 left a reply on Manually Adding Users In Code?

  1. Why are you needing to remove the token?
  2. You can move the password to a mutator on the User class.
  3. I would rename the variable returned from the User::create() to $user. This way at the bottom when you give the user the role you can have it read as $user->giveRoleTo($role) or I would even make it $user->giveRole($role).
  4. I would create default roles and then retrieve it by a slug or id.

xtremer360 left a reply on Manually Adding Users In Code?

It is difficult to help without seeing what your createUser() looks like? Can you provide us with this so we can better assist you?

For your UsersController I would highly recommend changing your createUser() method to store() this way you are able to work RESTfully.

22 Jan
3 months ago

xtremer360 started a new conversation Testing An Event Listener With Model Factories

I have the following situation where I'm trying to test an event listener. Currently, the test is passing which is great, however, my problem is that looking at this test you can't tell that the default room type is creating when the factory(BusinessUnit::class)->create() is executed. Then I can't test to make sure that the room type that is added is the one in the test which isn't included. The reason why I have it in the afterCreating method for a factory is really to mock what is needed when a business unit is created.

Does anyone have any suggestions on a better way to go about this so that the reader of my test would know that a default room type is created in that afterCreating method OR is there enough people that would agree that I'm fine with the current way the test is being written?

/** @test */
public function a_copy_of_the_default_rooms_are_added_to_the_created_business_unit()
{
    Event::fake([BusinessUnitCreated::class]);

    $businessUnit = factory(BusinessUnit::class)->create();
    $user = factory(User::class)->create();

    event(new BusinessUnitCreated($businessUnit, $user));

    $this->assertCount(1, $businessUnit->roomTypes);
}
$factory->afterCreating(BusinessUnit::class, function ($businessUnit, $faker) {
    $businessUnit->socialLinks()->save(factory(Social::class)->make());
    $businessUnit->address()->save(factory(Address::class)->make());
    factory(User::class)->states('inspector')->create(['business_unit_id' => $businessUnit->id]);

    $roomType = factory(RoomType::class)->states('default')->create(['name' => 'Kitchen']);
    $businessUnit->roomTypes()->attach($roomType->id, ['room_name' => $roomType->name, 'added_at' => now()]);
});
18 Jan
3 months ago

xtremer360 left a reply on Unit Testing An Event Handler With Auth User Attached

@talinon Is it okay to make that user null by default because I have two factories that are causing problems with that.

For example, I have the following factory that causes an error with the following test because it says that null is being passed through the construct of the BusinessUnitCreated Event class.

$factory->state(User::class, 'administrator', function () {
    return [
        'business_unit_id' => function () {
            return factory(BusinessUnit::class)->create()->id;
        },
        'role_id' => Role::whereSlug('administrator')->value('id')
    ];
});

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

        $response = $this->json('POST', '/business-units', $this->validParams());

        $response->assertStatus(403);
    }

xtremer360 left a reply on Unit Testing An Event Handler With Auth User Attached

That would work great, however, and this is my fault. I forgot to mention that this event is fired through the $displatchesEvents property on my model. Does that change things?

xtremer360 started a new conversation Unit Testing An Event Handler With Auth User Attached

Can anyone tell me if there is a way to unit test this event listener? I don't know if there's a way due to needing an authenticated user to save as the creator.

public function handle(BusinessUnitCreated $event)
    {
        $defaultTermsAndConditions = TermsAndConditions::defaults()->get();

        foreach ($defaultTermsAndConditions as $defaultTermsAndCondition) {
            $event->businessUnit->termsAndConditions()->create([
                'type_id' => $defaultTermsAndCondition->type_id,
                'content' => $defaultTermsAndCondition->content,
                'creator_id' => auth()->user()->id,
            ]);
        }
    }
16 Jan
3 months ago

xtremer360 left a reply on Another Shot At Clarity

I'll do some changes and circle back and update on this conversation.

xtremer360 left a reply on Another Shot At Clarity

@mikemacdowell Does that solve my problem then with it saying no such column: observations

xtremer360 left a reply on Another Shot At Clarity

I still haven't been able to get this issue fixed and would like to revisit my post to seek further guidance.

I am attempting to pass the test below. I have included the Models associated with this test as well as the controller that is hit from the endpoint to save a new observation for the property room. I have not included the route because I can guarantee that the endpoint DOES hit the store method for the ObservationsController.

With the current code provided below I am getting a General error: 1 no such column observations.

I don't know why it is looking for observations as a column when its a relationship method.

To help explain what is supposed happen.

  1. A business unit when created has copies of the default rooms added to their business unit.
  2. When a business unit creates a new property it takes the rooms assigned to that business unit and attaches them to the property.
  3. Then an authorized user can go into a room at that property and create an observation for that room through a comment about the room, a test on the room, or take a photo of the room or a combination of any of those.

My main focus is getting my relationships correct for the following models:Property, Room, Observation, and PropertyRoom solving this problem I'm certain will solve my current issue about the no such column observations.

/** @test */
    public function an_administrator_can_create_a_new_observation_for_a_room_at_a_property_belonging_to_their_business_unit()
    {
        // $this->withoutExceptionHandling();
        $signedInUser = factory(User::class)->states('administrator')->create();
        $property = factory(Property::class)->create(['business_unit_id' => $signedInUser->businessUnit->id]);
        $property->rooms()->attach($property->businessUnit->rooms()->first()->id, ['room_name' => Room::default()->first()->name]);

        $response = $this->actingAs($signedInUser)->json('POST', '/properties/'.$property->id.'/rooms/'.$property->rooms->first()->id.'/observations', []);

        $response->assertStatus(201);
        $this->assertCount(1, $property->rooms->first()->observations);
    }
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\Pivot;

class PropertyRoom extends Pivot
{
    protected $table = 'property_room';

    protected $fillable = ['property_id', 'room_id', 'room_name'];

    /**
     * Get the rooms that are assigned to a property.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function property()
    {
        return $this->belongsTo(Property::class);
    }

    /**
     * Get the rooms that are assigned to a property.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function room()
    {
        return $this->belongsTo(Room::class);
    }

    /**
     * Get the observations that are assigned to a property room.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function observations()
    {
        return $this->hasMany(Observation::class);
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'is_active', 'uses_wysiwyg', 'protocol', 'creator_id'];


    /**
     * Get the business unit that belongs to the room.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function businessUnit()
    {
        return $this->belongsTo(BusinessUnit::class);
    }

    /**
     * Get the properties that are assigned to the room.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function properties()
    {
        return $this->belongsToMany(Property::class, 'property_room', 'room_id', 'property_id')->using(PropertyRoom::class)->withPivot(['room_name']);
    }
}
<?php

namespace App\Models;

use App\Models\PropertyRoom;
use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['business_unit_id', 'customer_id', 'appointment_date', 'notes', 'main_photo_url', 'office_phone', 'inspector_id', 'creator_id'];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['appointment_date'];

    /**
     * Get the business unit associated to the property.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function businessUnit()
    {
        return $this->belongsTo(BusinessUnit::class);
    }

    /**
     * Get the rooms that are assigned to a property.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function rooms()
    {
        return $this->belongsToMany(Room::class, 'property_room', 'property_id', 'room_id')->using(PropertyRoom::class)->withPivot(['room_name']);
    }
}
<?php

namespace App\Http\Controllers;

use App\Models\Room;
use App\Models\Property;
use App\Models\Observation;
use App\Models\PropertyRoom;
use App\Http\Requests\StoreObservationRequest;
use App\Http\Resources\Observation as ObservationResource;

class ObservationsController extends Controller
{
    /**
     *
     * @param  \App\Http\Requests\StoreObservationRequest  $request
     * @param  \App\Models\Property  $property
     * @param  \App\Models\Room  $room
     * @return \App\Http\Resources\Observation
     */
    public function store(StoreObservationRequest $request, Property $property, Room $room)
    {
        $propertyRoom = PropertyRoom::where(['property_id' => $property->id, 'room_id' => $room->id])->first();
        dd($propertyRoom->observations);
        $max = $propertyRoom->observations()->max('sort_order');

        $observation = $propertyRoom->observations()->create([
            'sort_order' => $max + 1,
            'creator_id' => auth()->user()->id,
        ]);

        return new ObservationResource($observation);
    }
}
15 Jan
3 months ago

xtremer360 left a reply on Laravel Custom Form Request Get Id

I would also rethink your naming convention for your Form Request class. AddEditShopRequest isn't great. If you decide to do different Custom Request classes for Updating and Creating I would do StoreShopRequest and UpdateShopRequest this way it denotes the action that will take place.

10 Jan
3 months ago

xtremer360 left a reply on Limit Attendance Records Just One Per Day

@hfalucas I think they can even use the user record to get their attendances. I think this would be an easier approach since you already have the user you can use the relationship with the model.

$attended = $user->attendences
    ->whereDate('created_at', Carbon::today())
    ->exists();