paul-a-byford

paul-a-byford

Member Since 7 Months Ago

Experience Points 7,000
Experience Level 2

3,000 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 65
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

29 Jun
2 weeks ago

paul-a-byford commented on Frontend Authorization Brainstorming

I think option 2 would work well on a Vue SPA, where the Vue app is fetched once at login and subsequent interactions via laravel are via an API. Particularly when the authorisation permissions are quite dynamic and change during a single session - the option 2 pattern would mean each API call would include a fresh set of Auth grants. What do you think?

26 Jun
3 weeks ago

paul-a-byford left a reply on Adding Groups Of Assertions To Tests

Roni - Based on the description it sounds like a composition design pattern might help with your usecase. I've moved across from another language so less familiar with the specifics of how the pattern is appllied in php/laravel - but seen it work well to solve similar problems elsewhere.

example link https://sergeyzhuk.me/2017/01/08/composition-over-inheritance/

did you get any further in identifying specific options?

paul-a-byford left a reply on Elegant Eloquent Where

@RONI - Thanks, ->where('user_id',auth()->id()) was the missing piece.

25 Jun
3 weeks ago

paul-a-byford started a new conversation Elegant Eloquent Where

Hey everyone - what more elegant ways would you recommend solving the following.

Context - project management app. Each project has team members, team members have access permissions door individual project - eg read only permission, edit permissions etc

Requirement - return an authorisation policy that checks user permissions for a project and returns true if they have edit permissions.

Models - user, project, member

My first thought was something like the below would pull a list of all project members with write permissions; $project->members() ->where('permission', 'write')

But not clear on how I refine the query to one specific user and check if that user is the same as the user model instance I get passed by the policy

19 Jun
1 month ago

paul-a-byford left a reply on Testing Json And Enum Column Types With Sqlite

thanks for the advice. i've reworked the application to replace all the database enum columns with reference tables and other data types. i can run sqlite now, but sqlite causes issues with php unit testing because of the way it retrieves integers so I'm still interested in seeing how i can speed things up using my sql.

i tried implementing the solution @fastsol mentioned my code is below. but i'm not seeing the performance benefit, i think this is because my overiding method is not being called by the trait. do you have any suggestions on how to correct it?

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    use RefreshDatabase;

    protected function refreshTestDatabase()
    {

        if (! RefreshDatabaseState::$migrated) {
            DB::unprepared(file_get_contents(database_path('migrations_2019_06_19.sql')));

            $this->artisan('migrate');

            $this->app[Kernel::class]->setArtisan(null);

            RefreshDatabaseState::$migrated = true;
        }

        $this->beginDatabaseTransaction();
    }

}

paul-a-byford left a reply on SQLite :memory: Testing Results Inconsistent With MySql?

After further investigation I discovered the values returning blank were caused by sqlite returning integer column values as a string, rather than returning them as a numeric value. Eg sqlite returns the value "1" rather than 1, consequently the accessors I created returned null whenever it was called.

This behaviour of a string being returned for integers also causes some of my json testing to fail for fields where i don't use accessors. eg;

// my php unit test...

$attributes = [
    'project_id' = 1,
    'project_title' = 'My Test Project Title'
]

$user->projects()->update($attributes);

// test passes with mysql and sqlite
$this->assertDatabaseHas('matches', $item); 

// test fails with sqlite (but passes with mysql)
$this->json('GET', '/api/s/projects')
    ->assertJsonFragment($attributes);

error returned on failure is ;

Unable to find JSON fragment:

[{"project_id":1}]

then in the json i find 

"seeker_id":"1"


i found this issues from 2014 which puts the cause due to pdo drivers and that the mysql driver passing them through as numerics, whereas sqlite does not. https://github.com/laravel/framework/issues/3548 . their suggested workaround is to explicitly cast the attributes to an integer is an accessor. this would solve it but seems very laborious. 

are there any other suggested options to solve this problem and be able to test on sqlite without attribute specific accessors for all fields?
18 Jun
1 month ago

paul-a-byford started a new conversation SQLite :memory: Testing Results Inconsistent With MySql?

Hey Everyone, I've got an app with API resources where I've been using MySql for php unit tests. I attempted to move across to use sqlite :memory: as the testing having read about the potential speed/performance benefits.

After making the change I found a few examples of strange test results, where the API resource has started returning certain attributes values as blank, rather than than the value it should return.

More specifically the cases I've found of this problem seem to relate to where I've used eloquent Accessors to return the value. The strange aspect is that I use accessors on multiple fields, some return fine and others do not.

Any advice appreciated!

11 Jun
1 month ago

paul-a-byford started a new conversation Testing Json And Enum Column Types With Sqlite

Hey Everyone, I attempted to switch to sqlite (in memory) to speed up running phpunit testing with the RefreshDatabase trait. Currently I'm using mysql and found that RefreshDatabase adds about 2 seconds to the run time to process the migrations.

I discovered sqlite doesn't seem to support column types enum or json.

Can you recommend a way around this with sqlite, or any alternate approaches to speed up testing execution on mysql?

Thanks

07 Jun
1 month ago

paul-a-byford started a new conversation Architecture - Process Queue On Trigger

Hey Everyone, I've got an interesting one and would appreciate your thoughts on the most elegant way to go about architecting it.

Requirement is for the app to allow users to request certain actions but only process the actions after certain future conditions are met. For example allow a user to request access to a secure file, but only process the actions to provide access to the file and email a link to the file after a moderator has approved the request.

The way I'm conceptualising it at the moment is to create a list of requested actions and have triggers which process the actions, something like queues (the lists) and events (triggers). However concepualising this way doesn't seem to be how queues can be used.

What more elegant ways of architecting for this requirement would you recommend?

10 May
2 months ago

paul-a-byford left a reply on Eloquent Create Call To A Member Function On Null

thanks. that solved it! I had to make a slight variation of calling fresh() on team rather than conversation.

$team->fresh()->conversation->sendMessage($request->message);

does this mean laravel is using some form of caching when accessing relationships as properties?

paul-a-byford started a new conversation Eloquent Create Call To A Member Function On Null

hey everyone. i'm implementing a team send message function that should accept messages sent from the browser and add them to the database. I've tried using the code below to create a conversation if one does not exist, however i get an error call to a member function on null.

// send message function

            $team->conversation()->create([
                'type' => 'private',
            ]);
        }

        $team->conversation->sendMessage($request->message);```

it seems my call to $team->conversation->sendMessage() generates the problem, as if the conversation does not exist. but when i check the database i can see the conversation was created. 

what am i not understanding here?
28 Mar
3 months ago

paul-a-byford left a reply on API Resource Collection N+1 Performance

@manelgavalda @staudenmeir thank you. a combination of both your suggestions has reduced the query volume significantly.

a follow on question - if i were to add a tag model and a pivot table conversation_tag, what is the correct way to eager load pivot table relations?

eg is it;

$users->load('conversations.messages.conversation.conversation_tag');

plus would i need to do anything else, such as explicitly define a file for the pivot model?

27 Mar
3 months ago

paul-a-byford left a reply on API Resource Collection N+1 Performance

unfortunately this did not solve the problem of multiple database queries. to help explore the issue more easily I created a quick basic repo here to illustrate the problem https://github.com/paul-a-byford/nplus1.git

in this repo I have created 3 models & tables for user, conversation, messages. i've also created seeders and pulled in telescope

when hitting the /messages route on this repo you will see over 100 database queries, triggered by an attempt to pull in an attribute from a distant relationship

// App\Http\Resources\Message.php

   public function toArray($request)
    {
        return [
            'message' => $this->message,
            'message_is_read' => $this->is_read,
            'avatar_url' => $this->conversation->user->avatar_url,
        ];
    }

how would you recommend minimising the number of database queries. is there a way to eager load relationships for his scenario?

22 Mar
3 months ago

paul-a-byford left a reply on API Resource Collection N+1 Performance

thanks. see code excerpts below...

here is my controller where i lazy eager load in some of the relationships

// mycontroller.php

public function show(Role $role)
    {
        $role->load(
            'matches',
            'matches.role',
            'matches.conversation'
            'matches.person'
        );

        return new BundleResource($role);
    }

here is the resource definition for the first api resource

// BundleResource.php

    public function toArray($request)
    {
        return [
            'role_id' => $this->id,
            'role_title' => $this->title,
            'matches' => MatchResource::collection($this->matches),
        ];
    }

here is the resource definition for a second api resource used by the above

// MatchResource.php

   public function toArray($request)
    {
        return [
            'id' => $this->id,
            'role_id' => $this->role->id,
            'person' => new PersonResource($this->person),
            'status' => $this->status,
            'conversation' => $this->when($this->conversation, function(){
                return
                [
                    'id' => $this->conversation->id,
                    'match_id' => $this->conversation->match_id,
                    'latest_message' => new Message($this->conversation->messages()->latest()->first()),
                ];
            }),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s')
        ];
    }

paul-a-byford started a new conversation API Resource Collection N+1 Performance

hey everyone, please can you offer your thoughts on how best to solve a performance problem when I use API resource collections.

i'm finding from laravel telescope that the resource collection I've created executes 200 database queries to generate the response!

i've created an api resource class using artisan and updated the generated toArray method to return the various attributes I require on the resource. this includes items I fetch via relationships - which seems to be the cause of the multiple database queries.

from my controller I fetch the raw data as an eloquent collection and pass that to the static collection method on the api resource - similar to as described in the docs https://laravel.com/docs/5.8/eloquent-resources#resource-collections

i've attempted to use lazy eager loading in my controller before passing it to the api resource collection method, which reduced the query number a little. on attempted to debug it seems that the api resource collection method maps through the collection and calls toArray each time. when the toarray runs each time laravel runs individual database queries each time, rather than using the data I already eager loaded in the controller.

thanks