xtremer360

xtremer360

Member Since 5 Years Ago

Kissimmee, FL

Full Stack Developer at 321

Experience Points 143,565
Experience Level 29

1,435 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 1090
Lessons
Completed
Best Reply Awards 9
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

08 Jul
1 week ago

xtremer360 started a new conversation Data Providerrs Are They Worth It

I am trying to decide if using data providers for my tests is the best way to go.

Below I have an example of a test where an administrator can update an inactive user to be active. I have a data provider that I can apply to this test that returns an array of two different types of administrator roles. This array of roles are roles that have the ability to perform this action.

I understand for this simple test it would be just as easy to create a new test that assures the same functionality passes for the two different admin types however this starts to get bigger as different conditions are met on whether or not the user can be activated at all.

On the other end of the spectrum, I have 20+ tests that feature endpoint testing that tests form validation fails with passing the post parameters. Those tests all say that a specific role is logged in during those tests but both types of admin roles have the same type of results.

I'm seeking advice as to if many people reach for data providers a lot with situations like this or not or if there are some better alternatives. I've heard that some people will separate out the same tests into separate directories with a directory for each role but seems like a copy and paste for the same test with one minor change. Plus when criteria changes or another role is added you'd have to go in and create an additional directory with more copied tests.

What do you all think?

/** @test */
    public function an_administrator_can_activate_an_inactive_user()
    {
        $this->actAs('administrator');
        $user = factory(User::class)->states('inactive')->create();

        $response = $this->put(route('users.activate', $user));

        $response->assertRedirect(route('users.index'));
        tap($user->fresh(), function ($user) {
            $this->assertTrue($user->is_active);
        });
    }
09 Jun
1 month ago

xtremer360 left a reply on How To Order A Product Only Once In Laravel?

I think I've missed the question here. Did you include one?

10 May
2 months ago

xtremer360 started a new conversation Packages Not Being Defined

I'm trying to figure out why my Sticky and PerfectScrollbar are not defined when I try and load my page. This error says it's coming from the scripts.bundle.js.

resources/js/scripts.bundle.js

"use strict";
import jQuery from "jquery";
...
...

resources/js/entries/app.js

import "../bootstrap.js";
import "../scripts.bundle.js";

resources/js/bootstrap.js

import jQuery from "jquery";
import Sticky from "sticky-js";
import PerfectScrollbar from "perfect-scrollbar";
import Cookies from "js-cookie";
import Datatables from "datatables";
import "./bootstrappers/datatables.js";
window.$ = jQuery;

webpack.js

const mix = require("laravel-mix");
const endsWith = require("lodash.endswith");
const glob = require("glob");
const output = require("friendly-errors-webpack-plugin/src/output");

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.styles(
    [
        "resources/css/theme/style.bundle.css",
        "resources/css/theme/skins/header/base/light.css",
        "resources/css/theme/skins/header/menu/light.css",
        "resources/css/theme/skins/brand/dark.css",
        "resources/css/theme/skins/aside/dark.css"
    ],
    "public/css/theme.css"
);

mix.styles(
    [
        "resources/vendors/flaticon/flaticon.css",
        "resources/vendors/flaticon2/flaticon.css"
    ],
    "public/css/fonts.css"
);
mix.sass("resources/sass/app.scss", "public/css");

/************************************************************************
 * Copy Static Assets
 ************************************************************************/
mix.copyDirectory("resources/vendors/flaticon/font", "public/css/font");
mix.copyDirectory("resources/vendors/flaticon2/font", "public/css/font");

/************************************************************************
 * Mix Configuration
 * * We aren't keen on the "Build successful" notifications, so disable
 *   them
 * * We load in our webpack.config.js, which just contains aliases so
 *   PHPstorm reads them
 ************************************************************************/
// mix.webpackConfig(require("./webpack.config"));
mix.disableSuccessNotifications();
mix.sourceMaps(false, "inline-source-map");

/************************************************************************
 * Spit out all our entries as individual files
 * * specifically it's anything in resources/js/entries/*
 *   or any child directories, that get made into their own files
 * * It could be simpler, but we also make it output a line in the console
 *   for each entry.
 ************************************************************************/
/** @var {String[]} */
const entries = glob.sync("resources/js/entries/**/*.js");
const buildOutputPath = file =>
    file.replace("resources/js/entries/", "public/js/");
entries
    .filter(entry => !endsWith(entry, "app.js"))
    .forEach(file => {
        output.title("info", "ENTRY", file);
        mix.js(file, buildOutputPath(file));
    });
// We need to manually run this last as otherwise our output path breaks.
mix.js("resources/js/entries/app.js", "public/js/app.js");

// mix.js(["resources/js/scripts.bundle.js"], "public/js/app.js");

/************************************************************************
 * Extract all the vendor files, these are anything that appear in more
 * than ~3 of our entries. These all end up in vendor.js
 ************************************************************************/
mix.extract([
    "jquery",
    "popper.js",
    "bootstrap",
    "js-cookie",
    "moment",
    "tooltip.js",
    "perfect-scrollbar",
    "sticky-js",
    "wnumb",
    "datatables"
]);

06 May
2 months ago

xtremer360 left a reply on Clear Viewed Episodes In Series

Go to the series you are wanting to rewatch and you can unclick the button on the lesson that says Lesson Completed. It should update with making it unwatched.

xtremer360 left a reply on Clear Viewed Episodes In Series

You can still access series and rewatch them now even if you've watched them before.

28 Apr
2 months ago

xtremer360 left a reply on Sending String Parameter From Route To View

@neeonline Doesn't your first suggestion add logic to the view. I was starting to think about a view composer but not sure if that is the right direction.

27 Apr
2 months ago

xtremer360 left a reply on Internal Api Requests

Ah okay. Take a look at the other responses on that post. More people are saying to use app()->handle() rather than Route::dispatch().

xtremer360 left a reply on Internal Api Requests

Well, I don't believe there is a dispatch method on the Route class or a create method on the Request class.. Where did you see these methods?

26 Apr
2 months ago

xtremer360 left a reply on Sending String Parameter From Route To View

There may be some misunderstanding. Is there a way I can with a view composer or something to where on any index page it will show the state as capitalized when the variable is being requested.

xtremer360 left a reply on Sending String Parameter From Route To View

You are taking away the state getting put though the String title helper though.

xtremer360 started a new conversation Sending String Parameter From Route To View

I am trying to think of any better way to send through a string that has retrieved from a route parameter and has been run through a title string helper and echoed out into the view.

Route::get('/users/state/{state?}', '[email protected]')->name('users.index');
public function index($state = 'active')
{

        $users = User::hasState($state)->get();
        $state = Str::title($state);

        return response()->view('users.index', compact('users', 'state'));
}
{{ $state }} Users
19 Apr
2 months 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
3 months 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
3 months 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
3 months 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
3 months 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
3 months 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
3 months 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
3 months 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 months 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 months 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 months 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 months 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
3 months 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
3 months 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
3 months 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
4 months 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
4 months ago
09 Mar
4 months 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
4 months 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
4 months 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
4 months 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
4 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
4 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);
    }
}