xtremer360

xtremer360

Member Since 4 Years Ago

Kissimmee, FL

Full Stack Developer at 321

Experience Points 135,205
Experience Level 28

4,795 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 1024
Lessons
Completed
Best Reply Awards 8
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.

29 Jan
3 weeks ago

xtremer360 left a reply on Disable Exception Handling In Laravel Tests

Try

$this->withoutExceptionHandling();
28 Jan
3 weeks 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
4 weeks 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
1 month 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
1 month 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
1 month 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
1 month 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();
08 Jan
1 month ago

xtremer360 left a reply on Another Shot At Clarity

I hope this time around I have been to clarify any misunderstanding from the previous post. If there is anything that could use further clarification please tag team and I will do my best to explain.

xtremer360 started a new conversation Another Shot At Clarity

I wanted to make a new post about describing what I’m trying to achieve and help explain the parts of the app that are pertinent to my goal. This application has Properties, Rooms (Kitchen, Living Room, Bedroom, etc.), A Property can have many types of Rooms. When an inspector goes to a property they can make observations about each room in the property. Observations can be either a Test (different types of tests are Mold, Air, etc.), an Image (pictures taken of the room during the observation), Comment (further text describing the observation of the room).

My current database structure is the following.

PROPERTY_ROOM
id
property_id
room_id

OBSERVATIONS
id
property_room_id
observation_id
observation_type

OBSERVATION_PHOTOS
OBSERVATION_TESTS
OBSERVATION_COMMENTS

I have the following models to help with this.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\Pivot;

class PropertyRoom extends Pivot
{
    //
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ObservationImage extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['url', 'sort_order'];

    /**
     * Get the observation associated to the image.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function observation()
    {
        return $this->morphedToMany(Observation::class, 'observable');
    }
}

The following test I’m trying to upload an image to be assigned to a property_room but will also be saved as a morphed type for the observations table.

/** @test */
    public function an_administrator_can_upload_an_image_as_an_observation()
    {
        $this->withoutExceptionHandling();
        Storage::fake('s3');
        $file = UploadedFile::fake()->image('observation.jpg');

        $signedInUser = factory(User::class)->states('administrator')->create();
        $observation = factory(Observation::class)->create();

        $response = $this->actingAs($signedInUser)->json('POST', '/observations/'.$observation->id.'/images', $this->validParams([
            'image' => $file,
        ]));

        $response->assertStatus(200);
        tap($observation->images->first(), function ($image) use ($observation, $file) {
            dd($image->observation);
            $this->assertEquals('observations/'.$observation->id.'/'.$file->hashName(), $image->url);
            $this->assertEquals(1, $image->sort_order);
        });
    }

The code needs modified to work toward the desired solution.

<?php

namespace App\Http\Controllers;

use App\Models\Observation;
use App\Jobs\ProcessObservation;
use App\Http\Requests\StoreObservationImageRequest;
use App\Http\Resources\Observation as ObservationResource;

class ObservationImagesController extends Controller
{
    /**
     * @param  \App\Http\Requests\StoreObservationImageRequest  $request
     * @param  \App\Models\Observation  $observation
     * @return
     */
    public function store(StoreObservationImageRequest $request, Property $property, Room $room)
    {
        $path = request()->file('image')->store('property-rooms/images');

        $file = Storage::disk('s3')->put('property-rooms/', request()->image, 'public');

        $max = $this->observation->images()->max('sort_order');

        $this->observation->images()->create([
            'url' => $file,
            'sort_order' => $max + 1,
        ]);

        return new ObservationResource($observation);
    }
}

xtremer360 left a reply on Difficult Polymorphic Relationships

So your saying with that structure you are going to have maybe 50 records in the rooms table that have the name Kitchen

xtremer360 left a reply on Difficult Polymorphic Relationships

There's different types of tests such as Mold, AIr, Water, etc.

xtremer360 left a reply on Difficult Polymorphic Relationships

@bobbybouwmann @staudenmeir @martinbean I have updated this post with additional information to help understand what I'm trying to do.

xtremer360 left a reply on Difficult Polymorphic Relationships

@staudenmeir I would use those, however, the problem is having to scope it to the property_room_id which references an id of a pivot table.

xtremer360 started a new conversation Difficult Polymorphic Relationships

I have the following database structure and trying to figure out how to handle this thought process. If I am inside of a /property/{property}/room/{room} route and on the page where I can go to create a new observation (photo/test/comment} what would be the recommendation for the route. The observation table record isn’t created until the photo/test/commment record is created. This process doesn’t work out restfully. The hardest part of this is trying to figure out the relationships.

PROPERTY_ROOM
id
property_id
room_id

OBSERVATIONS
id
property_room_id
observation_id
observation_type

OBSERVATION_PHOTOS
OBSERVATION_TESTS
OBSERVATION_COMMENTS
04 Jan
1 month ago

xtremer360 started a new conversation Policy Actions For Pivot Models

I am currently trying to test that an administrator has the right permissions to attach a room to a property. I created a StorePropertyRoomRequest class for handling the incoming request of validating that they have the rights to make the request and handling the rules. I also have the policy associated with the pivot model.

I understand that method names on policies can be named anything however is there something I can call it to better explain that I'm wanting to check that a user can attach a room to a property?

Also, how can I pass in the room to the policy as well?

I'm wanting to test the following rules.

  1. A user must be an administrator.
  2. The property must be attached to the business unit that the user is apart of.
  3. The room must be attached to the business unit that the user is apart of.

StorePropertyRoomRequest.php

public function authorize()
{
    $room = Room::find($this->room);

    return $this->user()->can('create', PropertyRoom::class);
}

PropertyRoomPolicy

public function create(User $user)
{
    dd('testing');
    return $user->isAdministrator() || $user->isInspector() || $user->isManager();
}
30 Dec
1 month ago

xtremer360 started a new conversation Returning Var From DB Transaction

I'm asking to find out if this is correct way I should be returning the property inside of the DB::transaction closure as well ask if there are any suggestions on how to structure these calls in the controller.

<?php

namespace App\Http\Controllers;

use DB;
use App\Models\Customer;
use App\Models\Property;
use Illuminate\Http\Request;
use App\Jobs\ProcessPropertyMainPhoto;

class PropertiesController extends Controller
{
    /**
     * Store a newly created property for a business unit..
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $this->authorize('create', Property::class);

        $property = DB::transaction(function () use ($request) {
            $customer = Customer::create([
                'first_name' => $request->customer['first_name'],
                'last_name' => $request->customer['last_name'],
                'email' => $request->customer['email'],
                'home_phone' => $request->customer['home_phone'],
                'mobile_phone' => $request->customer['mobile_phone'],
            ]);

            $customer->address()->create([
                'address1' => $request->customer['address1'],
                'address2' => $request->customer['address2'],
                'city' => $request->customer['city'],
                'state' => $request->customer['state'],
                'zip' => $request->customer['zip'],
            ]);

            $property = auth()->user()->businessUnit->properties()->create([
                'appointment_date' => $request->appointment_date,
                'notes' => $request->notes,
                'office_phone' => $request->office_phone,
                'creator_id' => auth()->user()->id,
                'customer_id' => $customer->id,
            ]);

            $property->address()->create([
                'address1' => $request->address1,
                'address2' => $request->address2,
                'city' => $request->city,
                'state' => $request->state,
                'zip' => $request->zip,
            ]);

            ProcessPropertyMainPhoto::dispatch($property);

            return $property;
        });

        return response()->json(['property' => $property, 'status' => 'success'], Response::HTTP_CREATED);
    }

    /**
     * Update a property for a business unit.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Property  $property
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Property $property)
    {
        $this->authorize('update', $property);

        $proprty = DB::transaction(function () use ($request, $property) {
            $property->customer->update([
                'first_name' => $request->customer['first_name'],
                'last_name' => $request->customer['last_name'],
                'email' => $request->customer['email'],
                'home_phone' => $request->customer['home_phone'],
                'mobile_phone' => $request->customer['mobile_phone'],
            ]);

            $property->customer->address()->update([
                'address1' => $request->customer['address1'],
                'address2' => $request->customer['address2'],
                'city' => $request->customer['city'],
                'state' => $request->customer['state'],
                'zip' => $request->customer['zip'],
            ]);

            $property->update([
                'appointment_date' => $request->appointment_date,
                'notes' => $request->notes,
                'office_phone' => $request->office_phone,
            ]);

            $property->address()->update([
                'address1' => $request->address1,
                'address2' => $request->address2,
                'city' => $request->city,
                'state' => $request->state,
                'zip' => $request->zip,
            ]);

            ProcessPropertyMainPhoto::dispatch($property);

            return $property;
        });

        return response()->json(['property' => $property, 'status' => 'success'], Response::HTTP_OK);
    }
}

27 Dec
1 month ago

xtremer360 left a reply on AssertResponseStatus Does Not Exist.

I believe its just assertStatus()

xtremer360 started a new conversation File Upload To S3 Queued Job

I'm asking to find out if I the Job code below is the correct use for it or not or if there's another level of extraction that is needed to separate the concerns from the Upload of the file to s3 to updating the URL for the database main_photo_url field property.

<?php

namespace App\Jobs;

use App\Models\Property;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class ProcessProperty implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $property;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Property $property)
    {
        $this->property = $property;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->property->update([
            'main_photo_url' => Storage::disk('s3')->put('properties/'.$this->property->id, request()->main_photo_url, 'public'),
        ]);
    }
}
18 Dec
2 months ago

xtremer360 left a reply on Not Seeding Test Database

If in the Makefile I filter to a specific test it will pass however if I run phpunit by itself without the filter of a specific test then it'll fail all but a couple of tests.

xtremer360 left a reply on Not Seeding Test Database

@wilk_randall I don't believe I can do that with the Makefile I have set up.

xtremer360 started a new conversation Not Seeding Test Database

I'm trying to figure out why when I run make command it doesn't seed my testing database because when my test gets to the method I"m testing it says there are no roles in the database.

<?php

namespace Tests;

use Illuminate\Foundation\Testing\DatabaseTransactions;

class IntegrationTestCase extends TestCase
{
    use DatabaseTransactions;
}

Makefile

build:
    php artisan migrate:refresh --env="testing"
    php artisan db:seed --class="RolesTableSeeder" --env="testing"
    phpunit
APP_ENV=testing
APP_KEY=base64:zH6ySDqMKvAtbBwTFiKDK07/3cQoPOSGhrcEFM2HcmE=
BCRYPT_ROUNDS=4
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_CONNECTION=sync
MAIL_DRIVER=array
DB_HOST=127.0.0.1
DB_PORT=33060
DB_CONNECTION=mysql
DB_DATABASE=ets_laravel_testing
DB_USERNAME=homestead
DB_PASSWORD=secret
13 Dec
2 months ago

xtremer360 left a reply on Video On Model Property Testing

@talinon Thank you for your response as I have watched that series before however that doesn't answer provide insight as to what other devs do.

xtremer360 left a reply on Video On Model Property Testing

I've seen it done more than once but that helps. I've talked to a few people that are against because in their opinion it is testing the framework. To me, if it's not apart of the framework its not testing the framework. I think it is testing the parts of the application that you are constructing.

Can anyone else give their insight on this?

xtremer360 started a new conversation Video On Model Property Testing

At one point I saw a video here on Laracasts that shows Jeffrey Way writing a test for a property on a model. Does anyone know which video it was? The reason, why I'm asking, is that I'm having a discussion about doing such tests and would like to use it as a reference.

06 Dec
2 months ago

xtremer360 left a reply on Add Playing Time To Episode List?

This would be considered under Requests category.

05 Dec
2 months ago

xtremer360 started a new conversation Multiple Situations For Same Action

I have a form that will create a new team. When creating the team it can include an array of two players or the user can select two players from a multiselection dropdown. Is this ideal or should it be rethought how to handle this action?

03 Dec
2 months ago

xtremer360 left a reply on Modifying Form Data From Request

@snapey How would you do that?

xtremer360 left a reply on Modifying Form Data From Request

This is what I'm currently working on inside of a Staff model.

    {
        $baseData = ['started_at' => $this->started_at];
        dd($data);
        foreach ($data as $patientData) {
            $this->patients()->create(array_merge($patientData, $baseData), ['joined_on' => Carbon::now()]);
        }

        dd($this->patients);

        return $this;
    }```

xtremer360 left a reply on Modifying Form Data From Request

Right I've already validated the data. The problem is the field in my db is called height which is the total inches.

xtremer360 left a reply on Modifying Form Data From Request

What data is being validated? At the point of trying to calculate the height would have its data already validated. The feet and inches post values.

xtremer360 left a reply on Modifying Form Data From Request

I've heard that its best to not modify the request inside of model events and/or observers.

xtremer360 started a new conversation Modifying Form Data From Request

I've been told all types of possible solutions for this problem and haven't come to which direction I want to go. The following are suggestions have been made.

  • Validation Request (Feel that this problem isn't validating data)
  • Middlware (Manipulating post data like TrimStrings does.
  • A Normalizer class (Don't feel like adding another layer in my application at this time is the best way to go.

Situation

A have a form that you can add multiple patients at the same time. A user has stats like height but in the form the fields are feet and inches. What I'm wanting to do is before it saves the patients to the DB then to convert those values in the request to a height property that gets saved to the DB

Any opinions that can be discussed about this?

29 Nov
2 months ago

xtremer360 left a reply on Validation In Controller

@primordial I don't disagree with your statement however if you only have a couple of fields why create a new file just to move validation to a new file. Validation is acceptable to also keep in the controller but should be the first few lines in a controller method before any other code is executed.

22 Nov
2 months ago

xtremer360 left a reply on Form Validation In Select Box

@sanjayacloud Please provide us with more than "but it's not work" what type of data are you sending to the validator. At the top of the controller method that you are sending your post data to you can do dd(request()->all()) to show us what you are submitting with your form.

16 Nov
3 months ago

xtremer360 left a reply on Black Friday 2018 Not Working

@fiiine Where did you get this year's coupon from?

21 Sep
4 months ago

xtremer360 left a reply on Look Up Table For Use In A Seed File

@D9705996 I don't believe that will help me. I'm trying to set a value for each of the rows for the match types.

xtremer360 started a new conversation Look Up Table For Use In A Seed File

I have the following Eloquent call to my database that retrieves 10-12 rows. What I need to do for the purposes of a seeder is assign a value (int 1-100) to each of those rows so that I can declare the chance of one type being used more than the others. So as you can see from this snippet currently in my seed file it will just grab one of the types from the database however I want to give it a look up table to be able to say which types are more likely to be used than the others.

$match = $event->matches()->save(factory(Match::class)->create([
    'match_type_id' => MatchType::inRandomOrder()->first()->id,
]));
private function chance(int $percent)
{
    return rand(0, 100) < $percent;
}
13 Sep
5 months ago

xtremer360 left a reply on TravisCI Build DB Connection Times Out

Anyone have any further ideas on this?

12 Sep
5 months ago

xtremer360 started a new conversation Class Based Model Factories With States

I have the following two tests. One tests the length of how long wrestlers won championships and the other tests current champions (not lost) and past (lost) championships. If you wondering about the Fascade Factory I got it from the following link.

https://tighten.co/blog/tidy-up-your-tests-with-class-based-model-factories

I'm trying to figure out what I can do to the ChampionshipFactory class so that it can accept states for the championship. In the link I provided it shows how to add states however I have a use case of having states of current and past where current has a won_on date that would need to be the set based on the title's introduced_at field. Then the lost_on would be a time after the title was won. So I'm trying to figure out how I can get BOTH tests to pass.

/** @test */
    public function it_can_get_the_champion_with_the_longest_title_reign()
    {
        $wrestlerA = factory(Wrestler::class)->create();
        $wrestlerB = factory(Wrestler::class)->create();
        $wrestlerC = factory(Wrestler::class)->create();
        $title = factory(Title::class)->create();

        ChampionshipFactory::forWrestler($wrestlerA)->forTitle($title)->wonOn(Carbon::parse('2018-01-01'))->lostOn(Carbon::parse('2018-01-10'))->create();
        ChampionshipFactory::forWrestler($wrestlerB)->forTitle($title)->wonOn(Carbon::parse('2018-01-10'))->lostOn(Carbon::parse('2018-01-19'))->create();
        ChampionshipFactory::forWrestler($wrestlerC)->forTitle($title)->wonOn(Carbon::parse('2018-01-19'))->lostOn(Carbon::parse('2018-01-20'))->create();

        $champions = $this->repository->longestTitleReigns($title);

        $this->assertTrue($champions->contains($wrestlerA));
        $this->assertTrue($champions->contains($wrestlerB));
    }
/** @test */
    public function current_titles_held_returns_a_collection_of_active_titles()
    {
        $wrestler = factory(Wrestler::class)->create();
        $currentChampionshipA = ChampionshipFactory::states('current')->forWrestler($wrestler)->create();
        $currentChampionshipB = ChampionshipFactory::states('current')->forWrestler($wrestler)->create();
        $pastChampionship = ChampionshipFactory::states('past')->forWrestler($wrestler)->create();

        $currentTitlesHeld = $wrestler->currentTitlesHeld;

        $this->assertTrue($currentTitlesHeld->contains('id', $currentChampionshipA->title_id));
        $this->assertTrue($currentTitlesHeld->contains('id', $currentChampionshipB->title_id));
        $this->assertFalse($currentTitlesHeld->contains('id', $pastChampionship->title_id));
    }
<?php

use Carbon\Carbon;
use App\Models\Title;
use App\Models\Wrestler;
use App\Models\Championship;

class ChampionshipFactory
{
    private $wrestler;
    private $title = null;
    private $wonOn = null;
    private $lostOn = null;
    private $titleDefenses = 0;
    private $states = [];

    public function __construct()
    {
        $this->resetProperties();
    }

    public function states($states)
    {
        $this->states = $states;

        return $this;
    }

    public function create()
    {
        if (is_null($this->title)) {
            $this->title = factory(Title::class)->create();
            $this->wonOn = $this->title->introduced_at->copy()->addMonth();
        } elseif (!is_null($this->title) && is_null($this->wonOn)) {
            if ($this->title->champions()->exists()) {
                $dateLastChampionWon = $this->title->fresh()->currentChampion->pivot->won_on;
                $dateOfTitleChange = $dateLastChampionWon->copy()->addMonth();
                $this->title->fresh()->currentChampion->loseTitle($this->title, $dateOfTitleChange);
                $this->wonOn = $dateOfTitleChange;
            } else {
                $this->wonOn = $this->title->introduced_at->copy()->addMonth();
            }
        }

        $champion = factory(Championship::class)->states($this->states)->create([
            'wrestler_id' => $this->wrestler->id ?? factory(Wrestler::class)->create()->id,
            'title_id' => $this->title->id,
            'won_on' => $this->wonOn,
            'lost_on' => $this->lostOn,
            'successful_defenses' => $this->titleDefenses,
        ]);

        $this->resetProperties();

        return $champion;
    }

    public function forWrestler(Wrestler $wrestler)
    {
        $this->wrestler = $wrestler;

        return $this;
    }

    public function forTitle(Title $title)
    {
        $this->title = $title;

        return $this;
    }

    public function wonOn(Carbon $start)
    {
        $this->wonOn = $start;

        return $this;
    }

    public function lostOn(Carbon $end)
    {
        $this->lostOn = $end;

        return $this;
    }

    public function withSuccessfulTitleDefenses($count)
    {
        $this->titleDefenses = $count;

        return $this;
    }

    public function resetProperties()
    {
        if (!is_null($this->wrestler)) {
            $this->wrestler = null;
        }

        if (!is_null($this->title)) {
            $this->title = null;
        }

        if ($this->titleDefenses != 0) {
            $this->titleDefenses = 0;
        }

        if (! is_null($this->wonOn)) {
            $this->wonOn = null;
        }

        if (! is_null($this->lostOn)) {
            $this->lostOn = null;
        }
    }
}

11 Sep
5 months ago

xtremer360 left a reply on TravisCI Build DB Connection Times Out

Does anyone see anything that I have done wrong?

xtremer360 left a reply on TravisCI Build DB Connection Times Out

It appears no matter what I do I continue to get the following error.

1) Tests\Feature\Event\AddEventTest::users_who_have_permission_can_view_the_add_event_page
Illuminate\Database\QueryException: SQLSTATE[HY000] [2002] Connection timed out (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

.env.travis

APP_ENV=testing
APP_KEY=
APP_DEBUG=true

DB_CONNECTION=testing
DB_TESTING_HOST=127.0.0.1
DB_PORT=
DB_TESTING_DATABASE=ringside_testing
DB_TESTING_USERNAME=root
DB_TESTING_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync

phpunit.xml

<env name="DB_CONNECTION" value="testing"/>

.travis.yml

# Required to run your project under the correct environment.
language: php

# Versions of PHP you want your project run with.
php:
  - 7.1

services:
  - mysql  

# Commands to be run before your environment runs.
before_script:
  - cp .env.travis .env
  - mysql -e 'CREATE DATABASE ringside_testing;'
  - composer self-update
  - composer install --no-interaction
  - php artisan key:generate
  - php artisan migrate 

script:
  - vendor/bin/phpunit

cache:
  directories:
    - vendor  

config/database.php

'testing' => [
            'driver' => 'mysql',
            'host' => env('DB_TESTING_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_TESTING_DATABASE', 'forge'),
            'username' => env('DB_TESTING_USERNAME', 'forge'),
            'password' => env('DB_TESTING_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'InnoDB',
        ],

xtremer360 left a reply on TravisCI Build DB Connection Times Out

@pardeepkumar Thank you for your response, however as an aside do you know and can explain why I am receiving this error when it gets to my testsuite.

xtremer360 left a reply on TravisCI Build DB Connection Times Out

I have edited my original post to include more information about the problem.

10 Sep
5 months ago

xtremer360 started a new conversation TravisCI Build DB Connection Times Out

I'm trying to figure out why when I run my CI Build it says that my connection to the database times out.

The command "php artisan key:generate" exited with 0.
31.27s$ vendor/bin/phpunit
PHPUnit Pretty Result Printer 0.19.14 by Codedungeon and contributors.
==> Configuration:~/build/me/app/vendor/codedungeon/phpunit-result-printer/phpunit-printer.yml
PHPUnit 7.3.5 by Sebastian Bergmann and contributors.
 ==> Tests\Feature\Module\MyTest⚈
Time: 31.12 seconds, Memory: 24.00MB
There was 1 error:
1) Tests\Feature\Module\Test::my_test_method
Illuminate\Database\QueryException: SQLSTATE[HY000] [2002] Connection timed out (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

Caused by
Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000] [2002] Connection timed out