xtremer360

xtremer360

Full Stack Developer at 321

Member Since 6 Years Ago

Kissimmee, FL

Experience Points
180,655
Total
Experience

4,345 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
1363
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 37
180,655 XP
Oct
26
1 day ago
Activity icon

Started a new Conversation Laravel Livewire Rules Array

I am currently trying to do a check that a property on my form is required if a certain condition passes. With the current code I am receiving the error that the Constant expression contains invalid operations. I have no run into this problem before and looking for some understanding of what its trying to tell me.

protected $rules = [
    'field' => [
        Rule::requiredIf(function () {
             return $this->category->hasARange();
        }),
        'integer',
    ],

]
Activity icon

Started a new Conversation Dynamically Generating Elements With Livewire

I'm working on a Livewire component where ticking a checkbox will make a text box visible and clicking a button will generate an additional text box below. Currently I have the checkbox making the initial text field visible however my button that dynamically generates additional text field elements is not generating those elements. I'm still learning Livewire but not sure what I'm missing.

<input type="checkbox" wire:model="otherUser" wire-model="otherUserCount++">Other
@if ($otherUser)
    @foreach ($otherUsers as $user)
        <input type="text" class="form-control" id="userInput">
    @endforeach
    <button type="button" class="mt-2 btn btn-primary" >+ Add Additional User</button>
@endif
<?php

namespace App\Http\Livewire;

use App\User;
use Livewire\Component;

class UsersForm extends Component
{
    public $otherUser = false;
    public $otherUsers = [];

    public function render()
    {
        ...
    }
}

Oct
21
6 days ago
Activity icon

Started a new Conversation Passing In Data To Model Factory Methods

Currently I'm looking at some old code and looking for suggestions on if I should go ahead with the changes I am making below. Those changes being to pass in the factories generated into the User state method or go a different route?

for ($i = 1; $i <= 10; $i++) {
    $start = $startDate->copy();
    $end = $start->copy()->addYears($randomNumberOfYearsEmployed)->addMonth(rand(1, 11));

    $employment = Employment::factory()->started($start)->ended($end);
    $retirement = Retirement::factory()->started($end);
    User::factory()
        ->retired($employment, $retirement)
        ->create(['name' => 'User '.$eNum]);

    $eNum++;
}
// I know I still need to accept the two params for this method but should I be rethinking this strategy if I'm 
//  wanting to seed my database with factories with specific relation records
public function retired(): self
{
    $now = now();
    $start = $now->copy()->subDays(2);
    $end = $now->copy()->subDays(1);

    return $this->state([
        'status' => UserStatus::RETIRED,
    ])->hasEmployments(1, ['started_at' => $start, 'ended_at' => $end])
    ->hasRetirements(1, ['started_at' => $end])
    ->afterCreating(function (User $user) {
        $user->save();
        $user->load('employments');
        $user->load('retirements');
    });
}
Oct
15
1 week ago
Activity icon

Started a new Conversation Unit Testing Views In Isolation

I have some unit tests that I'm looking back through to see what is needed and what isn't needed. I'm wondering if this is a beneficial test or if I should scrape it.

/** @test */
public function a_employees_name_can_be_seen_on_their_biography_page()
{
    $manager = Employee::factory()->create(['first_name' => 'John', 'last_name' => 'Smith']);

    $view = $this->view('employees.show', compact('employee'));

    // $this->assertView('employees.show', compact('empoyee'))->contains('John Smith');
    $view->assertSee('John Smith');
}
Oct
12
2 weeks ago
Activity icon

Replied to Making Methods More Fluid

@automica Is that what you suggest or do you think that the likelihood of that happening is slim to none.

Activity icon

Replied to Making Methods More Fluid

@automica Done! Great refactor. The only other thought I had was about if the injure() was actually fluid. By this I mean Is there any problem with the fact that that injure() will never return false. It iwll other return the current class instance because the canBeInjured() will be responsible for throwing the Exception? Is this an okay thing to do?

Activity icon

Replied to Laravel Lando With XDebug BindingResolutionException

I've seen a few posts about this but no solutions.

Activity icon

Started a new Conversation Making Methods More Fluid

Does anyone see anything wrong with how this is written as it shows below?

public function injure($injuredAt = null)
{
    if ($this->canBeInjured()) {
        $injuredDate = $injuredAt ?? now();
        $this->injuries()->create(['started_at' => $injuredDate]);
        $this->save();

           
        if (optional($this->currentTeam)->isBookable()) {
            $this->currentTeam->touch();
            $this->currentTeam->refresh();
        }

        return $this;
    }
}

public function canBeInjured()
{
    if ($this->isUnemployed() || $this->isReleased() || $this->hasFutureEmployment() || $this->isRetired()) {
        throw new CannotBeInjuredException('Entity cannot be injured. This entity does not have an active employment.');
    }

    if ($this->isInjured()) {
        throw new CannotBeInjuredException('Entity cannot be injured. This entity is currently injured.');
    }

    if ($this->isSuspended()) {
        throw new CannotBeInjuredException('Entity cannot be injured. This entity is currently suspended.');
    }

    return true;
}
Oct
10
2 weeks ago
Activity icon

Replied to Laravel Lando With XDebug BindingResolutionException

jeffreydavidson at Jeffreys-iMac in ~
○ whoami
jeffreydavidson
jeffreydavidson at Jeffreys-iMac in ~
○ chown -R jeffreydavidson:jeffreydavidson ~/Projects/Ringside
chown: jeffreydavidson: illegal group name
Activity icon

Replied to Laravel Lando With XDebug BindingResolutionException

Yes, I would assume so. There's no other users on this computer. Is there a way I can verify this?

Activity icon

Replied to Laravel Lando With XDebug BindingResolutionException

@sinnbeck I'm on MacOS Catalina but the 501 was from inside the lando container. If I run id -u from outside the Lando then I still get 501.

Activity icon

Replied to Laravel Lando With XDebug BindingResolutionException

I ran lando ssh and then id -u.

Activity icon

Replied to Laravel Lando With XDebug BindingResolutionException

Well I run id -u I get 501.

Activity icon

Started a new Conversation Laravel Lando With XDebug BindingResolutionException

I'm working with Visual Studio Code and have xDebug installed and running and also running a Lando dev enviroment. I have run my PHPUnit tests from my Laravel 8 application inside the terminal without Lando and the tests run fine however when I run it in Lando then I start running into an error that I can't figure out. The error is below.

What I don't understand is what am I doing wrong in my configuration of Lando that is missing a Binding of some kind? Reason why I think its in my Lando configuration is like I said above the test works without an error. The test passes in both situations but when I run in Lando it reports the Uncaught BindingResolutionException.

I've ran composer dump-autoload several times and didn't change the error.

https://docs.lando.dev/guides/lando-with-vscode.html#getting-started

PHP Fatal error:  Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:1017
Stack trace:
#0 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(818): Illuminate\Container\Container->notInstantiable('Illuminate\Cont...')
#1 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(691): Illuminate\Container\Container->build('Illuminate\Cont...')
#2 /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(796): Illuminate\Container\Container->resolve('Illuminate\Cont...', Array, true)
#3 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(637): Illuminate\Foundation\Application->resolve('Illuminate\Cont...', Array)
#4 /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(781): Illuminate\Container\Container->make('Illuminate\Cont...', Array)
#5 /app/vendor/laravel/framework/src/Illuminate/ in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1017

Fatal error: Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1017

Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1017

Call Stack:
    5.0479   68751112   1. Illuminate\Foundation\Bootstrap\HandleExceptions->handleException() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:0
    5.0508   68749376   2. Illuminate\Foundation\Bootstrap\HandleExceptions->renderForConsole() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:94
    5.0508   68749376   3. Illuminate\Foundation\Bootstrap\HandleExceptions->getExceptionHandler() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:108
    5.0508   68749376   4. Illuminate\Foundation\Application->make() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:164
    5.0508   68749376   5. Illuminate\Foundation\Application->make() /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:781
    5.0508   68749376   6. Illuminate\Foundation\Application->resolve() /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:637
    5.0509   68749376   7. Illuminate\Foundation\Application->resolve() /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:796
    5.0510   68749376   8. Illuminate\Foundation\Application->build() /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:691
    5.0510   68749488   9. Illuminate\Foundation\Application->notInstantiable() /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:818

PHP Fatal error:  Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:1017
Stack trace:
#0 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(818): Illuminate\Container\Container->notInstantiable('Illuminate\Cont...')
#1 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(691): Illuminate\Container\Container->build('Illuminate\Cont...')
#2 /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(796): Illuminate\Container\Container->resolve('Illuminate\Cont...', Array, true)
#3 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(637): Illuminate\Foundation\Application->resolve('Illuminate\Cont...', Array)
#4 /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(781): Illuminate\Container\Container->make('Illuminate\Cont...', Array)
#5 /app/vendor/laravel/framework/src/Illuminate/ in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1017

Fatal error: Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1017

Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable. in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1017

Call Stack:
    5.0552   68763168   1. Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:0
    5.0572   68779408   2. Illuminate\Foundation\Bootstrap\HandleExceptions->handleException() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:130
    5.0573   68788752   3. Illuminate\Foundation\Bootstrap\HandleExceptions->renderForConsole() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:94
    5.0573   68788752   4. Illuminate\Foundation\Bootstrap\HandleExceptions->getExceptionHandler() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:108
    5.0573   68788752   5. Illuminate\Foundation\Application->make() /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:164
    5.0573   68788752   6. Illuminate\Foundation\Application->make() /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:781
    5.0573   68788752   7. Illuminate\Foundation\Application->resolve() /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:637
    5.0573   68788752   8. Illuminate\Foundation\Application->resolve() /app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:796
    5.0573   68788752   9. Illuminate\Foundation\Application->build() /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:691
    5.0573   68788864  10. Illuminate\Foundation\Application->notInstantiable() /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:818

.lando.yml

name: My App
recipe: laravel
config:
  php: '7.3'
  webroot: public
  database: mysql:5.7
  xdebug: true
  config:
    php: .vscode/php.ini
tooling:
  reseed:
    service: appserver
    description: "Seed the database"
    cmd: "php artisan db:seed"
  tinker:
    service: appserver
    description: "Drop into a tinker console"
    cmd: "php artisan tinker"
  ide:
    service: appserver
    description: "Update the IDE docs"
    cmd:
      - "php artisan ide-helper:meta"
      - "php artisan ide-helper:models --write --reset"
  migrate:
    service: appserver
    description: "Quick migrate"
    cmd: "php artisan migrate"
  phpunit:
    service: appserver
    description: "Run PHP Unit tests: lando phpunit"
    cmd: "vendor/bin/phpunit --testsuite Feature --coverage-html tests/coverage"
  phpunitdebug:
    service: appserver
    cmd: php -d xdebug.remote_port=9000 vendor/bin/phpunit

.vscode/php.ini

; [PHP]

; Xdebug
xdebug.max_nesting_level = 256
xdebug.show_exception_trace = 0
xdebug.collect_params = 0
; Extra custom Xdebug setting for debug to work in VSCode.
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_host = ${LANDO_HOST_IP}
; xdebug.remote_connect_back = 1
xdebug.remote_log = /tmp/xdebug.log

.vscode/launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
          "name": "Listen for XDebug",
          "type": "php",
          "request": "launch",
          "port": 9000,
          "log": false,
          "pathMappings": {
            "/app/": "${workspaceFolder}/",
          }
        },
        {
            "name": "PhpUnit dummy",
            "type": "php",
            "request": "launch",
            "port": 9001,
        },
    ],
    "compounds": [
        {
            "name": "PhpUnit",
            "configurations": ["Listen for XDebug", "PhpUnit dummy"]
        }
    ]
}
Sep
30
3 weeks ago
Activity icon

Replied to Retrieving A Single Model From A BelongsToMany

Any other suggestions?

Sep
29
4 weeks ago
Activity icon

Replied to Retrieving A Single Model From A BelongsToMany

Doesn’t that return a collection though.

Activity icon

Started a new Conversation Retrieving A Single Model From A BelongsToMany

Currently I have the following but needing to figure out how I can get currentTeam to return the single model. I don't want to use an accessor for this. I found a package that is like it but deals with MorphedModels. I've included this package below. The package does not include a way to deal with non polymorphic models so I need a way to retrieve a single model from the relationship.

https://github.com/fidum/laravel-eloquent-morph-to-one

public function teams()
{
        return $this->belongsToMany(Team::class, 'tag_team_player');
}

public function currentTeam()
{
    return $this->belongsToMany(Team::class, 'tag_team_player')
                ->where('started_at', '<=', now())
                ->whereNull('ended_at')
                ->limit(1);
}
Sep
25
1 month ago
Activity icon

Started a new Conversation Retrieving A MorphOne Model Instance

Any suggestions on how I can get the group model returned when I am trying to retrieve the currentGroup off of a model?

When I try and run $student->currentGroup I am getting an SQL error stating that the column member_id does not exist on the groups table. I understand the error however that member_idis inside of the Pivot table calledgroup_members`.

/**
     * Get the groups the model has been belonged to.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function groups()
    {
        return $this->morphToMany(Group::class, 'member', 'group_members');
    }
    /**
     * Get the current group the member belongs to.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function currentGroup()
    {
        return $this->morphOne(Group::class, 'member')
                    ->wherePivot('joined_at', '<=', now())
                    ->wherePivot('left_at', '=', null)
                    ->limit(1);
    }

students
______
id
name

teachers
______
id
name

groups
______
id
name

group_members
______
id
group_id
member_id
member_type
Sep
18
1 month ago
Activity icon

Replied to Model Touch

@snapey So then maybe my code is wrong to the point where after the model is unretired and/or employed() it needs to run the save() method on the model again due to code inside of an observer.

Activity icon

Replied to Model Touch

@snapey Should I not be returning its value? Should I be doing this instead then?

$this->touch();

return $this;
Activity icon

Started a new Conversation Model Touch

Can anyone suggest any modifications to strengthen these methods? The reason why I have the touch method call on the model is so it can dynamically change the status property of the model based on relationship criteria on the model/

public function unretire($unretiredAt = null)
{
    if ($this->canBeUnretired()) {
        $unretiredDate = $unretiredAt ?: now();

        $this->currentRetirement()->update(['ended_at' => $unretiredDate]);

        // Old Way
        // $this->employ($unretiredDate);
        
        // New way
        $this->employments()->create(['started_at' => $unretiredDate]);

        return $this->touch();
    }
}


public function employ($startedAt = null)
{
    if ($this->canBeEmployed()) {
        $startDate = $startedAt ?? now();

        $this->employments()->updateOrCreate(['ended_at' => null], ['started_at' => $startDate]);

        return $this->touch();
    }
}
Sep
10
1 month ago
Activity icon

Replied to Model Factory Relationships

If I dd(Player::factory()->injured()) with the following code inside of the injured method of the factory class then I get what proceeds the following but obviously the call is missing ->create(). As you can see I'm actually getting somewhere with the following code, however, if I surround the hasEmployments() and hasInjuries() methods in the afterCreating() hook then I don't get any desired results.

public function injured(): self
{
        $now = now();
        $start = $now->copy()->subDays(2);

        return $this->state([
            'status' => PlayerStatus::INJURED,
        ])->hasEmployments(0, ['started_at' => $start])
        ->hasInjuries(0, ['started_at' => $now]);
}
^ Database\Factories\PlayerFactory^ {#7867
  #modelClass: "App\Models\Player"
  #model: null
  #count: null
  #states: Illuminate\Support\Collection^ {#7834
    #items: array:3 [
      0 => Closure()^ {#7814
        class: "Illuminate\Database\Eloquent\Factories\Factory"
        this: Database\Factories\PlayerFactory {#7809 …}
        use: {
          $state: []
        }
      }
      1 => Closure()^ {#7829
        class: "Illuminate\Database\Eloquent\Factories\Factory"
        this: Database\Factories\PlayerFactory {#7831 …}
        use: {
          $state: []
        }
      }
      2 => Closure()^ {#7836
        class: "Illuminate\Database\Eloquent\Factories\Factory"
        this: Database\Factories\PlayerFactory {#7833 …}
        use: {
          $state: array:1 [
            "status" => "injured"
          ]
        }
      }
    ]
  }
  #has: Illuminate\Support\Collection^ {#7866
    #items: array:2 [
      0 => Illuminate\Database\Eloquent\Factories\Relationship^ {#7851
        #factory: Database\Factories\EmploymentFactory^ {#7850
          #modelClass: "App\Models\Employment"
          #model: null
          #count: 0
          #states: Illuminate\Support\Collection^ {#7849
            #items: array:2 [
              0 => Closure()^ {#7844
                class: "Illuminate\Database\Eloquent\Factories\Factory"
                this: Database\Factories\EmploymentFactory {#7839 …}
                use: {
                  $state: []
                }
              }
              1 => Closure()^ {#7848
                class: "Illuminate\Database\Eloquent\Factories\Factory"
                this: Database\Factories\EmploymentFactory {#7847 …}
                use: {
                  $state: array:1 [
                    "started_at" => Illuminate\Support\Carbon @1599583214^ {#7835
                      #constructedObjectId: "0000000035320a5a00000000589d3016"
                      #localMonthsOverflow: null
                      #localYearsOverflow: null
                      #localStrictModeEnabled: null
                      #localHumanDiffOptions: null
                      #localToStringFormat: null
                      #localSerializer: null
                      #localMacros: null
                      #localGenericMacros: null
                      #localFormatFunction: null
                      #localTranslator: null
                      #dumpProperties: array:3 [
                        0 => "date"
                        1 => "timezone_type"
                        2 => "timezone"
                      ]
                      #dumpLocale: null
                      date: 2020-09-08 16:40:14.659110 UTC (+00:00)
                    }
                  ]
                }
              }
            ]
          }
          #has: Illuminate\Support\Collection^ {#7838
            #items: []
          }
          #for: Illuminate\Support\Collection^ {#7841
            #items: []
          }
          #afterMaking: Illuminate\Support\Collection^ {#7840
            #items: []
          }
          #afterCreating: Illuminate\Support\Collection^ {#7843
            #items: []
          }
          #connection: null
          #faker: null
        }
        #relationship: "employments"
      }
      1 => Illuminate\Database\Eloquent\Factories\Relationship^ {#7865
        #factory: Database\Factories\InjuryFactory^ {#7864
          #modelClass: "App\Models\Injury"
          #model: null
          #count: 0
          #states: Illuminate\Support\Collection^ {#7863
            #items: array:2 [
              0 => Closure()^ {#7858
                class: "Illuminate\Database\Eloquent\Factories\Factory"
                this: Database\Factories\InjuryFactory {#7846 …}
                use: {
                  $state: []
                }
              }
              1 => Closure()^ {#7862
                class: "Illuminate\Database\Eloquent\Factories\Factory"
                this: Database\Factories\InjuryFactory {#7861 …}
                use: {
                  $state: array:1 [
                    "started_at" => Illuminate\Support\Carbon @1599756014^ {#7832
                      #constructedObjectId: "0000000035320a5900000000589d3016"
                      #localMonthsOverflow: null
                      #localYearsOverflow: null
                      #localStrictModeEnabled: null
                      #localHumanDiffOptions: null
                      #localToStringFormat: null
                      #localSerializer: null
                      #localMacros: null
                      #localGenericMacros: null
                      #localFormatFunction: null
                      #localTranslator: null
                      #dumpProperties: array:3 [
                        0 => "date"
                        1 => "timezone_type"
                        2 => "timezone"
                      ]
                      #dumpLocale: null
                      date: 2020-09-10 16:40:14.659110 UTC (+00:00)
                    }
                  ]
                }
              }
            ]
          }
          #has: Illuminate\Support\Collection^ {#7837
            #items: []
          }
          #for: Illuminate\Support\Collection^ {#7855
            #items: []
          }
          #afterMaking: Illuminate\Support\Collection^ {#7854
            #items: []
          }
          #afterCreating: Illuminate\Support\Collection^ {#7857
            #items: []
          }
          #connection: null
          #faker: null
        }
        #relationship: "injuries"
      }
    ]
  }
  #for: Illuminate\Support\Collection^ {#7823
    #items: []
  }
  #afterMaking: Illuminate\Support\Collection^ {#7638
    #items: []
  }
  #afterCreating: Illuminate\Support\Collection^ {#7636
    #items: []
  }
  #connection: null
  #faker: null
}
Activity icon

Replied to Model Factory Relationships

Did anyone else have any suggestions. Something else I can't figure out is if I run dd(Player::factory()->injured()) it returns two empty states in addition to the state I'm overriding.

Sep
09
1 month ago
Activity icon

Replied to Model Factory Relationships

@jdc1898 I want to make sure that when it creates a player it adds an employment and injury record for it.

Activity icon

Replied to Model Factory Relationships

@jdc1898 Why are you saying 0?

Activity icon

Started a new Conversation Model Factory Relationships

I'm trying to figure out why I'm not getting back my expected results from this model creation. Both employments and injuries are both MorphMany relationships. What is returned is a player that doesn't have any employments or injury records.

Player::factory()->injured()->create();
public function injured(): self
    {
        $this->state([
            'status' => PlayerStatus::INJURED,
        ]);

        $now = now();
        $start = $now->copy()->subDays(2);

        $this->hasEmployments(1, ['started_at' => $start]);

        $this->hasInjuries(1, ['started_at' => $now]);

        return $this;
    }
Sep
05
1 month ago
Activity icon

Replied to Model Instance Relationship Exists

Is my currentRetirement method correct? Or should it not be a relationship?

Activity icon

Replied to Model Instance Relationship Exists

If I check my log for what happens for currentRetirement() I get this. So I don't know why the where retirements.retiree_id is asking for a null value

[2020-09-05 14:44:52] testing.INFO: select exists(select * from "retirements" where "retirements"."retiree_id" is null and "retirements"."retiree_id" is not null and "retirements"."retiree_type" = App\Models\Player and "started_at" <= 2020-09-05 14:44:52 and "ended_at" is null limit 1) as "exists"  
Sep
04
1 month ago
Activity icon

Started a new Conversation Model Instance Relationship Exists

My goal is to find out why when it attempts to unretire the player that says the response that comes back from my test is that my CannotBeUnretiredException is thrown. I traced this back and found that my isRetired() method is returning false. Does anyone see why this is? I've included the trait and the model instance to see the retirement relationship.

public function __invoke(Player $player, UnretireRequest $request)
{
    $player->unretire();

    return redirect()->route('players.index');
}
App\Models\Player^ {#7128
  #casts: array:1 [
    "status" => "App\Enums\PlayerStatus"
  ]
  #connection: "sqlite"
  #table: "players"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:9 [
    "name" => "Tyrell Veum"
    "height" => 65
    "weight" => 480
    "hometown" => "Krisview, Maryland"
    "updated_at" => "2020-09-04 18:41:32"
    "created_at" => "2020-09-04 18:41:32"
    "id" => 1
  ]
  #original: array:9 [
    "name" => "Tyrell Veum"
    "height" => 65
    "weight" => 480
    "hometown" => "Krisview, Maryland"
    "updated_at" => "2020-09-04 18:41:32"
    "created_at" => "2020-09-04 18:41:32"
    "id" => 1
  ]
  #changes: []
  #classCastCache: []
  #dates: array:1 [
    0 => "deleted_at"
  ]
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:2 [
    "employments" => Illuminate\Support\Collection^ {#7070
      #items: array:1 [
        0 => App\Models\Employment^ {#7132
          #dates: array:2 [
            0 => "started_at"
            1 => "ended_at"
          ]
          #connection: "sqlite"
          #table: "employments"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: true
          #attributes: array:7 [
            "started_at" => "2020-09-02 18:41:32"
            "ended_at" => "2020-09-03 18:41:32"
            "employable_id" => 1
            "employable_type" => "App\Models\Player"
            "updated_at" => "2020-09-04 18:41:32"
            "created_at" => "2020-09-04 18:41:32"
            "id" => 1
          ]
          #original: array:7 [
            "started_at" => "2020-09-02 18:41:32"
            "ended_at" => "2020-09-03 18:41:32"
            "employable_id" => 1
            "employable_type" => "App\Models\Player"
            "updated_at" => "2020-09-04 18:41:32"
            "created_at" => "2020-09-04 18:41:32"
            "id" => 1
          ]
          #changes: []
          #casts: []
          #classCastCache: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #fillable: []
          #guarded: []
        }
      ]
    }
    "retirements" => Illuminate\Support\Collection^ {#7125
      #items: array:1 [
        0 => App\Models\Retirement^ {#7131
          #dates: array:2 [
            0 => "started_at"
            1 => "ended_at"
          ]
          #connection: "sqlite"
          #table: "retirements"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: true
          #attributes: array:6 [
            "started_at" => "2020-09-03 18:41:32"
            "retiree_id" => 1
            "retiree_type" => "App\Models\Player"
            "updated_at" => "2020-09-04 18:41:32"
            "created_at" => "2020-09-04 18:41:32"
            "id" => 1
          ]
          #original: array:6 [
            "started_at" => "2020-09-03 18:41:32"
            "retiree_id" => 1
            "retiree_type" => "App\Models\Player"
            "updated_at" => "2020-09-04 18:41:32"
            "created_at" => "2020-09-04 18:41:32"
            "id" => 1
          ]
          #changes: []
          #casts: []
          #classCastCache: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #fillable: []
          #guarded: []
        }
      ]
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: []
  #cachedAttributes: []
  #forceDeleting: false
}
<?php

namespace App\Models\Concerns;

use App\Exceptions\CannotBeRetiredException;
use App\Exceptions\CannotBeUnretiredException;
use App\Models\Retirement;
use App\Traits\HasCachedAttributes;

trait CanBeRetired
{
    public static function bootCanBeRetired()
    {
        if (config('app.debug')) {
            $traits = class_uses_recursive(static::class);

            if (! in_array(HasCachedAttributes::class, $traits)) {
                throw new \LogicException('CanBeRetired trait used without HasCachedAttributes trait');
            }
        }
    }

    /**
     * Get the retirements of the model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function retirements()
    {
        return $this->morphMany(Retirement::class, 'retiree');
    }

    /**
     * Get the current retirement of the model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function currentRetirement()
    {
        return $this->morphOne(Retirement::class, 'retiree')
                    ->wherePivot('started_at', '<=', now())
                    ->whereNull('ended_at')
                    ->limit(1);
    }

    /**
     * Get the previous retirements of the model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function previousRetirements()
    {
        return $this->retirements()
                    ->whereNotNull('ended_at');
    }

    /**
     * Get the previous employment of the model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function previousRetirement()
    {
        return $this->previousRetirements()
                    ->latest('ended_at')
                    ->limit(1);
    }

    /**
     * Scope a query to only include retired models.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeRetired($query)
    {
        return $this->whereHas('currentRetirement');
    }

    /**
     * Determine if a model is retired.
     *
     * @return bool
     */
    public function getIsRetiredCachedAttribute()
    {
        return $this->status === 'retired';
    }

    /**
     * Scope a query to only include unemployed models.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     */
    public function scopeWithCurrentRetiredAtDate($query)
    {
        return $query->addSelect(['current_retired_at' => Retirement::select('started_at')
            ->whereColumn('retiree_id', $this->getTable().'.id')
            ->where('retiree_type', $this->getMorphClass())
            ->oldest('started_at')
            ->limit(1),
        ])->withCasts(['current_retired_at' => 'datetime']);
    }

    /**
     * Scope a query to order by the models current retirement date.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     */
    public function scopeOrderByCurrentRetiredAtDate($query, $direction = 'asc')
    {
        return $query->orderByRaw("DATE(current_retired_at) $direction");
    }

    /**
     * Retire a model.
     *
     * @return bool
     */
    abstract public function retire();

    /**
     * Unretire a model.
     *
     * @param  string|null $unretiredAt
     * @return bool
     */
    public function unretire($unretiredAt = null)
    {
        if ($this->canBeUnretired()) {
            $unretiredDate = $unretiredAt ?: now();

            $this->currentRetirement()->update(['ended_at' => $unretiredDate]);
            $this->employ($unretiredAt);

            return $this->touch();
        }
    }

    /**
     * Check to see if the model is retired.
     *
     * @return bool
     */
    public function isRetired()
    {
        return $this->currentRetirement()->exists();
    }

    /**
     * Determine if the model can be retired.
     *
     * @return bool
     */
    public function canBeRetired()
    {
        if ($this->isUnemployed() || $this->isReleased() || $this->hasFutureEmployment()) {
            throw new CannotBeRetiredException('Entity cannot be retired. This entity does not have an active employment.');
        }

        if ($this->isRetired()) {
            throw new CannotBeRetiredException('Entity cannot be retired. This entity is retired.');
        }

        return true;
    }

    /**
     * Determine if the model can be retired.
     *
     * @return bool
     */
    public function canBeUnretired()
    {
        if (! $this->isRetired()) {
            throw new CannotBeUnretiredException('Entity cannot be unretired. This entity is not retired.');
        }

        return true;
    }

    /**
     * Get the current retirement of the model.
     *
     * @return App\Models\Retirement
     */
    public function getCurrentRetirementAttribute()
    {
        if (! $this->relationLoaded('currentRetirement')) {
            $this->setRelation('currentRetirement', $this->currentRetirement()->get());
        }

        return $this->getRelation('currentRetirement')->first();
    }

    /**
     * Get the previous retirement of the model.
     *
     * @return App\Models\Retirement
     */
    public function getPreviousRetirementAttribute()
    {
        if (! $this->relationLoaded('previousRetirement')) {
            $this->setRelation('previousRetirement', $this->previousRetirement()->get());
        }

        return $this->getRelation('previousRetirement')->first();
    }
}

Sep
03
1 month ago
Activity icon

Started a new Conversation Requiring Model Status Before Action

I'm trying to figure out where some logic should be placed in my application. I have a player model in my application that can be retired. This can be accomplished through an endpoint that uses route model binding. Before a player can be retired they must be an active player and a few other prerequisites. I know there's multiple ways to go about it, I'm just looking for some suggestions.

<?php

namespace App\Http\Controllers\Players;

use App\Http\Controllers\Controller;
use App\Models\Player;

class RetireController extends Controller
{
    /**
     * Retire a player.
     *
     * @param  \App\Models\Player  $player
     * @return \Illuminate\Http\RedirectResponse
     */
    public function __invoke(Player $player)
    {
        $player->retire();

        return redirect()->route('players.index');
    }
}
Aug
28
1 month ago
Activity icon

Replied to Restructuring Models And Parent Model

Does any of this information help anyone give further understanding of what I'm trying to accomplish?

Aug
27
2 months ago
Activity icon

Replied to Restructuring Models And Parent Model

@martinbean Lets say the ParentClass is a Staff class and the models are Teacher, Principal, and Teacher Assistant. They all are staff members so that's why I have them extending Staff however a Staff class should never be instantiated. You should only ever have one of the sub classes. All three classes each used 4 traits that were the same across the models. For this reason I moved those to the parent class.

  1. Was this a good refactor?
  2. Should Staff extend model still?
  3. What would be the right route to test that all functionality works inside of the traits without having to write the same tests for all models.
Aug
25
2 months ago
Activity icon

Replied to Restructuring Models And Parent Model

@squiaios I'm not 100% convinced that adding a trait and having it use the existing traits is the right route, at this time. I'm wondering if ParentClass should really be an interface since ModelA, ModelB, ModelC are all types of ParentClass.

Activity icon

Started a new Conversation Restructuring Models And Parent Model

Can someone kindly give some sugggestions on how to better restructure these models and class. I'm trying to figure out the best way to back fill some unit tests for these three model classes that all extend the ParentClass. The ParentClass isn't really a model really. So that's something I'll need to confider changing. The purpose of the ParentClass is just to house all the common traits and behaviors that all 3 models share.

The ParentClass should never be instantiated so that would be why its an abstract class.

So in addition to better structuring what I currently have my goal is to think about how I should write unit tests for these traits. What I don't want to do is write the same tests for all 3 models. I'd rather find a way that I can write tests for the parent class to make sure it behaves correctly and then write a test that confirms that linkage so it would be proven that that behavior would work for all classes that use the ParentClass.

<?php

namespace App\Models;


class ModelA extends ParentClass
{
}
<?php

namespace App\Models;


class ModelB extends ParentClass
{
}
<?php

namespace App\Models;


class ModelC extends ParentClass
{
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

abstract class ParentClass extends Model
{
    use Concerns\TraitA,
    Concerns\TraitB,
    Concerns\TraitC,
    Concerns\TraitD,
}
Aug
17
2 months ago
Activity icon

Started a new Conversation Updating Polymorphic Many To Many

My goal here is to try and update the current members of a single group. So the first thing I want to do is grab the current group of a User if one exists and update that record's left at as being the current datetimestamp or the passed in value. Then I want to create a new record for that user as joining a new group with that same datetimestamp.

My question is if there is an easier way to perform the joinGroup method?

Important information.

  • Multiple types of models can belong to many groups but those models can belong to only one group at a time.

User.php

public function groups()
    {
        return $this->morphToMany(Group::class, 'member', 'group_members')
                    ->withTimestamps()
                    ->withPivot([
                        'joined_at',
                        'left_at',
                    ]);
    }

    public function currentGroup()
    {
        return $this->groups()
                    ->wherePivotNull('left_at')
                    ->first();
    }


    public function joinGroup($group, $dateJoined = null)
    {
        $dateJoined = $dateJoined ?? now();

        $this->currentGroup()->updateExistingPivot($this->currentGroup, ['left_at' => $dateJoined]);

        $this->groups()->attach($group->id, ['joined_at' => $dateJoined]);
    }
Jul
03
3 months 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
3 months 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
4 months 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.