Synchro

Member Since 1 Year Ago

Experience Points
1,830
Total
Experience

3,170 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
6
Lessons
Completed
Best Reply Awards
0
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.

  • Community Pillar

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

Level 1
1,830 XP
Apr
11
23 hours ago
Activity icon

Replied to Can't Shake Off Double-wrapping Of Resource Collections

I think I may have found a cause. As I showed, my resource collection also has a with method that adds on additional metadata. Because this adds top-level metadata, it needs to put existing data into a data element – except that it shouldn't do that if there is already a data element. If I comment out the with method, the double-wrapping goes too. I can only think this is a Laravel bug.

Activity icon

Replied to Can't Shake Off Double-wrapping Of Resource Collections

That's a good thought, however, I would expect that to fall squarely into the "Laravel will never let your resources be accidentally double-wrapped" description, since my resource collection already contains a data element.

Furthermore, when I removed pagination, it still happens. I have also been using Spatie's JSON paginator, but removing that didn't help either.

Activity icon

Started a new Conversation Can't Shake Off Double-wrapping Of Resource Collections

I have JSON:API-style resources in Laravel 8.36 like this:

    public function toArray($request): array
    {
        if (is_null($this->resource)) {
            return [];
        }

        return [
            'type'          => 'thing',
            'id'            => (string)$this->uuid,
            'attributes'    => [
                //...
            ],
            'links'         => [
                'self' => route('things.show', ['thing' => $this->uuid]),
            ],
        ];
    }

That are bundled into collections like this (note manual suppressing of wrapping):

    public function toArray($request): array
    {
        ThingResource::withoutWrapping();

        return [
            'data' => ThingResource::collection($this->collection),
        ];
    }

    public function with($request): array
    {
        return [
            'links'    => [
                'self' => route('things.index'),
            ],
        ];
    }

and I have disabled wrapping globally in the app service provider, as per the docs:

    public function boot()
    {
        JsonResource::withoutWrapping();
    }

And yet my resource collections turn up like this:

{
  "data": {
    "data": [
      {
        "type": "things",
        "id": "f40666e1-0c93-4646-8e64-a19e07dea36c",
        "attributes": {
            //...
        },
    ],
  },
  "links": {
    "self": "http:\/\/localhost:8081\/carriers"
  },

while the docs say:

You may be wondering if this will cause your outermost resource to be wrapped in two data keys. Don't worry, Laravel will never let your resources be accidentally double-wrapped, so you don't have to be concerned about the nesting level of the resource collection you are transforming:

The only thing I can see that's possibly an issue is that the outer data element is an object while the inner one is an array. The array syntax is correct.

How can I prevent that double wrapping that the docs promises it won't do?

Apr
10
1 day ago
Activity icon

Started a new Conversation Is Is Possible To Stream Large File Requests?

A typical request to an external web service might require submitting a file, for example this request to Azure cognitive services using a Guzzle client:

    $response = $this->client->post(
        'analyze',
        [
            'query' => [
                'language' => 'en',
                'visualFeatures' => 'Description',
            ],
            'headers' => [
                'content-type' => 'application/octet-stream',
            ],
            'body' => file_get_contents($this->filePath),
        ]
    );

That works fine, but requires reading the entire file at $this->filePath into memory before making the request. That's fine for typical images, but starts to become a problem with larger audio or video files which could easily be larger than PHP's memory allocation.

Is there some way to stream the contents of the file into the request rather than reading the whole thing into memory first?

Apr
05
6 days ago
Activity icon

Replied to API Resource Tries To Populate Empty Resource Object

My resource uses the standard JsonResource class, which includes this behaviour, trapping exactly this scenario:

    public function toArray($request)
    {
        if (is_null($this->resource)) {
            return [];
        }

        return is_array($this->resource)
            ? $this->resource
            : $this->resource->toArray();
    }

and if I dd($product->carrier), I get null. My custom resources override toArray in the style the docs describe, so that behaviour is lost. This would be useful to mention there.

The option to return a semi-populated resource is there in withDefault, but I'm not using that.

I guess I have to duplicate this handling manually in every resource. That's a shame as it's very ugly!

Activity icon

Replied to API Resource Tries To Populate Empty Resource Object

It may be that the right way to deal with this is in the controller, where the belongsTo could do some kind of findOrFail, but I'm expecting that to be automatic, so I think I'm missing something else.

Activity icon

Replied to API Resource Tries To Populate Empty Resource Object

I know how to check for a null value, and what null coalesce is for, but that's simply addressing the symptom, not the cause. I expect it to not return a resource at all in that case – an empty array or object perhaps, or a 404 would even be reasonable; How to do any of those is also not the question. I don't think anyone would expect an API to return resources with parts missing to indicate "nothing here". I really want to know what the expected behaviour of resources should be in those circumstances, since I expect it's a very, very common scenario where I'd expect some kind of useful default behaviour, i.e. that Laravel won't even attempt to populate a Resource when there is no data.

Activity icon

Started a new Conversation API Resource Tries To Populate Empty Resource Object

I have a model that has a belongsTo relationship, but it may not be populated:

    public function carrier(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'carrier_product_id');
    }

A controller that hits this returns a resource:

    public function carrier(Product $product)
    {
        ProductResource::withoutWrapping();

        return new ProductResource($product->carrier);
    }

and the resource looks like:

    public function toArray($request): array
    {
        return [
            'type'          => 'products',
            'id'            => $this->serial,
            'attributes'    => [
                'serial'                => $this->serial,
                'status'                => $this->status,
            ],
        ];
    }

however, if the relationship is empty, it still tries to populate the resource, so I get an error saying Attempt to read property \"serial\" on null on $this->serial.

I was under the impression that the base Resource class handled this automatically, but apparently not. How should this be done?

Mar
31
1 week ago
Activity icon

Replied to OAuth Token Is Revoked?

I managed to track this down. It was a Postman problem. After fetching an access token, it displays it in a window with a "use token" button. You press that and it puts the tokens into variables that get used by other requests. At least that's how it's meant to work. What actually happens is that it doesn't store the token in the variables, and uses some old token instead, but since the first 50 or so bytes are mostly identical in all tokens, and it doesn't show the whole thing, it's hard to spot. It turns out you have to manually hit "save" on the screen that's used for requesting the token in order for it to actually put it in the variables.

Thank you for making me question my assumptions, you've been an excellent rubber duck 🦆

Activity icon

Replied to OAuth Token Is Revoked?

That's what I'm doing. I'm passing the token I get in an Authorization header prefixed with a Bearer label. For testing I'm using Postman's stock OAuth mechanism for getting a token and then using it in headers for API requests (which it does automatically). The initial call to the /oauth/token endpoint works fine – that's where I get the token from; it's using it afterwards that's the problem.

Activity icon

Started a new Conversation OAuth Token Is Revoked?

I'm using Passport in L8 with a password grant. I can request an auth token by passing the client id, secret, username and password, which succeeds. But when I try to use it for subsequent requests, it fails with this error:

The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.

As far as I can see it's none of those things; everything visible lines up. At the client end it appears as a 401 Unauthorized with an Unauthenticated message. I can see the access token is in the database and is not expired, the token received from authenticating is included in an Authorization: Bearer... header, and I have normal auth:api middleware. One curiosity is that I'm even getting this error from routes that do not have this middleware (and do not normally require auth at all).

Both my local config and a staging deployment are acting the same way. It was all working fine until recently, so it's clearly something I've changed, however, I'm not aware of having touched anything to do with auth. How can I track down what's going wrong?

Mar
29
1 week ago
Activity icon

Started a new Conversation What Triggers Expired Password Reset Cleanup?

I happened to notice that I have records in my password_resets table that are nearly a year old (in a Laravel 6 app). Running artisan auth:clear-resets clears them as expected, but I assume this should be happening automatically as a scheduled job. I can't find any mention of such a thing in the password reset docs in L6 or in L8 either. Before I add it to my own scheduled tasks, is there something I've missed? How is this normally triggered?

Activity icon

Replied to Should API Validation Generate 404 Responses For Missing Items?

But how do I make those rule checks occur with route model binding? That rule definition is in the controller, which isn't involved until after that's happened (AFAIK). Isn't the exists:products rule implicit in the bound model?

If I'm doing:

    Route::post('{product}/thing', [ProductController::class, 'thing']);

and {product} is in the wrong format (which involves calculating a hash, so it's not regexable – that's what's my Serial() Rule class does), how can I get in there to apply that check and make it return a 422? Do I need to use a closure for that param within the Route or something?

Say I was using UUIDs to identify my products – how would I make this give a 422 for an invalid UUID, rather than a 404 for failing to find it in the DB? The main point of this is to avoid an unnecessary DB lookup.

Activity icon

Replied to Should API Validation Generate 404 Responses For Missing Items?

Quite right, thanks. I was doing some other requests in a different area of the API and had blithely implemented this one along with them, when it should have been implemented under the Product hierarchy with a bound route identifier.

That leads me to the same problem but from the other direction. Laravel now does a database lookup of the serial number as part of route model binding, and it attempts to do that even if the serial number format is wrong. How can I get into that point to validate the format prior to the lookup? In this case a 404 will do, but a 422 or 420 would be more accurate.

Activity icon

Started a new Conversation Should API Validation Generate 404 Responses For Missing Items?

I have a validation rule like this to validate a serial number:

'serial'                => ['required', new Serial(), 'exists:products,serial'],

This checks that it's present, that the format of the serial number is correct, and that it actually exists in the products table. That's all fine, but I was wondering if it would be appropriate to return a 404 rather than a 422 code for the last rule. If so, how would I tell the validation to return that code? Obviously I can live with a 422, but a 404 would seem more accurate, though it opens the opportunity for that to be interpreted as the endpoint being AWOL rather than the item itself. Is there an OpenAPI or similar policy on this?

Mar
27
2 weeks ago
Activity icon

Awarded Best Reply on Invokable Controllers, Api Resources, And Policies

Yes, that's what I was trying. It was very odd - I could get it to trigger some policy calls but not others.

I've now solved it by moving all the invokables into a single resource controller, and now the policy works fine.

Activity icon

Replied to Invokable Controllers, Api Resources, And Policies

Yes, that's what I was trying. It was very odd - I could get it to trigger some policy calls but not others.

I've now solved it by moving all the invokables into a single resource controller, and now the policy works fine.

Activity icon

Replied to Invokable Controllers, Api Resources, And Policies

As i said, this is a set of single action controllers that acts like a single resource controller, and I'm trying to understand why it was built this way. I think the answer here will be to move it into a regular resource controller, however, it might be easier to call the methods in the policy manually, though I'm not sure what the right way to do that might be since the authorize call I'm using (as above) doesn't seem to provide that.

Activity icon

Replied to Invokable Controllers, Api Resources, And Policies

I didn't register it because I'm relying on autodiscovery.

The policy contains the usual resource methods: viewAny, view, create, update, delete, restore, and forceDelete, plus a couple of extra ones.

Is there a way to get a before policy method to trigger across multiple invokable controllers (e.g. for admin access to all)?

This wasn't my design – Given that this is a bunch of methods relating to a single resource type, I suspect it might be better to migrate it to a single controller.

Activity icon

Started a new Conversation Invokable Controllers, Api Resources, And Policies

I have a set of invokable single action controllers for an API resource. I also have a policy for the underlying model. The controllers have a base class that tells it to authorize requests in its constructor:

$this->authorizeResource(Product::class, 'product');

The problem seems to be that these policy methods are never triggered. Do invokable controllers and policies not get on? Does the lack of an action name (because it's always __invoke) mean that the action to policy name mapping (e.g. index -> viewAny) doesn't work?

To be clear, I'm also calling:

$this->authorize('viewAny', Product::class);

from within the __invoke method of the index controller, but I'm wondering if that fails to make the connection to the policy for the product model, since that method is never called.

Mar
24
2 weeks ago
Activity icon

Awarded Best Reply on Using ASCII Fields In UTF-8 Queries

It turns out that this is a bug introduced in MySQL 8.0.22 that is fixed in MySQL 8.0.23.

Activity icon

Replied to Using ASCII Fields In UTF-8 Queries

It turns out that this is a bug introduced in MySQL 8.0.22 that is fixed in MySQL 8.0.23.

Mar
23
2 weeks ago
Activity icon

Replied to Using ASCII Fields In UTF-8 Queries

I've found an oddity that might be a Laravel bug. This fails with the error I originally described:

Thing::firstOrCreate(
            [
                'id' => 1,
                'uuid'       => '1abb9e11-4f00-4904-988e-233a3c0ce411',
            ],
            [
                'type'       => 'thing 1',
                'name'       => 'Café',
            ]
        );

but this works fine!

Thing::firstOrCreate(
            [
                'id' => 1,
            ],
            [
                'uuid'       => '1abb9e11-4f00-4904-988e-233a3c0ce411',
                'type'       => 'thing 1',
                'name'       => 'Café',
            ]
        );

Either way, the same literal UTF-8 UUID value is going to be used in an ASCII context. I gather that Laravel generates two queries for firstOrCreate: one to check if it exists, and a second to do an insert if it doesn't. It's the first query that's failing.

Activity icon

Replied to Using ASCII Fields In UTF-8 Queries

Now I've hit a second issue that breaks my workaround... Because the field is declared as a UUID, Eloquent validates it as one, but the validation fails because the BINARY prefix makes the UUID longer than it should be:

$bytes string should contain 16 characters.

  at vendor/ramsey/uuid/src/Codec/StringCodec.php:94
Activity icon

Started a new Conversation Using ASCII Fields In UTF-8 Queries

i have a UUID-like field that's set to use an ASCII charset to avoid all the unnecessary overhead of UTF-8. It's in a table and database that is otherwise UTF-8. This has been working for ages, because ASCII is UTF-8 compatible. Just lately it's developed a glitch:

Thing::firstOrCreate(
            [
                'id' => 1,
                'uuid'       => '1abb9e11-4f00-4904-988e-233a3c0ce411',
            ],
            [
                'type'       => 'thing 1',
                'name'       => 'Café',
            ]
        );

This throws an error:

SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (ascii_bin,IMPLICIT) and (utf8mb4_unicode_ci,COERCIBLE) for operation '=' (SQL: select * from `things` where (`id` = 1 and `uuid` = 1abb9e11-4f00-4904-988e-233a3c0ce411) limit 1)

I can work around this like so:

Thing::firstOrCreate(
            [
                'id' => 1,
                'uuid'       => DB::raw('BINARY \'1abb9e11-4f00-4904-988e-233a3c0ce411\''),
            ],
            [
                'type'       => 'thing 1',
                'name'       => 'Café',
            ]
        );

However, that seems unnecessary, and indeed it's been working fine without that for months. There is no 7-bit ASCII string that is not also valid UTF-8, so I don't understand why it has suddenly decided to not be coercible.

This is the table definition:

CREATE TABLE `things` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `uuid` char(36) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `things_uuid_unique` (`uuid`)
) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

This is in Laravel 8.34 on PHP 8 with MySQL 8.

Any ideas?

Mar
03
1 month ago
Activity icon

Replied to Artisan Command For Testing Route Matching?

Dang. Rejected. I added domain searching too. Oh well, the code's there if anyone feels like packaging it.

Activity icon

Replied to Artisan Command For Testing Route Matching?

Done! I made a PR to add this functionality to route:list.

Activity icon

Replied to Artisan Command For Testing Route Matching?

I discovered a similar feature that's built in to artisan route:list:

php artisan route:list --path=thing

This will show all the route patterns that it matches via a simple "contains" match, which is a good start, though it's not quite the same as actually evaluating the routing rules. I'm currently looking to see if I can extend the route:list command to do this.

Mar
01
1 month ago
Activity icon

Replied to Artisan Command For Testing Route Matching?

That's great, thanks. I tweaked it to show the matching route:

$router = Route::getRoutes();
$request = Request::create($url);
try {
    $route = $router->match($request);
    dump($route->uri);
}
catch (\Exception $e) {
    dump('Route does not exist.');
}

That would be really useful to have in an artisan command. In my case this showed me that I had a route ordering problem and it was matching a different route than the one I expected.

Activity icon

Started a new Conversation Artisan Command For Testing Route Matching?

Is there an artisan command for testing route matching? I'm thinking something along the lines of:

php artisan route:check '/thing/param1/param2'

and have it show you the routes it matches, like a subset of the output from route:list

Feb
26
1 month ago
Activity icon

Replied to Naming Policy Methods For Single Action Controllers

OK, that makes sense, thanks.

Activity icon

Started a new Conversation Naming Policy Methods For Single Action Controllers

Laravel's policy methods match up with controller methods by name. How does this work with single-action invokable controllers that don't have a unique method name (it's always __invoke)? I'd guess that there might be some built-in mapping for common names – view, viewAny, create, etc – but what do you call a policy method to match a custom invokable controller that doesn't have a name in the way a method does? Do you have to do authorization inside the controller?

Feb
25
1 month ago
Activity icon

Replied to How To Get More Informative Errors From PHPUnit?

Unfortunately that doesn't help much. It shows a stack trace to the "where" at a slightly earlier point where the internal validation fails rather than when the external response status check fails in the test, and still doesn't show any more info about the "why" or other context, so it's really just a different phrasing of the same error:

Illuminate\Validation\ValidationException : The given data was invalid.
vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:130
...
vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:333
tests/Unit/ProductTest.php:54

I'm currently adding this to reveal the relevant info, but I don't really want to have to do this everywhere:

Log::debug(var_export($response->content(), true));
Activity icon

Started a new Conversation How To Get More Informative Errors From PHPUnit?

Say I have a test that fails like this:

Expected status code 201 but received 422.
Failed asserting that 201 is identical to 422.
vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php:186
tests/Unit/ProductTest.php:57

That tells me where it failed, but not why. In this example it's a validation failure, which could be caused by any of my rules, but I can't tell which from the information provided, yet I know that the response contains that info. PHPUnit aggressively suppresses output even during test failures (even killing dd output), so it's unnecessarily difficult to get more feedback on why something failed. As a workaround I'm forced to add manual logging calls to my actual code to dump response data so that I can see the actual error responses, which negates a lot of the point of having automated tests.

How can I get PHPUnit (or some aspect of my test setup) to produce more verbose output on failure?

Feb
24
1 month ago
Activity icon

Replied to Exempting A Single API Route From Auth

Perfect, thanks. Allowing $user to be null in the policy fixed it, and I understand why that works!

Activity icon

Started a new Conversation Exempting A Single API Route From Auth

I want to exempt a show method in a controller from both authentication and authorization checks.

I have an API resource which uses Laravel's default auth:api middleware, set in its controller's constructor:

    $this->middleware('auth:api')->except('show');
    $this->authorizeResource(Thing::class);

and the policy for this controller returns true for the show method.

But I'm still getting a 403. Where else should I be looking to permit unauth access to this?

Feb
16
1 month ago
Activity icon

Replied to HasOne Drops Linking Field

I am trying to use Eloquent relations as intended! I had no idea that this automatic merging would occur - I was expecting it to work like other eloquent relations, so it was a surprise to have the hasOne merge everything. All there is here is a vanilla hasOne and a corresponding belongsTo and it it all seems to happen automatically.

What do you see me doing that's not "as intended"?

Activity icon

Started a new Conversation HasOne Drops Linking Field

I have a simple hasOne/belongsTo relation.

Location
id
name
Store
location_id
otherfield

When I retrieve a Location model (as a Resource that renders it into JSON), it automatically gains the otherfield field as if it was its own property, which is Eloquent's "magic" at work:

Location
id
name
otherfield

That's nice, but the location_id field that links them disappears or becomes inaccessible, especially if I attempt to retrieve Store instances by themselves:

The location_id is declared in Store's fillable array, it's in the database too, and used in the Store's Resource like this:

    public function toArray($request): array
    {
        $rel = [];
        if ($this->location_id !== null) {
            $rel['location'] = [
                'data' => [
                    'type' => 'locations',
                    'id'   => $this->location->uuid,
                ],
            ];
        }

But accessing the property like that leads to this error:

[2021-02-16 16:35:40] testing.ERROR: Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$location_id {"userId":18,"exception":"[object] (ErrorException(code: 0): Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$location_id at /Users/marcus/myapp/vendor/laravel/framework/src/Illuminate/Http/Resources/DelegatesToResource.php:136)

Why would that happen?

Jan
20
2 months ago
Activity icon

Replied to Model Lifecycle And Transactions For Sequences

That's excellent, very helpful, thank you.

Activity icon

Replied to Model Lifecycle And Transactions For Sequences

I found this article which describes using a service provider to mediate access to a resource type via a repository pattern. This looks like the right direction, but I'm concerned that after adding so much complexity, I may just be moving the problem so that I end up with the same issues inside the service provider. Feeling quite lost.

Jan
19
2 months ago
Activity icon

Replied to Model Lifecycle And Transactions For Sequences

That's the impression I'd got, but I have no idea at all how to do that! Do you have any examples of wrapping a model in a service provider that you could point me at?

Activity icon

Started a new Conversation Model Lifecycle And Transactions For Sequences

This discussion covers using an observer to create dynamic values during instance creation. I have a similar situation with an important difference. I have various different types of things stored in one table with a type field, a standard "morph" pattern. For each value of the type property, i want to have a serial number mechanism, just like MySQL autoincrements, but per-type. So I might have a type1 instance with a serial number of 1, and a type2 instance with the same serial number. I maintain a sequences table that records the current sequence number for each type, and only ever interact with that in an atomic way using transactions to emulate sequences, because they are not native in MySQL. This works fine in things like controllers, but I want it to be applied universally whenever a new instance is created via events. However, what I'm concerned about is that the start/commit/rollback phases of such a transaction may not be called in the correct order, or may interfere with an external containing transaction.

Anyone have any bright ideas about how to use transactions within the model lifecycle?

Jan
12
2 months ago
Activity icon

Replied to Seeders, Migrations, And Schemas

Thanks for the suggestions. I think we're going to end up using both of these measures and another one: having a different set of seeders for production and test. All still a bit messy though!

Activity icon

Started a new Conversation Seeders, Migrations, And Schemas

I've seen lots of discussion about how to deal with fixed data needed by apps, and whether to create it in seeders or migrations, or to call seeders from migrations, etc. The general separation also applies to testing, where the consensus seems to be run migrations but not seeders in production, and run both in testing.

Then schema:dump enters the fray.

This creates a new problem. The schema dump does not include any inserts done by migrations, it's literally only the schema, and not the same as the aggregate of running all the migrations. So this means that you can't call seeders from migrations either, because migrations predating the schema dump will not be run. So now you need to have seeders run in production to populate fixed data. This puts additional constraints on seeders, as for tests these often create large amounts of random stuff for testing purposes that we don't have to worry about cleaning up because they're tests and we know it will all be trashed anyway. But now we need to run seeders in production, which if you are coming from a "lots of test data" starting point is very dangerous. Seeders must be made environment aware, or be idempotent, which is sometimes tricky.

Now I'm looking at creating two sets of seeders: one set for prod only, and another set for test and prod.

in short, this is all a bit of a mess. How have others solved this?

Nov
13
4 months ago
Activity icon

Started a new Conversation Adding Livewire Components Dynamically

I'm building an infinite scroll page similar to google images/pinterest, and it renders a grid of items, where the collection of items is a single livewire component. I've been looking at examples like this. That works ok, and I can trigger a load of new items when I scroll to the bottom of the page, however it's got a large architectural flaw - every time it triggers the new load, it reloads the entire collection, plus the next chunk. So on the first load it loads 30 items, then 60, then 90, then 120, etc. That's OK for a tech demo, but it's clearly an efficiency disaster!

What I'd like to do instead is to make each individual item a component within the grid (which I guess doesn't need to be an LW component itself), and inject only the new items and add them to the container dynamically. I've heard it said that LW won't do that – can someone confirm if that's true, and if so what other way I might do this instead?