issue
dict | pr
dict | pr_details
dict |
---|---|---|
{
"body": "### Laravel Version\r\n\r\n10.45.1\r\n\r\n### PHP Version\r\n\r\n8.1.27\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nThe `getPrefix()` method of the `Illuminate\\Routing\\Route` returns different values for non-cached and cached routes:\r\n- `/{locale}` - the return value of the getPrefix() method for a non-cached route\r\n- `{locale}` - the return value of the getPrefix() method for a cached route\r\n\r\nThis discrepancy in the results for non-cached/cached routes seems a sort of bug to me.\r\n\r\nThis issue might be related with #43882 and #43997.\r\n\r\n### Steps To Reproduce\r\n\r\nAfter installing a new Laravel project, just add a route group to the `web` routes (the `/routes/web.php` file). For example:\r\n```php\r\nRoute::group([\r\n 'prefix' => '{locale}',\r\n 'where' => ['locale' => 'en|fr|de'],\r\n], function () {\r\n Route::get('/', function () {\r\n return view('welcome');\r\n });\r\n});\r\n```\r\n\r\nThen, use the `tinker` tool to get the registered routes and check the `getPrefix()` return values.\r\nLet's check the non-cacned routes:\r\n```php\r\n$routes = app('router')->getRoutes()->get('GET');\r\n\r\nforeach ($routes as $route) {\r\n dump($route->getPrefix());\r\n}\r\n```\r\n\r\nThe result is going to be:\r\n\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use `tinker` again.\r\n```php\r\n$routes = app('router')->getRoutes()->get('GET');\r\n\r\nforeach ($routes as $route) {\r\n dump($route->getPrefix());\r\n}\r\n```\r\n\r\nThe result is going to be:\r\n\r\n\r\n",
"comments": [
{
"body": "@kudashevs does the solution for https://github.com/laravel/framework/pull/43932 work if you apply the patch locally? We could maybe try to revive it with proper tests.",
"created_at": "2024-02-26T09:32:35Z"
},
{
"body": "Actually, we also tried this at https://github.com/laravel/framework/pull/44011 but that trims both sides and broke things for some people. So not sure if this one is solvable at all. Although I agree the behaviour should be the same in both cached and none-cached routes. \r\n\r\nFrom a first glance I think the cached route value is the correct one (without the prefixed `/`) because that's the actual value of \"prefix\". ",
"created_at": "2024-02-26T09:36:22Z"
},
{
"body": "> @kudashevs does the solution for #43932 work if you apply the patch locally? We could maybe try to revive it with proper tests.\r\n\r\n@driesvints the patch adds a forward slash to both (cached and non-cached) routes",
"created_at": "2024-02-26T14:45:09Z"
},
{
"body": "> From a first glance I think the cached route value is the correct one (without the prefixed `/`) because that's the actual value of \"prefix\".\r\n\r\nFrom the first glance I agree. But, it’s not so obvious.\r\n\r\nIn the [documentation](https://laravel.com/docs/10.x/routing) all the route examples with paths have a forward slash. On the other hand, the slash is optional because it is going to be removed during the parsing process. In the community people use both notations (with forward slash and without). \r\n\r\nThe [only prefix example](https://laravel.com/docs/10.x/routing#route-group-prefixes) goes without a forward slash. However, due to the logic of the aforementioned route examples it should be expanded to something with a forward slash (which is going to be removed during the parsing process). But the `{locale}` is not a path. So, it shouldn’t start with a slash to me. This is really complicated :)\r\n\r\nSo, I think, to move forward we need someone who is in charge of making a final decision on this. I mean, the final decision on the expected behavior (should a route go with a forward slash or without a slash; in which cases a slash should be added). And, I would expect the behavior to be the same for cached and non-cached routes.\r\n\r\n**P.S.** the things are even more complicated because the `getPrefix()` method has another discrepancy in the behavior for cached and non-cached prefixless routes. If you want, I can brought up this topic too.\r\n",
"created_at": "2024-02-26T15:27:01Z"
},
{
"body": "> P.S. the things are even more complicated because the getPrefix() method has another discrepancy in the behavior for cached and non-cached prefixless routes. If you want, I can brought up this topic too.\r\n\r\nWhat's that?",
"created_at": "2024-02-27T14:37:31Z"
},
{
"body": "> What's that?\r\n\r\nWhen you create a route without a prefix, the `getPrefix()` method returns an empty string for a non-cached route and null for the cached route.\r\n\r\n\r\n### Steps To Reproduce\r\n\r\nAfter installing a new Laravel project, just add a route group to the `web` routes (the `/routes/web.php` file). For example:\r\n```\r\nRoute::get('/test', function () {\r\n return view('welcome');\r\n});\r\n```\r\n\r\nThen, use the `tinker` tool to get the registered routes and check the `getPrefix()` return values.\r\nLet's check the non-cacned routes:\r\n\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use tinker again.\r\n\r\n\r\nThis discrepancy is not a big deal to me. However, if there is a plan to fix the discrepancy with prefixes, it might make sense to fix this one too.",
"created_at": "2024-02-27T18:39:19Z"
},
{
"body": "Just in case, for those, who use the `getPrefix()` method in their code (I use it in a custom middleware). If you want to rely on the `getPrefix()` return value to make further decisions (I use a comparison for this), you can use these two simple workarounds:\r\n\r\n- use `routesAreCached()` to check whether routes are cached before the comparison:\r\n```php\r\n(app()->routesAreCached())\r\n ? $route->getPrefix() === '{locale}'\r\n : $route->getPrefix() === '/{locale}';\r\n```\r\n\r\n- trim the return value before the comparison:\r\n```php\r\nltrim($route->getPrefix(), '/') === '{locale}';\r\n```\r\n\r\nI would prefer the second one. However, you might want to keep the reason of using the different comparisons.",
"created_at": "2024-03-01T08:57:57Z"
},
{
"body": "It's been almost three months without any progress.\r\n@driesvints I wonder if I should provide any additional information?",
"created_at": "2024-04-16T11:03:05Z"
},
{
"body": "No. I'm sorry but I just haven't gotten to this yet. Honestly I do not know what the correct path forward is. I think cached routes should mimic what uncached routes do personally. But I don't have the time to work on a solution. If you could work on a PR and send it in then we can go from there. Thanks",
"created_at": "2024-04-16T11:17:26Z"
},
{
"body": "I also don't know how to approach this issue. What makes the issue even worse is that it seems that this is the default behavior for all the versions (at least I checked 9, 10, 11).\r\n\r\n> > \r\n> So, I think, to move forward we need someone who is in charge of making a final decision on this. I mean, the final decision on the expected behavior (should a route go with a forward slash or without a slash; in which cases a slash should be added). And, I would expect the behavior to be the same for cached and non-cached routes.\r\n\r\nAs mentioned earlier, without having the requirements (or at least an explanatory post with a thorough explanation on how the cached and non-cahced routes should behave) approved by Taylor (or someone else who is in charge of making the final decision on the system's behavior) it is going to be a sort of shot in the dark.\r\n",
"created_at": "2024-04-16T11:46:18Z"
},
{
"body": "I also think cached routes should exactly mimic the behavior of uncached routes. In other words, if cached routes are currently different than uncached, they should be updated to match the uncached behavior.",
"created_at": "2024-04-16T19:23:17Z"
},
{
"body": "Hello there,\r\n\r\nI played around with the issue today, and I didn't find any way to write tests for this issue. What do I mean.\r\n\r\nTo check whether the cached routes behave in the correct way, they should be cached. The usual way to cache them is to use the artisan command. So, I used the [testRouteGrouping](https://github.com/laravel/framework/blob/877ebcab5fb0d97b8e8eb7c213dd549647e071ad/tests/Routing/RoutingRouteTest.php#L1134) method as a basis, but it turned out that you cannot just call an artisan command without a bootstrapped app (that makes sense). So, I thought to go in a different direction and use `Orchestra\\Testbench\\TestCase` which provides a bootstrapped app. And it kind of worked with the artisan command, but it doesn't store any cached routes (because the cache path is emulated).\r\n\r\nI thought, that mocking a cache path might be an option here. I mocked the `getCachedRoutesPath` to provide the existing path and it turned out that the artisan command reads a list of routes from a route file. But, the route file doesn't exist in the bare framework. So, this pattern for providing routes, which is used in the current test code base, \r\n```php\r\n $router = $this->getRouter();\r\n $router->group(['prefix' => 'foo'], function () use ($router) {\r\n $router->get('bar', function () {\r\n return 'hello';\r\n });\r\n });\r\n $routes = $router->getRoutes();\r\n $routes = $routes->getRoutes();\r\n```\r\ndoesn't work in this case. The command just doesn't get any routes.\r\n\r\nHave I missed something? Do you have any ideas or suggestions on how the tests could be implemented? Or, do you have any code examples of the tests that work with cached routes (I didn't find any)? Is there a way to cache the routes without the artisan command and without duplicating its functionality? Any idea or advice might be helpful in this case.",
"created_at": "2024-04-18T18:37:03Z"
},
{
"body": "@crynobone would you maybe know how we can test cached routes in framework using test bench?",
"created_at": "2024-04-19T05:25:00Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-04-19T09:08:32Z"
}
],
"number": 50239,
"title": "Different getPrefix() behavior for cached and non-cached routes"
} | {
"body": "I solved bug : #50239",
"number": 51542,
"review_comments": [],
"title": "[11.x] Fix getPrefix behaviour for cached routes"
} | {
"commits": [
{
"message": "debug : issue 50239"
},
{
"message": "bug:50239"
},
{
"message": "bug:50239"
}
],
"files": [
{
"diff": "@@ -61,16 +61,23 @@ protected static function formatNamespace($new, $old)\n * @param bool $prependExistingPrefix\n * @return string|null\n */\n- protected static function formatPrefix($new, $old, $prependExistingPrefix = true)\n- {\n- $old = $old['prefix'] ?? '';\n-\n- if ($prependExistingPrefix) {\n- return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n- }\n+ protected static function formatPrefix($new, $old, $prependExistingPrefix = true)\n+ {\n+ $old = $old['prefix'] ?? '';\n+ \n+ if ($prependExistingPrefix) {\n+ \n+ if(mb_substr($new['prefix'] , 0 , 1) == '/')\n+ {\n+ \n+ return isset($new['prefix']) ? trim($old, '/').$new['prefix'] : $old;\n+ } \n \n- return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;\n- }\n+ return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n+ }\n+ \n+ return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;\n+ }\n \n /**\n * Format the \"wheres\" for the new group attributes.",
"filename": "src/Illuminate/Routing/RouteGroup.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.45.1\r\n\r\n### PHP Version\r\n\r\n8.1.27\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nThe `getPrefix()` method of the `Illuminate\\Routing\\Route` returns different values for non-cached and cached routes:\r\n- `/{locale}` - the return value of the getPrefix() method for a non-cached route\r\n- `{locale}` - the return value of the getPrefix() method for a cached route\r\n\r\nThis discrepancy in the results for non-cached/cached routes seems a sort of bug to me.\r\n\r\nThis issue might be related with #43882 and #43997.\r\n\r\n### Steps To Reproduce\r\n\r\nAfter installing a new Laravel project, just add a route group to the `web` routes (the `/routes/web.php` file). For example:\r\n```php\r\nRoute::group([\r\n 'prefix' => '{locale}',\r\n 'where' => ['locale' => 'en|fr|de'],\r\n], function () {\r\n Route::get('/', function () {\r\n return view('welcome');\r\n });\r\n});\r\n```\r\n\r\nThen, use the `tinker` tool to get the registered routes and check the `getPrefix()` return values.\r\nLet's check the non-cacned routes:\r\n```php\r\n$routes = app('router')->getRoutes()->get('GET');\r\n\r\nforeach ($routes as $route) {\r\n dump($route->getPrefix());\r\n}\r\n```\r\n\r\nThe result is going to be:\r\n\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use `tinker` again.\r\n```php\r\n$routes = app('router')->getRoutes()->get('GET');\r\n\r\nforeach ($routes as $route) {\r\n dump($route->getPrefix());\r\n}\r\n```\r\n\r\nThe result is going to be:\r\n\r\n\r\n",
"comments": [
{
"body": "@kudashevs does the solution for https://github.com/laravel/framework/pull/43932 work if you apply the patch locally? We could maybe try to revive it with proper tests.",
"created_at": "2024-02-26T09:32:35Z"
},
{
"body": "Actually, we also tried this at https://github.com/laravel/framework/pull/44011 but that trims both sides and broke things for some people. So not sure if this one is solvable at all. Although I agree the behaviour should be the same in both cached and none-cached routes. \r\n\r\nFrom a first glance I think the cached route value is the correct one (without the prefixed `/`) because that's the actual value of \"prefix\". ",
"created_at": "2024-02-26T09:36:22Z"
},
{
"body": "> @kudashevs does the solution for #43932 work if you apply the patch locally? We could maybe try to revive it with proper tests.\r\n\r\n@driesvints the patch adds a forward slash to both (cached and non-cached) routes",
"created_at": "2024-02-26T14:45:09Z"
},
{
"body": "> From a first glance I think the cached route value is the correct one (without the prefixed `/`) because that's the actual value of \"prefix\".\r\n\r\nFrom the first glance I agree. But, it’s not so obvious.\r\n\r\nIn the [documentation](https://laravel.com/docs/10.x/routing) all the route examples with paths have a forward slash. On the other hand, the slash is optional because it is going to be removed during the parsing process. In the community people use both notations (with forward slash and without). \r\n\r\nThe [only prefix example](https://laravel.com/docs/10.x/routing#route-group-prefixes) goes without a forward slash. However, due to the logic of the aforementioned route examples it should be expanded to something with a forward slash (which is going to be removed during the parsing process). But the `{locale}` is not a path. So, it shouldn’t start with a slash to me. This is really complicated :)\r\n\r\nSo, I think, to move forward we need someone who is in charge of making a final decision on this. I mean, the final decision on the expected behavior (should a route go with a forward slash or without a slash; in which cases a slash should be added). And, I would expect the behavior to be the same for cached and non-cached routes.\r\n\r\n**P.S.** the things are even more complicated because the `getPrefix()` method has another discrepancy in the behavior for cached and non-cached prefixless routes. If you want, I can brought up this topic too.\r\n",
"created_at": "2024-02-26T15:27:01Z"
},
{
"body": "> P.S. the things are even more complicated because the getPrefix() method has another discrepancy in the behavior for cached and non-cached prefixless routes. If you want, I can brought up this topic too.\r\n\r\nWhat's that?",
"created_at": "2024-02-27T14:37:31Z"
},
{
"body": "> What's that?\r\n\r\nWhen you create a route without a prefix, the `getPrefix()` method returns an empty string for a non-cached route and null for the cached route.\r\n\r\n\r\n### Steps To Reproduce\r\n\r\nAfter installing a new Laravel project, just add a route group to the `web` routes (the `/routes/web.php` file). For example:\r\n```\r\nRoute::get('/test', function () {\r\n return view('welcome');\r\n});\r\n```\r\n\r\nThen, use the `tinker` tool to get the registered routes and check the `getPrefix()` return values.\r\nLet's check the non-cacned routes:\r\n\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use tinker again.\r\n\r\n\r\nThis discrepancy is not a big deal to me. However, if there is a plan to fix the discrepancy with prefixes, it might make sense to fix this one too.",
"created_at": "2024-02-27T18:39:19Z"
},
{
"body": "Just in case, for those, who use the `getPrefix()` method in their code (I use it in a custom middleware). If you want to rely on the `getPrefix()` return value to make further decisions (I use a comparison for this), you can use these two simple workarounds:\r\n\r\n- use `routesAreCached()` to check whether routes are cached before the comparison:\r\n```php\r\n(app()->routesAreCached())\r\n ? $route->getPrefix() === '{locale}'\r\n : $route->getPrefix() === '/{locale}';\r\n```\r\n\r\n- trim the return value before the comparison:\r\n```php\r\nltrim($route->getPrefix(), '/') === '{locale}';\r\n```\r\n\r\nI would prefer the second one. However, you might want to keep the reason of using the different comparisons.",
"created_at": "2024-03-01T08:57:57Z"
},
{
"body": "It's been almost three months without any progress.\r\n@driesvints I wonder if I should provide any additional information?",
"created_at": "2024-04-16T11:03:05Z"
},
{
"body": "No. I'm sorry but I just haven't gotten to this yet. Honestly I do not know what the correct path forward is. I think cached routes should mimic what uncached routes do personally. But I don't have the time to work on a solution. If you could work on a PR and send it in then we can go from there. Thanks",
"created_at": "2024-04-16T11:17:26Z"
},
{
"body": "I also don't know how to approach this issue. What makes the issue even worse is that it seems that this is the default behavior for all the versions (at least I checked 9, 10, 11).\r\n\r\n> > \r\n> So, I think, to move forward we need someone who is in charge of making a final decision on this. I mean, the final decision on the expected behavior (should a route go with a forward slash or without a slash; in which cases a slash should be added). And, I would expect the behavior to be the same for cached and non-cached routes.\r\n\r\nAs mentioned earlier, without having the requirements (or at least an explanatory post with a thorough explanation on how the cached and non-cahced routes should behave) approved by Taylor (or someone else who is in charge of making the final decision on the system's behavior) it is going to be a sort of shot in the dark.\r\n",
"created_at": "2024-04-16T11:46:18Z"
},
{
"body": "I also think cached routes should exactly mimic the behavior of uncached routes. In other words, if cached routes are currently different than uncached, they should be updated to match the uncached behavior.",
"created_at": "2024-04-16T19:23:17Z"
},
{
"body": "Hello there,\r\n\r\nI played around with the issue today, and I didn't find any way to write tests for this issue. What do I mean.\r\n\r\nTo check whether the cached routes behave in the correct way, they should be cached. The usual way to cache them is to use the artisan command. So, I used the [testRouteGrouping](https://github.com/laravel/framework/blob/877ebcab5fb0d97b8e8eb7c213dd549647e071ad/tests/Routing/RoutingRouteTest.php#L1134) method as a basis, but it turned out that you cannot just call an artisan command without a bootstrapped app (that makes sense). So, I thought to go in a different direction and use `Orchestra\\Testbench\\TestCase` which provides a bootstrapped app. And it kind of worked with the artisan command, but it doesn't store any cached routes (because the cache path is emulated).\r\n\r\nI thought, that mocking a cache path might be an option here. I mocked the `getCachedRoutesPath` to provide the existing path and it turned out that the artisan command reads a list of routes from a route file. But, the route file doesn't exist in the bare framework. So, this pattern for providing routes, which is used in the current test code base, \r\n```php\r\n $router = $this->getRouter();\r\n $router->group(['prefix' => 'foo'], function () use ($router) {\r\n $router->get('bar', function () {\r\n return 'hello';\r\n });\r\n });\r\n $routes = $router->getRoutes();\r\n $routes = $routes->getRoutes();\r\n```\r\ndoesn't work in this case. The command just doesn't get any routes.\r\n\r\nHave I missed something? Do you have any ideas or suggestions on how the tests could be implemented? Or, do you have any code examples of the tests that work with cached routes (I didn't find any)? Is there a way to cache the routes without the artisan command and without duplicating its functionality? Any idea or advice might be helpful in this case.",
"created_at": "2024-04-18T18:37:03Z"
},
{
"body": "@crynobone would you maybe know how we can test cached routes in framework using test bench?",
"created_at": "2024-04-19T05:25:00Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-04-19T09:08:32Z"
}
],
"number": 50239,
"title": "Different getPrefix() behavior for cached and non-cached routes"
} | {
"body": "#50239\r\n\r\nI solved issue . now when cache route and non-cache the prefix is same.",
"number": 51529,
"review_comments": [],
"title": "debug : issue 50239"
} | {
"commits": [
{
"message": "debug : issue 50239"
}
],
"files": [
{
"diff": "@@ -66,7 +66,7 @@ protected static function formatPrefix($new, $old, $prependExistingPrefix = true\n $old = $old['prefix'] ?? '';\n \n if ($prependExistingPrefix) {\n- return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n+ return isset($new['prefix']) ? trim($old, '/').$new['prefix'] : $old;\n }\n \n return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;",
"filename": "src/Illuminate/Routing/RouteGroup.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n11.7.0\n\n### PHP Version\n\n8.3.3\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nWe're using a custom route binding for a backed enum in our Laravel application.\r\n\r\nTo avoid having to create a new backed enum (string) for plural words, we've been using a custom route binding to resolve the enum from plural words.\r\n\r\nFor single words, it works fine. But for plural words, it doesn't work anymore, giving the following error:\r\n\r\n```\r\nObject of class App\\Enums\\YourEnumHere could not be converted to string\r\n```\r\n\r\n#### ⚠️ See the \"Steps To Reproduce\" section below for more details.\r\n\r\n### Possible Solution\r\nDo not implicitly resolve backed enums when there is a custom route binding.\r\n\n\n### Steps To Reproduce\n\n1. Create a backed enum\r\n```php\r\n<?php\r\n\r\nnamespace App\\Enums;\r\n\r\nenum Fruit:string\r\n{\r\n case APPLE = 'apple';\r\n case BANANA = 'banana';\r\n case PEAR = 'pear';\r\n\r\n public static function fromPlural(string $plural): self\r\n {\r\n return match ($plural) {\r\n 'apples' => self::APPLE,\r\n 'bananas' => self::BANANA,\r\n 'pears' => self::PEAR,\r\n };\r\n }\r\n}\r\n```\r\n\r\n2. Add custom route binding to the AppServiceProvider.php\r\n```php\r\nRoute::bind('fruits', fn(string $x) => Fruit::fromPlural($x));\r\n```\r\n\r\n3. Add a route to the web.php file\r\n```php\r\nRoute::get('shop/get/{fruit}/{id}', function (App\\Enums\\Fruit $fruit, string $id) {\r\n dd($fruit, $id); // IT WORKS!!!\r\n});\r\n\r\nRoute::get('shop/list/{fruits}', function (App\\Enums\\Fruit $fruits) {\r\n dd($fruits); // ERROR: Object of class App\\Enums\\Fruit could not be converted to string\r\n});\r\n```",
"comments": [],
"number": 51514,
"title": "Custom route binding for backed enums doesn't work"
} | {
"body": "fixes #51514\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 51525,
"review_comments": [],
"title": "Fixes explicit route binding with `BackedEnum`"
} | {
"commits": [
{
"message": "Fixes explicit route binding with `BackedEnum`\n\nfixes #51514\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
}
],
"files": [
{
"diff": "@@ -90,7 +90,9 @@ protected static function resolveBackedEnumsForRoute($route, $parameters)\n \n $backedEnumClass = $parameter->getType()?->getName();\n \n- $backedEnum = $backedEnumClass::tryFrom((string) $parameterValue);\n+ $backedEnum = $parameterValue instanceof $backedEnumClass\n+ ? $parameterValue\n+ : $backedEnumClass::tryFrom((string) $parameterValue);\n \n if (is_null($backedEnum)) {\n throw new BackedEnumCaseNotFoundException($backedEnumClass, $parameterValue);",
"filename": "src/Illuminate/Routing/ImplicitRouteBinding.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,18 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Routing;\n+\n+enum CategoryBackedEnum: string\n+{\n+ case People = 'people';\n+ case Fruits = 'fruits';\n+\n+ public static function fromCode(string $code)\n+ {\n+ return match ($code) {\n+ 'c01' => self::People,\n+ 'c02' => self::Fruits,\n+ default => null,\n+ };\n+ }\n+}",
"filename": "tests/Integration/Routing/CategoryBackedEnum.php",
"status": "added"
},
{
"diff": "@@ -5,8 +5,6 @@\n use Illuminate\\Support\\Facades\\Route;\n use Orchestra\\Testbench\\TestCase;\n \n-include_once 'Enums.php';\n-\n class ImplicitBackedEnumRouteBindingTest extends TestCase\n {\n protected function defineEnvironment($app): void\n@@ -61,14 +59,20 @@ public function testWithoutRouteCachingEnabled()\n return $category->value;\n })->middleware('web');\n \n+ Route::bind('categoryCode', fn (string $categoryCode) => CategoryBackedEnum::fromCode($categoryCode) ?? abort(404));\n+\n+ Route::post('/categories-code/{categoryCode}', function (CategoryBackedEnum $categoryCode) {\n+ return $categoryCode->value;\n+ })->middleware(['web']);\n+\n $response = $this->post('/categories/fruits');\n $response->assertSee('fruits');\n \n $response = $this->post('/categories/people');\n $response->assertSee('people');\n \n $response = $this->post('/categories/cars');\n- $response->assertNotFound(404);\n+ $response->assertNotFound();\n \n $response = $this->post('/categories-default/');\n $response->assertSee('fruits');\n@@ -78,5 +82,14 @@ public function testWithoutRouteCachingEnabled()\n \n $response = $this->post('/categories-default/fruits');\n $response->assertSee('fruits');\n+\n+ $response = $this->post('/categories-code/c01');\n+ $response->assertSee('people');\n+\n+ $response = $this->post('/categories-code/c02');\n+ $response->assertSee('fruits');\n+\n+ $response = $this->post('/categories-code/00');\n+ $response->assertNotFound();\n }\n }",
"filename": "tests/Integration/Routing/ImplicitBackedEnumRouteBindingTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n11.7.0\n\n### PHP Version\n\n8.3.6\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nWhen running any `artisan` command (just `php artisan` does the same), the code inside `console.php` route file and/or `->withSchedule()` bootstrap method gets executed. Usually this wouldn't be a big deal, because the code should only register cron events. However, sometimes dynamic scheduling might involve database queries which can inflict unwanted performance penalty or in worst case scenario fail in CI setup.\r\n\r\nWe noticed this in our CI while upgrading from Laravel 10 to Laravel 11 (with slimmed down app structure). Our scheduler needs to be dynamic and it makes a DB query for that reason. When CI is setting up the application it runs `composer install` which then runs `php artisan package:discover --ansi` as a composer `post-autoload-dump` script. This is standard in every Laravel project. Since `package:discover` is an artisan command it boots up the scheduler as well. At this stage in CI database is not yet available thus we get a `QueryException: SQLSTATE[HY000] [2002] Connection refused`.\r\n\r\nI have checked and this wasn't the case with Laravel 10. I'm not sure if this is now intended or not, but I would expect scheduler code to only execute when calling `php artisan schedule:run` and `php artisan schedule:work`.\n\n### Steps To Reproduce\n\n* Set up new Laravel 11 project.\r\n* Add `dd();` inside `console.php` route file or inside `->withSchedule()` app bootstrap method.\r\n* Run `php artisan` and observe the command to fail.",
"comments": [
{
"body": "Thanks @crynobone for taking your time to look at this. Unfortunately your attempt unveiled another issue. I tried investigating this myself and here are my findings:\r\n\r\n1. Artisan command is invoked.\r\n2. Console [Kernel is bootstrapped](https://github.com/laravel/framework/blob/11.x/src/Illuminate/Foundation/Console/Kernel.php#L194).\r\n3. [Commands are discovered](https://github.com/laravel/framework/blob/11.x/src/Illuminate/Foundation/Console/Kernel.php#L479)\r\n4. `console.php` [route file is required](https://github.com/laravel/framework/blob/11.x/src/Illuminate/Foundation/Console/Kernel.php#L499).\r\n * If the file contains scheduled commands `\\Illuminate\\Console\\Scheduling\\Schedule` is resolved too.\r\n5. [Console application is bootstrapped](https://github.com/laravel/framework/blob/11.x/src/Illuminate/Console/Application.php#L77), [executing bootstrappers](https://github.com/laravel/framework/blob/11.x/src/Illuminate/Console/Application.php#L130) registered with `Artisan::starting()`\r\n\r\n---\r\n\r\nCurrently, `->withSchedule()` looks like this:\r\n```php\r\nArtisan::starting(fn () => $callback($this->app->make(Schedule::class)));\r\n```\r\n\r\nMeaning that the code inside `->withSchedule()` gets executed with every artisan command.\r\n@crynobone suggested to change this to\r\n```php\r\nArtisan::starting(function () use ($callback) {\r\n $this->app->afterResolving(Schedule::class, fn ($schedule) => $callback($schedule));\r\n});\r\n```\r\nWhich unfortunately doesn't work if `console.php` route file contains scheduled commands, because `\\Illuminate\\Console\\Scheduling\\Schedule` gets [resolved immediately the second time](https://github.com/laravel/framework/blob/11.x/src/Illuminate/Container/Container.php#L774), skipping both `$resolvingCallbacks` and `$afterResolvingCallbacks`.\r\n\r\n---\r\n\r\nAt this point, for this to work we would need to either detect scheduled commands inside `console.php` and defer registering them after console application is bootsrapped (step 5), or execute `$afterResolvingCallbacks` even if items, that have already been resolved before, are returned from container directly.\r\nPerhaps I don't see the full picture yet and am missing some other hook that can be used?\r\n\r\nOf course, another option is to treat this \"bug\" as \"working as expected\" and perhaps document it. After all, all code inside `console.php` is already being executed with every artisan call, so maybe code inside `->withSchedule()` should be too.",
"created_at": "2024-05-10T17:01:59Z"
},
{
"body": "Why you did not run 'schedule' inside a Artisan::command() function? like following:\r\n\r\n`` Artisan::command('schedule:run', function () { //write schedulers here. });``\r\n\r\nSo when run `php artisan schedule:run` only code there get executed.",
"created_at": "2024-05-18T22:37:39Z"
},
{
"body": "Well... [`schedule:run`](https://laravel.com/docs/master/scheduling#running-the-scheduler) is already a command. Overriding that would mean re-implementing the whole cron logic myself.\r\n\r\nUnless I'm missing something?",
"created_at": "2024-05-19T14:23:37Z"
},
{
"body": "How about having a dedicated `schedule.php` file? During migration to L11 I found this to be very confusing and I am experiencing my commands not being run besides them appearing in the CLI `list`. It may be a completely another issue but it feels worth a second thought.",
"created_at": "2024-05-23T11:58:13Z"
},
{
"body": "@flexchar You are able to do that using `->withSchedule()` method on app bootstrap and then importing/requiring `schedule.php` file.",
"created_at": "2024-05-23T12:39:38Z"
}
],
"number": 51354,
"title": "Schedule gets registered with every artisan call"
} | {
"body": "fixes #51354\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 51364,
"review_comments": [],
"title": "[11.x] Defer registering schedule registered using `ApplicationBuilder::withScheduling()`"
} | {
"commits": [
{
"message": "[11.x] Defer registering schedule registered using\n`ApplicationBuilder::withScheduling()`\n\nfixes #51354\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
}
],
"files": [
{
"diff": "@@ -294,7 +294,9 @@ protected function withCommandRouting(array $paths)\n */\n public function withSchedule(callable $callback)\n {\n- Artisan::starting(fn () => $callback($this->app->make(Schedule::class)));\n+ Artisan::starting(function () use ($callback) {\n+ $this->app->afterResolving(Schedule::class, fn ($schedule) => $callback($schedule));\n+ });\n \n return $this;\n }",
"filename": "src/Illuminate/Foundation/Configuration/ApplicationBuilder.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.45.1\r\n\r\n### PHP Version\r\n\r\n8.1.27\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nThe `getPrefix()` method of the `Illuminate\\Routing\\Route` returns different values for non-cached and cached routes:\r\n- `/{locale}` - the return value of the getPrefix() method for a non-cached route\r\n- `{locale}` - the return value of the getPrefix() method for a cached route\r\n\r\nThis discrepancy in the results for non-cached/cached routes seems a sort of bug to me.\r\n\r\nThis issue might be related with #43882 and #43997.\r\n\r\n### Steps To Reproduce\r\n\r\nAfter installing a new Laravel project, just add a route group to the `web` routes (the `/routes/web.php` file). For example:\r\n```php\r\nRoute::group([\r\n 'prefix' => '{locale}',\r\n 'where' => ['locale' => 'en|fr|de'],\r\n], function () {\r\n Route::get('/', function () {\r\n return view('welcome');\r\n });\r\n});\r\n```\r\n\r\nThen, use the `tinker` tool to get the registered routes and check the `getPrefix()` return values.\r\nLet's check the non-cacned routes:\r\n```php\r\n$routes = app('router')->getRoutes()->get('GET');\r\n\r\nforeach ($routes as $route) {\r\n dump($route->getPrefix());\r\n}\r\n```\r\n\r\nThe result is going to be:\r\n\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use `tinker` again.\r\n```php\r\n$routes = app('router')->getRoutes()->get('GET');\r\n\r\nforeach ($routes as $route) {\r\n dump($route->getPrefix());\r\n}\r\n```\r\n\r\nThe result is going to be:\r\n\r\n\r\n",
"comments": [
{
"body": "@kudashevs does the solution for https://github.com/laravel/framework/pull/43932 work if you apply the patch locally? We could maybe try to revive it with proper tests.",
"created_at": "2024-02-26T09:32:35Z"
},
{
"body": "Actually, we also tried this at https://github.com/laravel/framework/pull/44011 but that trims both sides and broke things for some people. So not sure if this one is solvable at all. Although I agree the behaviour should be the same in both cached and none-cached routes. \r\n\r\nFrom a first glance I think the cached route value is the correct one (without the prefixed `/`) because that's the actual value of \"prefix\". ",
"created_at": "2024-02-26T09:36:22Z"
},
{
"body": "> @kudashevs does the solution for #43932 work if you apply the patch locally? We could maybe try to revive it with proper tests.\r\n\r\n@driesvints the patch adds a forward slash to both (cached and non-cached) routes",
"created_at": "2024-02-26T14:45:09Z"
},
{
"body": "> From a first glance I think the cached route value is the correct one (without the prefixed `/`) because that's the actual value of \"prefix\".\r\n\r\nFrom the first glance I agree. But, it’s not so obvious.\r\n\r\nIn the [documentation](https://laravel.com/docs/10.x/routing) all the route examples with paths have a forward slash. On the other hand, the slash is optional because it is going to be removed during the parsing process. In the community people use both notations (with forward slash and without). \r\n\r\nThe [only prefix example](https://laravel.com/docs/10.x/routing#route-group-prefixes) goes without a forward slash. However, due to the logic of the aforementioned route examples it should be expanded to something with a forward slash (which is going to be removed during the parsing process). But the `{locale}` is not a path. So, it shouldn’t start with a slash to me. This is really complicated :)\r\n\r\nSo, I think, to move forward we need someone who is in charge of making a final decision on this. I mean, the final decision on the expected behavior (should a route go with a forward slash or without a slash; in which cases a slash should be added). And, I would expect the behavior to be the same for cached and non-cached routes.\r\n\r\n**P.S.** the things are even more complicated because the `getPrefix()` method has another discrepancy in the behavior for cached and non-cached prefixless routes. If you want, I can brought up this topic too.\r\n",
"created_at": "2024-02-26T15:27:01Z"
},
{
"body": "> P.S. the things are even more complicated because the getPrefix() method has another discrepancy in the behavior for cached and non-cached prefixless routes. If you want, I can brought up this topic too.\r\n\r\nWhat's that?",
"created_at": "2024-02-27T14:37:31Z"
},
{
"body": "> What's that?\r\n\r\nWhen you create a route without a prefix, the `getPrefix()` method returns an empty string for a non-cached route and null for the cached route.\r\n\r\n\r\n### Steps To Reproduce\r\n\r\nAfter installing a new Laravel project, just add a route group to the `web` routes (the `/routes/web.php` file). For example:\r\n```\r\nRoute::get('/test', function () {\r\n return view('welcome');\r\n});\r\n```\r\n\r\nThen, use the `tinker` tool to get the registered routes and check the `getPrefix()` return values.\r\nLet's check the non-cacned routes:\r\n\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use tinker again.\r\n\r\n\r\nThis discrepancy is not a big deal to me. However, if there is a plan to fix the discrepancy with prefixes, it might make sense to fix this one too.",
"created_at": "2024-02-27T18:39:19Z"
},
{
"body": "Just in case, for those, who use the `getPrefix()` method in their code (I use it in a custom middleware). If you want to rely on the `getPrefix()` return value to make further decisions (I use a comparison for this), you can use these two simple workarounds:\r\n\r\n- use `routesAreCached()` to check whether routes are cached before the comparison:\r\n```php\r\n(app()->routesAreCached())\r\n ? $route->getPrefix() === '{locale}'\r\n : $route->getPrefix() === '/{locale}';\r\n```\r\n\r\n- trim the return value before the comparison:\r\n```php\r\nltrim($route->getPrefix(), '/') === '{locale}';\r\n```\r\n\r\nI would prefer the second one. However, you might want to keep the reason of using the different comparisons.",
"created_at": "2024-03-01T08:57:57Z"
},
{
"body": "It's been almost three months without any progress.\r\n@driesvints I wonder if I should provide any additional information?",
"created_at": "2024-04-16T11:03:05Z"
},
{
"body": "No. I'm sorry but I just haven't gotten to this yet. Honestly I do not know what the correct path forward is. I think cached routes should mimic what uncached routes do personally. But I don't have the time to work on a solution. If you could work on a PR and send it in then we can go from there. Thanks",
"created_at": "2024-04-16T11:17:26Z"
},
{
"body": "I also don't know how to approach this issue. What makes the issue even worse is that it seems that this is the default behavior for all the versions (at least I checked 9, 10, 11).\r\n\r\n> > \r\n> So, I think, to move forward we need someone who is in charge of making a final decision on this. I mean, the final decision on the expected behavior (should a route go with a forward slash or without a slash; in which cases a slash should be added). And, I would expect the behavior to be the same for cached and non-cached routes.\r\n\r\nAs mentioned earlier, without having the requirements (or at least an explanatory post with a thorough explanation on how the cached and non-cahced routes should behave) approved by Taylor (or someone else who is in charge of making the final decision on the system's behavior) it is going to be a sort of shot in the dark.\r\n",
"created_at": "2024-04-16T11:46:18Z"
},
{
"body": "I also think cached routes should exactly mimic the behavior of uncached routes. In other words, if cached routes are currently different than uncached, they should be updated to match the uncached behavior.",
"created_at": "2024-04-16T19:23:17Z"
},
{
"body": "Hello there,\r\n\r\nI played around with the issue today, and I didn't find any way to write tests for this issue. What do I mean.\r\n\r\nTo check whether the cached routes behave in the correct way, they should be cached. The usual way to cache them is to use the artisan command. So, I used the [testRouteGrouping](https://github.com/laravel/framework/blob/877ebcab5fb0d97b8e8eb7c213dd549647e071ad/tests/Routing/RoutingRouteTest.php#L1134) method as a basis, but it turned out that you cannot just call an artisan command without a bootstrapped app (that makes sense). So, I thought to go in a different direction and use `Orchestra\\Testbench\\TestCase` which provides a bootstrapped app. And it kind of worked with the artisan command, but it doesn't store any cached routes (because the cache path is emulated).\r\n\r\nI thought, that mocking a cache path might be an option here. I mocked the `getCachedRoutesPath` to provide the existing path and it turned out that the artisan command reads a list of routes from a route file. But, the route file doesn't exist in the bare framework. So, this pattern for providing routes, which is used in the current test code base, \r\n```php\r\n $router = $this->getRouter();\r\n $router->group(['prefix' => 'foo'], function () use ($router) {\r\n $router->get('bar', function () {\r\n return 'hello';\r\n });\r\n });\r\n $routes = $router->getRoutes();\r\n $routes = $routes->getRoutes();\r\n```\r\ndoesn't work in this case. The command just doesn't get any routes.\r\n\r\nHave I missed something? Do you have any ideas or suggestions on how the tests could be implemented? Or, do you have any code examples of the tests that work with cached routes (I didn't find any)? Is there a way to cache the routes without the artisan command and without duplicating its functionality? Any idea or advice might be helpful in this case.",
"created_at": "2024-04-18T18:37:03Z"
},
{
"body": "@crynobone would you maybe know how we can test cached routes in framework using test bench?",
"created_at": "2024-04-19T05:25:00Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-04-19T09:08:32Z"
}
],
"number": 50239,
"title": "Different getPrefix() behavior for cached and non-cached routes"
} | {
"body": "Fixes : #50239 \r\n\r\nThe getPrefix() method of the Illuminate\\Routing\\Route returns different values for non-cached and cached routes:\r\n\r\n/{locale} - the return value of the getPrefix() method for a non-cached route\r\n{locale} - the return value of the getPrefix() method for a cached route\r\n\r\nThis PR fixes this issue by modifying the formatPrefix function in the RouteGroup class when initializing the route model\r\n\r\n\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 51176,
"review_comments": [],
"title": "[11.x] Fix the error with the prefix in non-cached routes"
} | {
"commits": [
{
"message": "[11.x] Fix the error with the prefix in non-cached routes.\n\n#50239 \r\nFix:The getPrefix() method of the Illuminate\\Routing\\Route returns different values for non-cached and cached routes:\r\n\r\n/{locale} - the return value of the getPrefix() method for a non-cached route\r\n{locale} - the return value of the getPrefix() method for a cached route"
},
{
"message": "Update RouteGroup.php"
}
],
"files": [
{
"diff": "@@ -66,7 +66,9 @@ protected static function formatPrefix($new, $old, $prependExistingPrefix = true\n $old = $old['prefix'] ?? '';\n \n if ($prependExistingPrefix) {\n- return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n+ return isset($new['prefix']) \n+ ? ($old ? trim($old, '/').'/'.trim($new['prefix'], '/') : trim($new['prefix'], '/')) \n+ : $old;\n }\n \n return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;",
"filename": "src/Illuminate/Routing/RouteGroup.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n11.1.0\n\n### PHP Version\n\n8.2.17\n\n### Database Driver & Version\n\nSQL Server 2022\n\n### Description\n\nI am in the process of upgrading Laravel from version 10 to 11 for a project that uses SQLServer as the database. In Laravel 10, after executing `php artisan migrate command`, the migrations table is successfully created, and running `php artisan migrate:status` yields the expected output.\r\n\r\nHowever, after upgrading to Laravel 11, while the `php artisan migrate command` still creates the migrations table as expected, running `php artisan migrate:status` results in an error message stating `ERROR Migration table not found.`\r\nThis issue arises despite the fact that the migrations table does indeed exist in the SQLServer database, as confirmed through manual inspection.\r\n\r\nThis behavior is inconsistent with the expected outcome and differs from the results in Laravel 10 under the same conditions. It suggests there might be an issue with how the migration status command interacts with the SQLServer database in Laravel 11, specifically in recognizing the existence of the migrations table.\r\n\r\nI am looking for guidance on resolving this error and understanding whether this is a known issue with a workaround or a newly introduced bug in Laravel 11. \n\n### Steps To Reproduce\n\n1. Create a fresh Laravel 11 project and configure it to use SQLServer. \r\n2. Execute `php artisan migrate` to initialize the database schemas, including the creation of the migrations table in your SQLServer database.\r\n3. Immediately following the successful migration, run `php artisan migrate:status` to assess the migration status. Despite the migrations table clearly existing in the SQLServer database, this command unexpectedly results in an error stating `ERROR Migration table not found.`",
"comments": [
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-03-29T14:04:22Z"
},
{
"body": "Sorry, I could only reproduce it once but not anymore.\r\n\r\nPlease put `dd(\\Schema::getTables());` into a route/controller and share the (expanded) result.",
"created_at": "2024-03-29T14:19:33Z"
},
{
"body": "Thank you for your response! \r\nI have attached the image showing the expanded result. \r\nPlease note that the presentation might be somewhat basic due to the omission of production code for privacy reasons.\r\n\r\n<img width=\"566\" alt=\"スクリーンショット 2024-03-30 0 32 40\" src=\"https://github.com/laravel/framework/assets/64859506/93684161-6dcc-40f2-a8dd-6d2bbe585303\">\r\n",
"created_at": "2024-03-29T15:36:51Z"
},
{
"body": "Your schema is not actually called `sample`, right? But you are using a custom one (i.e. not `dbo`)?",
"created_at": "2024-03-29T17:06:17Z"
},
{
"body": "And what is the value of `config('database.migrations')`?",
"created_at": "2024-03-29T17:52:52Z"
},
{
"body": "@staudenmeir \r\nYou are correct. In our project, we manage multiple schemas within a single SQL Server database, hence we are utilizing custom schemas. \"sample\" is indeed one such example.",
"created_at": "2024-03-30T04:03:48Z"
},
{
"body": "How did you make the custom schema work with Laravel (since there is no config option for it)? Did you set it as the default schema for the database user?",
"created_at": "2024-03-30T09:24:23Z"
},
{
"body": "As @staudenmeir said, there is no config option for setting default schema when using SQL Server connection. So it's hardcoded to `dbo` unless you explicitly pass the custom schema name. So on your application's `config/database.php` file, you may change the `migrations` option as follow and let us know if it solves your issue:\r\n\r\n```php\r\n'migrations' => 'sample.migrations', // as your default schema is `sample`\r\n```\r\n\r\nOr using new Laravel 11 options:\r\n\r\n```php\r\n'migrations' => [\r\n 'table' => 'sample.migrations', // as your default schema is `sample`\r\n 'update_date_on_publish' => true,\r\n],\r\n```",
"created_at": "2024-03-30T10:43:54Z"
},
{
"body": "@staudenmeir @hafezdivandari \r\n\r\nThank you for your response! \r\nIndeed, by changing the default schema, it has been working even without a configuration option in previous versions of Laravel.\r\n\r\nI've confirmed that adding the following code works without any issues!\r\n\r\n```php\r\n'migrations' => [\r\n 'table' => 'sample.migrations',\r\n],\r\n\r\n```\r\n\r\nIs there any plan to support the traditional behavior in the future?\r\n",
"created_at": "2024-03-30T13:59:32Z"
},
{
"body": "@Hikaru-Giannis It's a new feature on Laravel 11 that you can use custom schema name on almost all `Schema` methods, you may check PR #50019 and #49965.\r\n\r\n> Is there any plan to support the traditional behavior in the future?\r\n\r\nJust sent PR #50855 to also support \"traditional behavior\".",
"created_at": "2024-03-30T15:08:23Z"
},
{
"body": "@hafezdivandari \r\nThank you for your support! I will also check the PRs you mentioned.\r\n\r\n> How did you make the custom schema work with Laravel (since there is no config option for it)? Did you set it as the default schema for the database user?\r\n\r\nMy apologies for the oversight. In previous versions of Laravel, I was able to use a custom schema by executing SQL statements like the following:\r\n\r\n```sql\r\nCREATE LOGIN [sample] WITH PASSWORD = 'sample';\r\nCREATE SCHEMA [sample];\r\nCREATE USER [sample] FOR LOGIN [sample];\r\nALTER USER [sample] WITH DEFAULT_SCHEMA = [sample];\r\nGRANT CREATE TABLE TO [sample];\r\nGRANT SELECT ON SCHEMA::role TO [sample];\r\nGRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER ON SCHEMA::sample TO [sample];\r\nGRANT CREATE TABLE TO [sample];\r\nGRANT ALTER ON SCHEMA::sample TO [sample];\r\n\r\n```\r\n\r\nDoes this align with your intended answer?",
"created_at": "2024-03-31T00:02:03Z"
},
{
"body": "> Sorry, I could only reproduce it once but not anymore.\r\n> \r\n> Please put `dd(\\Schema::getTables());` into a route/controller and share the (expanded) result.\r\n\r\n\r\nCan you please add some details ?",
"created_at": "2024-03-31T23:42:32Z"
}
],
"number": 50842,
"title": "Migration table not found error in SQL Server despite existence of migrations table when running migrate command"
} | {
"body": "Fixes #50842\r\n\r\nOn SQL Server, `Schema` methods were always using `dbo` schema as default. This causes problem in a rare condition that user manually changes the default schema (e.g by calling `alter user my_user with default_schema = my_schema`). This PR fixes that by utilizing the actual default schema (not always `dbo`).",
"number": 50855,
"review_comments": [],
"title": "[11.x] Use Default Schema Name on SQL Server"
} | {
"commits": [
{
"message": "get default schema name on sqlsrv"
},
{
"message": "force re-run tests"
},
{
"message": "add test"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "revert adding test"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "wip"
},
{
"message": "formatting"
}
],
"files": [
{
"diff": "@@ -37,6 +37,16 @@ class SqlServerGrammar extends Grammar\n */\n protected $fluentCommands = ['Default'];\n \n+ /**\n+ * Compile a query to determine the name of the default schema.\n+ *\n+ * @return string\n+ */\n+ public function compileDefaultSchema()\n+ {\n+ return 'select schema_name()';\n+ }\n+\n /**\n * Compile a create database command.\n *",
"filename": "src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php",
"status": "modified"
},
{
"diff": "@@ -42,6 +42,7 @@ public function hasTable($table)\n {\n [$schema, $table] = $this->parseSchemaAndTable($table);\n \n+ $schema ??= $this->getDefaultSchema();\n $table = $this->connection->getTablePrefix().$table;\n \n foreach ($this->getTables() as $value) {\n@@ -64,6 +65,7 @@ public function hasView($view)\n {\n [$schema, $view] = $this->parseSchemaAndTable($view);\n \n+ $schema ??= $this->getDefaultSchema();\n $view = $this->connection->getTablePrefix().$view;\n \n foreach ($this->getViews() as $value) {\n@@ -151,6 +153,16 @@ public function getForeignKeys($table)\n );\n }\n \n+ /**\n+ * Get the default schema for the connection.\n+ *\n+ * @return string\n+ */\n+ protected function getDefaultSchema()\n+ {\n+ return $this->connection->scalar($this->grammar->compileDefaultSchema());\n+ }\n+\n /**\n * Parse the database object reference and extract the schema and table.\n *\n@@ -159,7 +171,7 @@ public function getForeignKeys($table)\n */\n protected function parseSchemaAndTable($reference)\n {\n- $parts = array_pad(explode('.', $reference, 2), -2, 'dbo');\n+ $parts = array_pad(explode('.', $reference, 2), -2, null);\n \n if (str_contains($parts[1], '.')) {\n $database = $parts[0];",
"filename": "src/Illuminate/Database/Schema/SqlServerBuilder.php",
"status": "modified"
},
{
"diff": "@@ -425,6 +425,43 @@ public function testAutoIncrementStartingValue($connection)\n });\n }\n \n+ #[DataProvider('connectionProvider')]\n+ public function testHasTable($connection)\n+ {\n+ if ($this->driver !== 'sqlsrv') {\n+ $this->markTestSkipped('Test requires a SQL Server connection.');\n+ }\n+\n+ $db = DB::connection($connection);\n+ $schema = $db->getSchemaBuilder();\n+\n+ try {\n+ $db->statement(\"create login my_user with password = 'Passw0rd'\");\n+ $db->statement('create user my_user for login my_user');\n+ } catch(\\Illuminate\\Database\\QueryException $e) {\n+ //\n+ }\n+\n+ $db->statement('grant create table to my_user');\n+ $db->statement('grant alter on SCHEMA::my_schema to my_user');\n+ $db->statement(\"alter user my_user with default_schema = my_schema execute as user='my_user'\");\n+\n+ config([\n+ 'database.connections.'.$connection.'.username' => 'my_user',\n+ 'database.connections.'.$connection.'.password' => 'Passw0rd',\n+ ]);\n+\n+ $this->assertEquals('my_schema', $db->scalar('select schema_name()'));\n+\n+ $schema->create('table', function (Blueprint $table) {\n+ $table->id();\n+ });\n+\n+ $this->assertTrue($schema->hasTable('table'));\n+ $this->assertTrue($schema->hasTable('my_schema.table'));\n+ $this->assertFalse($schema->hasTable('dbo.table'));\n+ }\n+\n public static function connectionProvider(): array\n {\n return [",
"filename": "tests/Integration/Database/SchemaBuilderSchemaNameTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.48.3\n\n### PHP Version\n\n8.3.3\n\n### Database Driver & Version\n\nmysqlnd 8.3.3\n\n### Description\n\nThis issue is similar to #49894, but for querying pivot relations with raw expressions.\r\n\r\nIn Laravel 9 it was possible to do this:\r\n\r\n```php\r\n$item->someMorphToMany()\r\n ->wherePivotNotIn(\r\n DB::raw(\"CONCAT(some_field, '_', other_field)\"),\r\n ['a_b', 'c_d']\r\n )->detach();\r\n```\r\n\r\nwhich would produce a where statement like `CONCAT(some_field, '_', other_field) not in (?, ?)` which is to be expected.\r\n\r\nWith the changes of enforcing manual casting of the expression to its raw value, I can no longer get `wherePivotNotIn` to produce the expected output.\r\n\r\n```php\r\n$item->someMorphToMany()\r\n ->wherePivotNotIn(\r\n DB::raw(\"CONCAT(some_field, '_', other_field)\")->getValue(DB::connection()->getQueryGrammar()),\r\n ['a_b', 'c_d']\r\n )->detach();\r\n```\r\n\r\nnow produces the following where clause\r\n\r\n```sql\r\n`database`.`pivot_table`.`CONCAT(some_field, '_', other_field)` not in (?, ?)`\r\n```\r\n\r\nwhich is correctly identified by mysql as an unknown field.\r\n\r\nFollowing the callgraph, I can get rid of the database and table prefix, by prefixing the concatenated fields myself (see https://github.com/laravel/framework/blob/10.x/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php#L1527 ).\r\n\r\nBut then somehwhere in the wrap function it gets mangled again:\r\n```php\r\n$item->someMorphToMany()\r\n ->wherePivotNotIn(\r\n DB::raw(\"CONCAT(table.some_field, '_', table.other_field)\")->getValue(DB::connection()->getQueryGrammar()),\r\n ['a_b', 'c_d']\r\n )->detach();\r\n```\r\n\r\n```sql\r\n`CONCAT(table`.`some_field, '_', table`.`other_field)` not in (?, ?)\r\n```\r\n\r\nI'm not confident enough to fiddle around in the guts of eloquent to create a PR for this, so any help would be greatly appreciated\n\n### Steps To Reproduce\n\n1. Setup a `morphToMany` relationship\r\n2. Try to query the relationship with a raw expression constraint to the pivot",
"comments": [
{
"body": "@tpetry is this something we need to fix as well?",
"created_at": "2024-03-28T11:21:54Z"
},
{
"body": "Yeah, special handling in the core is required to unwrap expressions in this case. But due to personal stuff, I cant work on this currently.",
"created_at": "2024-03-29T07:52:24Z"
},
{
"body": "No worries at all @tpetry. Will leave this one open for anyone to pick up.",
"created_at": "2024-03-29T08:05:53Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-03-29T08:06:13Z"
},
{
"body": "Thanks @Jigsaw5279 for reporting that, I have fixed that in #50849 \r\nHowever, I see that your issue is related to Laravel 10.x and I made MR to 11.x according to [Which branch](https://laravel.com/docs/11.x/contributions#which-branch) - is it okay @driesvints?",
"created_at": "2024-03-30T00:02:37Z"
}
],
"number": 50787,
"title": "Using expressions in pivot queries"
} | {
"body": "Query builder supports query expressions when Many-to-Many relationships. \r\nI have fixed that by check if passed column to be qualified with explicit table name is query expression, if so I made a return to use it as developer requested, without qualifying. Added support for expression in clauses methods types. Covered by test which is verifying if base relation methods receives expression.\r\nMoreover, PHPUnit test case replaced with Mockery adapter test case, which closes Mockery by themself.\r\n\r\nThis MR solves #50787",
"number": 50849,
"review_comments": [],
"title": "Allow passing query Expression as column in Many-to-Many relationship"
} | {
"commits": [
{
"message": "Allow passing query Expression as column in Many-to-Many relationships (#50787)"
}
],
"files": [
{
"diff": "@@ -65,7 +65,7 @@ class BelongsToMany extends Relation\n /**\n * The pivot table columns to retrieve.\n *\n- * @var array\n+ * @var array<string|\\Illuminate\\Contracts\\Database\\Query\\Expression>\n */\n protected $pivotColumns = [];\n \n@@ -356,7 +356,7 @@ public function as($accessor)\n /**\n * Set a where clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param mixed $operator\n * @param mixed $value\n * @param string $boolean\n@@ -372,7 +372,7 @@ public function wherePivot($column, $operator = null, $value = null, $boolean =\n /**\n * Set a \"where between\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param array $values\n * @param string $boolean\n * @param bool $not\n@@ -386,7 +386,7 @@ public function wherePivotBetween($column, array $values, $boolean = 'and', $not\n /**\n * Set a \"or where between\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param array $values\n * @return $this\n */\n@@ -398,7 +398,7 @@ public function orWherePivotBetween($column, array $values)\n /**\n * Set a \"where pivot not between\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param array $values\n * @param string $boolean\n * @return $this\n@@ -411,7 +411,7 @@ public function wherePivotNotBetween($column, array $values, $boolean = 'and')\n /**\n * Set a \"or where not between\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param array $values\n * @return $this\n */\n@@ -423,7 +423,7 @@ public function orWherePivotNotBetween($column, array $values)\n /**\n * Set a \"where in\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param mixed $values\n * @param string $boolean\n * @param bool $not\n@@ -439,7 +439,7 @@ public function wherePivotIn($column, $values, $boolean = 'and', $not = false)\n /**\n * Set an \"or where\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param mixed $operator\n * @param mixed $value\n * @return $this\n@@ -454,7 +454,7 @@ public function orWherePivot($column, $operator = null, $value = null)\n *\n * In addition, new pivot records will receive this value.\n *\n- * @param string|array $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression|array<string, string> $column\n * @param mixed $value\n * @return $this\n *\n@@ -494,7 +494,7 @@ public function orWherePivotIn($column, $values)\n /**\n * Set a \"where not in\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param mixed $values\n * @param string $boolean\n * @return $this\n@@ -519,7 +519,7 @@ public function orWherePivotNotIn($column, $values)\n /**\n * Set a \"where null\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param string $boolean\n * @param bool $not\n * @return $this\n@@ -534,7 +534,7 @@ public function wherePivotNull($column, $boolean = 'and', $not = false)\n /**\n * Set a \"where not null\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param string $boolean\n * @return $this\n */\n@@ -546,7 +546,7 @@ public function wherePivotNotNull($column, $boolean = 'and')\n /**\n * Set a \"or where null\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param bool $not\n * @return $this\n */\n@@ -558,7 +558,7 @@ public function orWherePivotNull($column, $not = false)\n /**\n * Set a \"or where not null\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @return $this\n */\n public function orWherePivotNotNull($column)\n@@ -569,7 +569,7 @@ public function orWherePivotNotNull($column)\n /**\n * Add an \"order by\" clause for a pivot table column.\n *\n- * @param string $column\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n * @param string $direction\n * @return $this\n */\n@@ -1558,11 +1558,15 @@ public function getPivotColumns()\n /**\n * Qualify the given column name by the pivot table.\n *\n- * @param string $column\n- * @return string\n+ * @param string|\\Illuminate\\Contracts\\Database\\Query\\Expression $column\n+ * @return string|\\Illuminate\\Contracts\\Database\\Query\\Expression\n */\n public function qualifyPivotColumn($column)\n {\n+ if ($this->getGrammar()->isExpression($column)) {\n+ return $column;\n+ }\n+\n return str_contains($column, '.')\n ? $column\n : $this->table.'.'.$column;",
"filename": "src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,152 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Database;\n+\n+use Illuminate\\Database\\Capsule\\Manager as DB;\n+use Illuminate\\Database\\Eloquent\\Model as Eloquent;\n+use Illuminate\\Database\\Eloquent\\Relations\\MorphToMany;\n+use Illuminate\\Database\\Query\\Expression;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use PHPUnit\\Framework\\TestCase;\n+\n+class DatabaseEloquentBelongsToManyExpressionTest extends TestCase\n+{\n+ protected function setUp(): void\n+ {\n+ $db = new DB;\n+\n+ $db->addConnection([\n+ 'driver' => 'sqlite',\n+ 'database' => ':memory:',\n+ ]);\n+\n+ $db->bootEloquent();\n+ $db->setAsGlobal();\n+\n+ $this->createSchema();\n+ }\n+\n+ public function testAmbiguousColumnsExpression(): void\n+ {\n+ $this->seedData();\n+\n+ $tags = DatabaseEloquentBelongsToManyExpressionTestTestPost::findOrFail(1)\n+ ->tags()\n+ ->wherePivotNotIn(new Expression(\"tag_id || '_' || type\"), ['1_t1'])\n+ ->get();\n+\n+ $this->assertCount(1, $tags);\n+ $this->assertEquals(2, $tags->first()->getKey());\n+ }\n+\n+ public function testQualifiedColumnExpression(): void\n+ {\n+ $this->seedData();\n+\n+ $tags = DatabaseEloquentBelongsToManyExpressionTestTestPost::findOrFail(2)\n+ ->tags()\n+ ->wherePivotNotIn(new Expression(\"taggables.tag_id || '_' || taggables.type\"), ['2_t2'])\n+ ->get();\n+\n+ $this->assertCount(1, $tags);\n+ $this->assertEquals(3, $tags->first()->getKey());\n+ }\n+\n+ /**\n+ * Setup the database schema.\n+ *\n+ * @return void\n+ */\n+ public function createSchema()\n+ {\n+ $this->schema()->create('posts', fn (Blueprint $t) => $t->id());\n+ $this->schema()->create('tags', fn (Blueprint $t) => $t->id());\n+ $this->schema()->create('taggables', function (Blueprint $t) {\n+ $t->unsignedBigInteger('tag_id');\n+ $t->unsignedBigInteger('taggable_id');\n+ $t->string('type', 10);\n+ $t->string('taggable_type');\n+ }\n+ );\n+ }\n+\n+ /**\n+ * Tear down the database schema.\n+ *\n+ * @return void\n+ */\n+ protected function tearDown(): void\n+ {\n+ $this->schema()->drop('posts');\n+ $this->schema()->drop('tags');\n+ $this->schema()->drop('taggables');\n+ }\n+\n+ /**\n+ * Helpers...\n+ */\n+ protected function seedData(): void\n+ {\n+ $p1 = DatabaseEloquentBelongsToManyExpressionTestTestPost::query()->create();\n+ $p2 = DatabaseEloquentBelongsToManyExpressionTestTestPost::query()->create();\n+ $t1 = DatabaseEloquentBelongsToManyExpressionTestTestTag::query()->create();\n+ $t2 = DatabaseEloquentBelongsToManyExpressionTestTestTag::query()->create();\n+ $t3 = DatabaseEloquentBelongsToManyExpressionTestTestTag::query()->create();\n+\n+ $p1->tags()->sync([\n+ $t1->getKey() => ['type' => 't1'],\n+ $t2->getKey() => ['type' => 't2'],\n+ ]);\n+ $p2->tags()->sync([\n+ $t2->getKey() => ['type' => 't2'],\n+ $t3->getKey() => ['type' => 't3'],\n+ ]);\n+ }\n+\n+ /**\n+ * Get a database connection instance.\n+ *\n+ * @return \\Illuminate\\Database\\ConnectionInterface\n+ */\n+ protected function connection()\n+ {\n+ return Eloquent::getConnectionResolver()->connection();\n+ }\n+\n+ /**\n+ * Get a schema builder instance.\n+ *\n+ * @return \\Illuminate\\Database\\Schema\\Builder\n+ */\n+ protected function schema()\n+ {\n+ return $this->connection()->getSchemaBuilder();\n+ }\n+}\n+\n+class DatabaseEloquentBelongsToManyExpressionTestTestPost extends Eloquent\n+{\n+ protected $table = 'posts';\n+ protected $fillable = ['id'];\n+ public $timestamps = false;\n+\n+ public function tags(): MorphToMany\n+ {\n+ return $this->morphToMany(\n+ DatabaseEloquentBelongsToManyExpressionTestTestTag::class,\n+ 'taggable',\n+ 'taggables',\n+ 'taggable_id',\n+ 'tag_id',\n+ 'id',\n+ 'id',\n+ );\n+ }\n+}\n+\n+class DatabaseEloquentBelongsToManyExpressionTestTestTag extends Eloquent\n+{\n+ protected $table = 'tags';\n+ protected $fillable = ['id'];\n+ public $timestamps = false;\n+}",
"filename": "tests/Database/DatabaseEloquentBelongsToManyExpressionTest.php",
"status": "added"
},
{
"diff": "@@ -6,6 +6,7 @@\n use Illuminate\\Database\\Eloquent\\Collection;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany;\n+use Illuminate\\Database\\Query\\Grammars\\Grammar;\n use Mockery as m;\n use PHPUnit\\Framework\\TestCase;\n \n@@ -61,6 +62,9 @@ protected function getRelation()\n $builder->shouldReceive('getModel')->andReturn($related);\n $related->shouldReceive('qualifyColumn');\n $builder->shouldReceive('join', 'where');\n+ $builder->shouldReceive('getGrammar')->andReturn(\n+ m::mock(Grammar::class, ['isExpression' => false])\n+ );\n \n return new BelongsToMany(\n $builder,",
"filename": "tests/Database/DatabaseEloquentBelongsToManyWithCastedAttributesTest.php",
"status": "modified"
},
{
"diff": "@@ -5,6 +5,7 @@\n use Illuminate\\Database\\Eloquent\\Builder;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany;\n+use Illuminate\\Database\\Query\\Grammars\\Grammar;\n use Mockery as m;\n use PHPUnit\\Framework\\TestCase;\n use stdClass;\n@@ -55,6 +56,7 @@ public function getRelationArguments()\n $builder->shouldReceive('join')->once()->with('club_user', 'users.id', '=', 'club_user.user_id');\n $builder->shouldReceive('where')->once()->with('club_user.club_id', '=', 1);\n $builder->shouldReceive('where')->once()->with('club_user.is_admin', '=', 1, 'and');\n+ $builder->shouldReceive('getGrammar')->andReturn(m::mock(Grammar::class, ['isExpression' => false]));\n \n return [$builder, $parent, 'club_user', 'club_id', 'user_id', 'id', 'id', null, false];\n }",
"filename": "tests/Database/DatabaseEloquentBelongsToManyWithDefaultAttributesTest.php",
"status": "modified"
},
{
"diff": "@@ -7,6 +7,7 @@\n use Illuminate\\Database\\Eloquent\\Builder;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany;\n+use Illuminate\\Database\\Query\\Grammars\\Grammar;\n use Mockery as m;\n use PHPUnit\\Framework\\TestCase;\n \n@@ -31,6 +32,7 @@ public function testItWillNotTouchRelatedModelsWhenUpdatingChild(): void\n $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);\n $builder->shouldReceive('getModel')->andReturn($related);\n $builder->shouldReceive('where');\n+ $builder->shouldReceive('getGrammar')->andReturn(m::mock(Grammar::class, ['isExpression' => false]));\n $relation = new BelongsToMany($builder, $parent, 'article_users', 'user_id', 'article_id', 'id', 'id');\n $builder->shouldReceive('update')->never();\n ",
"filename": "tests/Database/DatabaseEloquentBelongsToManyWithoutTouchingTest.php",
"status": "modified"
},
{
"diff": "@@ -2860,6 +2860,7 @@ protected function addMockConnection($model)\n $resolver->shouldReceive('connection')->andReturn($connection = m::mock(Connection::class));\n $connection->shouldReceive('getQueryGrammar')->andReturn($grammar = m::mock(Grammar::class));\n $grammar->shouldReceive('getBitwiseOperators')->andReturn([]);\n+ $grammar->shouldReceive('isExpression')->andReturnFalse();\n $connection->shouldReceive('getPostProcessor')->andReturn($processor = m::mock(Processor::class));\n $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) {\n return new BaseBuilder($connection, $grammar, $processor);\n@@ -3214,6 +3215,7 @@ public function getConnection()\n $mock = m::mock(Connection::class);\n $mock->shouldReceive('getQueryGrammar')->andReturn($grammar = m::mock(Grammar::class));\n $grammar->shouldReceive('getBitwiseOperators')->andReturn([]);\n+ $grammar->shouldReceive('isExpression')->andReturnFalse();\n $mock->shouldReceive('getPostProcessor')->andReturn($processor = m::mock(Processor::class));\n $mock->shouldReceive('getName')->andReturn('name');\n $mock->shouldReceive('query')->andReturnUsing(function () use ($mock, $grammar, $processor) {",
"filename": "tests/Database/DatabaseEloquentModelTest.php",
"status": "modified"
},
{
"diff": "@@ -5,18 +5,15 @@\n use Illuminate\\Database\\Eloquent\\Builder;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Relations\\MorphToMany;\n+use Illuminate\\Database\\Query\\Expression;\n+use Illuminate\\Database\\Query\\Grammars\\Grammar;\n+use Mockery\\Adapter\\Phpunit\\MockeryTestCase as TestCase;\n use Mockery as m;\n-use PHPUnit\\Framework\\TestCase;\n use stdClass;\n \n class DatabaseEloquentMorphToManyTest extends TestCase\n {\n- protected function tearDown(): void\n- {\n- m::close();\n- }\n-\n- public function testEagerConstraintsAreProperlyAdded()\n+ public function testEagerConstraintsAreProperlyAdded(): void\n {\n $relation = $this->getRelation();\n $relation->getParent()->shouldReceive('getKeyName')->andReturn('id');\n@@ -30,7 +27,7 @@ public function testEagerConstraintsAreProperlyAdded()\n $relation->addEagerConstraints([$model1, $model2]);\n }\n \n- public function testAttachInsertsPivotTableRecord()\n+ public function testAttachInsertsPivotTableRecord(): void\n {\n $relation = $this->getMockBuilder(MorphToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock();\n $query = m::mock(stdClass::class);\n@@ -43,7 +40,7 @@ public function testAttachInsertsPivotTableRecord()\n $relation->attach(2, ['foo' => 'bar']);\n }\n \n- public function testDetachRemovesPivotTableRecord()\n+ public function testDetachRemovesPivotTableRecord(): void\n {\n $relation = $this->getMockBuilder(MorphToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock();\n $query = m::mock(stdClass::class);\n@@ -59,7 +56,7 @@ public function testDetachRemovesPivotTableRecord()\n $this->assertTrue($relation->detach([1, 2, 3]));\n }\n \n- public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven()\n+ public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven(): void\n {\n $relation = $this->getMockBuilder(MorphToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock();\n $query = m::mock(stdClass::class);\n@@ -75,14 +72,39 @@ public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven()\n $this->assertTrue($relation->detach());\n }\n \n- public function getRelation()\n+ public function testQueryExpressionCanBePassedToDifferentPivotQueryBuilderClauses(): void\n+ {\n+ $value = 'pivot_value';\n+ $column = new Expression(\"CONCAT(foo, '_', bar)\");\n+ $relation = $this->getRelation();\n+ /** @var Builder|m\\MockInterface $builder */\n+ $builder = $relation->getQuery();\n+\n+ $builder->shouldReceive('where')->with($column, '=', $value, 'and')->times(2)->andReturnSelf();\n+ $relation->wherePivot($column, '=', $value);\n+ $relation->withPivotValue($column, $value);\n+\n+ $builder->shouldReceive('whereBetween')->with($column, [$value, $value], 'and', false)->once()->andReturnSelf();\n+ $relation->wherePivotBetween($column, [$value, $value]);\n+\n+ $builder->shouldReceive('whereIn')->with($column, [$value], 'and', false)->once()->andReturnSelf();\n+ $relation->wherePivotIn($column, [$value]);\n+\n+ $builder->shouldReceive('whereNull')->with($column, 'and', false)->once()->andReturnSelf();\n+ $relation->wherePivotNull($column);\n+\n+ $builder->shouldReceive('orderBy')->with($column, 'asc')->once()->andReturnSelf();\n+ $relation->orderByPivot($column);\n+ }\n+\n+ public function getRelation(): MorphToMany\n {\n [$builder, $parent] = $this->getRelationArguments();\n \n return new MorphToMany($builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'id', 'id');\n }\n \n- public function getRelationArguments()\n+ public function getRelationArguments(): array\n {\n $parent = m::mock(Model::class);\n $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));\n@@ -105,6 +127,11 @@ public function getRelationArguments()\n $builder->shouldReceive('where')->once()->with('taggables.taggable_id', '=', 1);\n $builder->shouldReceive('where')->once()->with('taggables.taggable_type', get_class($parent));\n \n+ $grammar = m::mock(Grammar::class);\n+ $grammar->shouldReceive('isExpression')->with(m::type(Expression::class))->andReturnTrue();\n+ $grammar->shouldReceive('isExpression')->with(m::type('string'))->andReturnFalse();\n+ $builder->shouldReceive('getGrammar')->andReturn($grammar);\n+\n return [$builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'id', 'id', 'relation_name', false];\n }\n }",
"filename": "tests/Database/DatabaseEloquentMorphToManyTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n11\r\n\r\n### PHP Version\r\n\r\n8.3\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nReferenced Code: https://github.com/laravel/framework/commit/ceb8ed25e7f72f69d3df508765607b8825e046c5#r139707506\r\n\r\nThe previous code snippet makes a hash check, problem is **my app does not have a password field** this causes the previous method storePasswordHashInSession to set an empty password hash in the session, causing the hash_equals to throw the following exception.\r\n\r\n```\r\nhash_equals(): Argument #1 ($known_string) must be of type string, null given\r\n```\r\n\r\nStackstace via Flare https://flareapp.io/share/J7oDeQZ5#context-request-browser\r\n\r\n### Steps To Reproduce\r\n\r\nCreate a new application and remove the password field via the migration",
"comments": [
{
"body": "I have the same problem as I don't use a password for authentication. Overrode the getAuthPasswordName method in my User model seemed to work if I returned email from it.\r\n\r\n```php\r\npublic function getAuthPasswordName()\r\n{\r\n return \"email\";\r\n}\r\n```\r\n\r\nNot sure if this is a good approach or not but work for now.",
"created_at": "2024-03-13T04:34:04Z"
},
{
"body": "> I have the same problem as I don't use a password for authentication. Overrode the getAuthPasswordName method in my User model seemed to work if I returned email from it.\r\n> \r\n> ```\r\n> public function getAuthPasswordName()\r\n> {\r\n> return \"email\";\r\n> }\r\n> ```\r\n> \r\n> Not sure if this is a good approach or not but work for now.\r\n\r\n\r\nOn the user Model also works in my case, but it will just treat the new id as the password which technically should not be needed at all.",
"created_at": "2024-03-13T04:35:31Z"
},
{
"body": "cc @valorin ",
"created_at": "2024-03-13T09:47:15Z"
},
{
"body": "@valorin I'm not sure what the behaviour should be if there's an empty password. Should we logout the user in that case?",
"created_at": "2024-03-13T10:14:53Z"
},
{
"body": "The problem is the `password_hash_*` session key is being set, even without a password field on the record. There is no point setting this at all if there is no password, so I think we need a way to disable that entirely - and detect when there is no password for backwards compatibility. At the moment the code just assumes there is a password and sets the key - it hashes an empty string fine, but cannot compare an empty string.\r\n\r\nI'll work on a possible fix.",
"created_at": "2024-03-13T10:27:03Z"
},
{
"body": "Thanks @valorin ",
"created_at": "2024-03-13T10:30:02Z"
},
{
"body": "Alright, I've dived deeper into this and it seems to be caused by the `\\Illuminate\\Session\\Middleware\\AuthenticateSession` middleware, whose sole purpose is to log out any other sessions when the user changes their password. It's also optional and disabled by default.\r\n\r\nI'm having trouble replicating the issue in 11 after enabling it, but I'll keep trying. However, I suspect the issue is actually that this middleware shouldn't be used when you're not using a password.\r\n\r\nIs there a reason why you're using this middleware? Or can you replicate this issue without this middleware enabled?",
"created_at": "2024-03-13T10:46:20Z"
},
{
"body": "Alright, I replicated the issue and it's definitely that middleware. I've made a PR to silence the issue: https://github.com/laravel/framework/pull/50507\r\n\r\nThe other fix is to disable the middleware. That could go in the upgrade guide - this middleware is not useful without a password on the user record.",
"created_at": "2024-03-13T11:03:45Z"
}
],
"number": 50497,
"title": "Exception thrown if Application does not have a password field"
} | {
"body": "Fixes #50497\n\nThe `\\Illuminate\\Session\\Middleware\\AuthenticateSession` middleware is designed to log out other user sessions when their password has changed. \n\nIt shouldn't be used when there is no password on the user record, however it used to fail silently in 10.x and earlier. Since 11.x expects a password, it now fails on apps without a password and this middleware enabled. This checks for a password and if none set, ignores the rest of the checks to prevent errors in a backwards compatible way.\n\nIdeally this middleware shouldn't be enabled on these sites - so the alternative is to instruct devs to disable this middleware on affected apps and document this in the Upgrade guide.\n",
"number": 50507,
"review_comments": [],
"title": "[11.x] Check for password before storing hash in session"
} | {
"commits": [
{
"message": "Check for password before storing hash in session\n\nFixes #50497"
}
],
"files": [
{
"diff": "@@ -44,7 +44,7 @@ public function __construct(AuthFactory $auth)\n */\n public function handle($request, Closure $next)\n {\n- if (! $request->hasSession() || ! $request->user()) {\n+ if (! $request->hasSession() || ! $request->user() || ! $request->user()->getAuthPassword()) {\n return $next($request);\n }\n ",
"filename": "src/Illuminate/Session/Middleware/AuthenticateSession.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.42.0\r\n\r\n### PHP Version\r\n\r\n8.3.2\r\n\r\n### Database Driver & Version\r\n\r\nRedis 7.2.4\r\n\r\n### Description\r\n\r\nQueued jobs with ShouldBeUnique may cause stale unique locks in the case when the dependent model is missing.\r\n\r\nAccording to the source code of the [CallQueuedHandler::call()](https://github.com/laravel/framework/blob/10.x/src/Illuminate/Queue/CallQueuedHandler.php#L58) unique lock cleanup may never be reached in case if the job depends on the missing model AND the job is configured to be deleted when the model is missing (`public $deleteWhenMissingModels = true`).\r\n\r\n\r\n\r\n### Steps To Reproduce\r\n\r\nThe PoC is made using Redis queue, a similar approach may work with other drivers.\r\n\r\n1. Create a new project: `laravel new poc`.\r\n2. Ensure Redis is configured & reachable in your `.env` file. **WARNING**: PoC will flush all keys.\r\n3. Create poc.php file with the following contents:\r\n```php\r\n<?php\r\n\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Queue\\WorkerOptions;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Illuminate\\Support\\Facades\\Queue;\r\nuse Illuminate\\Support\\Facades\\Redis;\r\nuse Illuminate\\Queue\\SerializesModels;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Contracts\\Console\\Kernel;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Contracts\\Queue\\ShouldBeUnique;\r\n\r\nrequire 'vendor/autoload.php';\r\n$app = require __DIR__.'/bootstrap/app.php';\r\n$cli = $app->make(Kernel::class);\r\n$cli->bootstrap();\r\n\r\nconfig([\r\n 'database.default' => 'sqlite',\r\n 'queue.default' => 'redis',\r\n 'cache.default' => 'redis',\r\n]);\r\n\r\n@unlink(config('database.connections.sqlite.database'));\r\n$cli->call('migrate', ['--force' => true]);\r\n\r\nDB::unprepared(\"\r\n CREATE TABLE IF NOT EXISTS main (\r\n id INTEGER NOT NULL PRIMARY KEY,\r\n name VARCHAR(255) UNIQUE\r\n )\r\n\");\r\n\r\nDB::unprepared(\"\r\n CREATE TABLE IF NOT EXISTS secondary (\r\n id INTEGER NOT NULL PRIMARY KEY,\r\n name VARCHAR(255) NOT NULL\r\n )\r\n\");\r\n\r\n// ensure there are no keys in the DB\r\nRedis::flushdb();\r\n\r\nclass Main extends Model {\r\n public $table = 'main';\r\n public $timestamps = false;\r\n public $fillable = ['name'];\r\n}\r\n\r\nclass Secondary extends Model {\r\n public $table = 'secondary';\r\n public $timestamps = false;\r\n public $fillable = ['name'];\r\n}\r\n\r\nclass MyJob implements ShouldQueue, ShouldBeUnique {\r\n use Dispatchable, Queueable, SerializesModels;\r\n\r\n public $tries = 1;\r\n public $maxExceptions = 1;\r\n public $deleteWhenMissingModels = true;\r\n\r\n public function __construct(\r\n public Main $main,\r\n public Secondary $secondary,\r\n )\r\n {\r\n }\r\n\r\n public function handle() {\r\n }\r\n\r\n public function uniqueId() {\r\n return 'job-for-' . $this->main->id;\r\n }\r\n}\r\n\r\n// create 2 instances\r\n$main = Main::create(['name' => 'main model']);\r\n$secondary = Secondary::create(['name' => 'secondary model']);\r\n\r\n// and schedule a job for them\r\nMyJob::dispatch($main, $secondary);\r\n\r\n// delete the secondary model\r\n$secondary->delete();\r\n\r\n// run the job\r\napp('queue.worker')->runNextJob('redis', 'default', new WorkerOptions);\r\n\r\necho 'Queue size: ', Queue::size('default'), PHP_EOL; // no tasks left\r\necho 'Redis contents:', PHP_EOL;\r\ndump(Redis::keys('*')); // unique id is still there\r\n```\r\n4. Execute the poc.php `php poc.php`\r\n5. Inspect the output to see the stale unique lock\r\n\r\n**Output**\r\n\r\n```\r\nQueue size: 0\r\nRedis contents:\r\narray:1 [\r\n 0 => \"laravel_database_laravel_cache_:laravel_unique_job:MyJobjob-for-1\"\r\n] // poc.php:95\r\n```\r\n\r\n**Expected result**\r\n\r\nThe unique lock has been removed.\r\n\r\n**Actual result**\r\n\r\nA stale unique lock still exists.",
"comments": [
{
"body": "The right approach here is to not make `uniqueId` dependent on the model and assign the id to the job when constructing it. I don't think you can expect deleteWhenMissingModels to be compatible with a behaviour in your jobs where you at all times need access to the model.",
"created_at": "2024-01-29T15:04:29Z"
},
{
"body": "The bug is not about the uniqueId as this can be addressed in the user code.\r\n\r\nThe bug is that `deleteWhenModelMissing` configuration may effectively break the unique job lock mechanism causing a particular kind of jobs to be blocked until manual intervention. And there are no log messages or errors logged.\r\n\r\nNeither of the cases is mentioned in the documentation and it took a while to figure out what was happening on the server and why there are so many stale unique locks.",
"created_at": "2024-01-29T17:27:40Z"
},
{
"body": "To make it more clear, here's another PoC to be executed in the same environment (step 3).\r\n\r\n```php\r\n<?php\r\n\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Queue\\WorkerOptions;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Illuminate\\Support\\Facades\\Queue;\r\nuse Illuminate\\Support\\Facades\\Redis;\r\nuse Illuminate\\Queue\\SerializesModels;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Contracts\\Console\\Kernel;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Contracts\\Queue\\ShouldBeUnique;\r\n\r\nrequire 'vendor/autoload.php';\r\n$app = require __DIR__.'/bootstrap/app.php';\r\n$cli = $app->make(Kernel::class);\r\n$cli->bootstrap();\r\n\r\nconfig([\r\n 'database.default' => 'sqlite',\r\n 'queue.default' => 'redis',\r\n 'cache.default' => 'redis',\r\n]);\r\n\r\n@unlink(config('database.connections.sqlite.database'));\r\n$cli->call('migrate', ['--force' => true]);\r\n\r\nDB::unprepared(\"\r\n CREATE TABLE main (\r\n id INTEGER NOT NULL PRIMARY KEY,\r\n name VARCHAR(255) UNIQUE\r\n )\r\n\");\r\n\r\n// ensure there are no keys in the DB\r\nRedis::flushdb();\r\n\r\nclass Main extends Model {\r\n public $table = 'main';\r\n public $timestamps = false;\r\n public $fillable = ['name'];\r\n}\r\n\r\nclass MyJob implements ShouldQueue, ShouldBeUnique {\r\n use Dispatchable, Queueable, SerializesModels;\r\n\r\n public $tries = 1;\r\n public $deleteWhenMissingModels = true;\r\n\r\n public function __construct(\r\n public Main $main,\r\n )\r\n {\r\n }\r\n\r\n public function handle() {\r\n }\r\n}\r\n\r\n// create the job instance\r\n$instance = Main::create(['name' => 'main model']);\r\n\r\n// and schedule a job for them\r\nMyJob::dispatch($instance);\r\n\r\n// delete the secondary model\r\n$instance->delete();\r\n\r\n// run the job\r\napp('queue.worker')->runNextJob('redis', 'default', new WorkerOptions);\r\n\r\necho 'Queue size: ', Queue::size('default'), PHP_EOL; // no tasks left\r\necho 'Redis contents:', PHP_EOL;\r\ndump(Redis::keys('*')); // unique id is still there\r\n```\r\n\r\nI would also argue, that unique ID is being created and maintained by the framework. Hence it is framework's job to ensure that the unique ID is properly attached to the job to avoid special cases like the described one.\r\n\r\nBut skip that for now, the fix for the lock itself would be highly appreciated.",
"created_at": "2024-01-29T17:41:19Z"
},
{
"body": "Thanks @naquad for that explanation. I'll re-open this one. We'd appreciate a PR for a fix if anyone can figure one out.",
"created_at": "2024-01-30T08:53:38Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-01-30T08:53:54Z"
},
{
"body": "Here's my take on the fix that needs some blessing before I get knee-deep into fixing tests.\r\n\r\nA somewhat hackish way would be the following:\r\n1. Make `UniqueLock::getKey()` public static (the naming scheme is a pure function, so it can be static IMHO).\r\n2. Update `UniqueLock::getKey()`: if it receives a string that looks like a unique lock key (just a precaution to ensure everything explodes if misused), it will return it as is.\r\n3. Update `Queue::createObjectPayload()` to save the unique ID as seen during the job queuing.\r\n4. Update `CallQueuedHandler` to rely on the unique ID in the payload rather than trying to get it from the job.\r\n\r\nThe patch would look like this:\r\n```patch\r\ndiff --git a/src/Illuminate/Bus/UniqueLock.php b/src/Illuminate/Bus/UniqueLock.php\r\nindex a4066b77c1..f07830caf3 100644\r\n--- a/src/Illuminate/Bus/UniqueLock.php\r\n+++ b/src/Illuminate/Bus/UniqueLock.php\r\n@@ -3,6 +3,7 @@\r\n namespace Illuminate\\Bus;\r\n \r\n use Illuminate\\Contracts\\Cache\\Repository as Cache;\r\n+use Illuminate\\Support\\Str;\r\n \r\n class UniqueLock\r\n {\r\n@@ -40,7 +41,7 @@ public function acquire($job)\r\n ? $job->uniqueVia()\r\n : $this->cache;\r\n \r\n- return (bool) $cache->lock($this->getKey($job), $uniqueFor)->get();\r\n+ return (bool) $cache->lock(static::getKey($job), $uniqueFor)->get();\r\n }\r\n \r\n /**\r\n@@ -55,7 +56,7 @@ public function release($job)\r\n ? $job->uniqueVia()\r\n : $this->cache;\r\n \r\n- $cache->lock($this->getKey($job))->forceRelease();\r\n+ $cache->lock(static::getKey($job))->forceRelease();\r\n }\r\n \r\n /**\r\n@@ -64,8 +65,12 @@ public function release($job)\r\n * @param mixed $job\r\n * @return string\r\n */\r\n- protected function getKey($job)\r\n+ public static function getKey($job)\r\n {\r\n+ if (is_string($job) && Str::startsWith($job, 'laravel_unique_job:')) {\r\n+ return $job;\r\n+ }\r\n+\r\n $uniqueId = method_exists($job, 'uniqueId')\r\n ? $job->uniqueId()\r\n : ($job->uniqueId ?? '');\r\ndiff --git a/src/Illuminate/Queue/CallQueuedHandler.php b/src/Illuminate/Queue/CallQueuedHandler.php\r\nindex 5bee1d9ebb..6a545f43e8 100644\r\n--- a/src/Illuminate/Queue/CallQueuedHandler.php\r\n+++ b/src/Illuminate/Queue/CallQueuedHandler.php\r\n@@ -10,7 +10,6 @@\r\n use Illuminate\\Contracts\\Container\\Container;\r\n use Illuminate\\Contracts\\Encryption\\Encrypter;\r\n use Illuminate\\Contracts\\Queue\\Job;\r\n-use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\r\n use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\r\n use Illuminate\\Database\\Eloquent\\ModelNotFoundException;\r\n use Illuminate\\Pipeline\\Pipeline;\r\n@@ -60,17 +59,18 @@ public function call(Job $job, array $data)\r\n $job, $this->getCommand($data)\r\n );\r\n } catch (ModelNotFoundException $e) {\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n return $this->handleModelNotFound($job, $e);\r\n }\r\n \r\n if ($command instanceof ShouldBeUniqueUntilProcessing) {\r\n- $this->ensureUniqueJobLockIsReleased($command);\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n }\r\n \r\n $this->dispatchThroughMiddleware($job, $command);\r\n \r\n if (! $job->isReleased() && ! $command instanceof ShouldBeUniqueUntilProcessing) {\r\n- $this->ensureUniqueJobLockIsReleased($command);\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n }\r\n \r\n if (! $job->hasFailed() && ! $job->isReleased()) {\r\n@@ -196,13 +196,14 @@ protected function ensureSuccessfulBatchJobIsRecorded($command)\r\n /**\r\n * Ensure the lock for a unique job is released.\r\n *\r\n- * @param mixed $command\r\n+ * @param array $data\r\n * @return void\r\n */\r\n- protected function ensureUniqueJobLockIsReleased($command)\r\n+ protected function ensureUniqueJobLockIsReleased($data)\r\n {\r\n- if ($command instanceof ShouldBeUnique) {\r\n- (new UniqueLock($this->container->make(Cache::class)))->release($command);\r\n+ if (isset($data['uniqueId'])) {\r\n+ (new UniqueLock($this->container->make(Cache::class)))\r\n+ ->release($data['uniqueId']);\r\n }\r\n }\r\n \r\n@@ -246,7 +247,7 @@ public function failed(array $data, $e, string $uuid)\r\n $command = $this->getCommand($data);\r\n \r\n if (! $command instanceof ShouldBeUniqueUntilProcessing) {\r\n- $this->ensureUniqueJobLockIsReleased($command);\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n }\r\n \r\n if ($command instanceof \\__PHP_Incomplete_Class) {\r\ndiff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php\r\nindex 09eb245263..a87c81c5f3 100755\r\n--- a/src/Illuminate/Queue/Queue.php\r\n+++ b/src/Illuminate/Queue/Queue.php\r\n@@ -4,9 +4,12 @@\r\n \r\n use Closure;\r\n use DateTimeInterface;\r\n+use Illuminate\\Bus\\UniqueLock;\r\n use Illuminate\\Container\\Container;\r\n use Illuminate\\Contracts\\Encryption\\Encrypter;\r\n use Illuminate\\Contracts\\Queue\\ShouldBeEncrypted;\r\n+use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\r\n+use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\r\n use Illuminate\\Contracts\\Queue\\ShouldQueueAfterCommit;\r\n use Illuminate\\Queue\\Events\\JobQueued;\r\n use Illuminate\\Queue\\Events\\JobQueueing;\r\n@@ -150,6 +153,7 @@ protected function createObjectPayload($job, $queue)\r\n 'timeout' => $job->timeout ?? null,\r\n 'retryUntil' => $this->getJobExpiration($job),\r\n 'data' => [\r\n+ 'uniqueId' => $this->getJobUniqueId($job),\r\n 'commandName' => $job,\r\n 'command' => $job,\r\n ],\r\n@@ -167,6 +171,24 @@ protected function createObjectPayload($job, $queue)\r\n ]);\r\n }\r\n \r\n+ /**\r\n+ * Get the unique ID of the job\r\n+ *\r\n+ * @param object $job\r\n+ * @return string|null\r\n+ */\r\n+ protected function getJobUniqueId($job)\r\n+ {\r\n+ if (\r\n+ $job instanceof ShouldBeUnique ||\r\n+ $job instanceof ShouldBeUniqueUntilProcessing\r\n+ ) {\r\n+ return UniqueLock::getKey($job);\r\n+ }\r\n+\r\n+ return null;\r\n+ }\r\n+\r\n /**\r\n * Get the display name for the given job.\r\n *\r\n```\r\n\r\n*EDIT*: Patch changes.",
"created_at": "2024-01-30T13:27:09Z"
},
{
"body": "Scratch that. `uniqueVia` breaks in this implementation.",
"created_at": "2024-01-30T14:48:11Z"
},
{
"body": "Ok, I think I got it right. The idea is: to create a helper class to manage the lock based on the initial data. This way the `UniqueLock` ~~doesn't need to be changed at all~~, **UPDATE**: it needs a change to properly handle the job class name . Although, some duplicate code is present, but I don't think it's a big issue. The only thing that worries me is the reliance on the cache store name.\r\n\r\n\r\n```patch\r\ndiff --git a/src/Illuminate/Bus/UniqueLock.php b/src/Illuminate/Bus/UniqueLock.php\r\nindex a4066b77c1..c70a7b252a 100644\r\n--- a/src/Illuminate/Bus/UniqueLock.php\r\n+++ b/src/Illuminate/Bus/UniqueLock.php\r\n@@ -70,6 +70,10 @@ protected function getKey($job)\r\n ? $job->uniqueId()\r\n : ($job->uniqueId ?? '');\r\n \r\n- return 'laravel_unique_job:'.get_class($job).$uniqueId;\r\n+ $jobName = property_exists($job, 'jobName')\r\n+ ? $job->jobName\r\n+ : get_class($job);\r\n+\r\n+ return 'laravel_unique_job:'.$jobName.$uniqueId;\r\n }\r\n }\r\ndiff --git a/src/Illuminate/Queue/CallQueuedHandler.php b/src/Illuminate/Queue/CallQueuedHandler.php\r\nindex 5bee1d9ebb..f5d326e9e3 100644\r\n--- a/src/Illuminate/Queue/CallQueuedHandler.php\r\n+++ b/src/Illuminate/Queue/CallQueuedHandler.php\r\n@@ -4,13 +4,10 @@\r\n \r\n use Exception;\r\n use Illuminate\\Bus\\Batchable;\r\n-use Illuminate\\Bus\\UniqueLock;\r\n use Illuminate\\Contracts\\Bus\\Dispatcher;\r\n-use Illuminate\\Contracts\\Cache\\Repository as Cache;\r\n use Illuminate\\Contracts\\Container\\Container;\r\n use Illuminate\\Contracts\\Encryption\\Encrypter;\r\n use Illuminate\\Contracts\\Queue\\Job;\r\n-use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\r\n use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\r\n use Illuminate\\Database\\Eloquent\\ModelNotFoundException;\r\n use Illuminate\\Pipeline\\Pipeline;\r\n@@ -60,17 +57,18 @@ public function call(Job $job, array $data)\r\n $job, $this->getCommand($data)\r\n );\r\n } catch (ModelNotFoundException $e) {\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n return $this->handleModelNotFound($job, $e);\r\n }\r\n \r\n if ($command instanceof ShouldBeUniqueUntilProcessing) {\r\n- $this->ensureUniqueJobLockIsReleased($command);\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n }\r\n \r\n $this->dispatchThroughMiddleware($job, $command);\r\n \r\n if (! $job->isReleased() && ! $command instanceof ShouldBeUniqueUntilProcessing) {\r\n- $this->ensureUniqueJobLockIsReleased($command);\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n }\r\n \r\n if (! $job->hasFailed() && ! $job->isReleased()) {\r\n@@ -83,6 +81,29 @@ public function call(Job $job, array $data)\r\n }\r\n }\r\n \r\n+ /**\r\n+ * Get the unserialized object from the given payload.\r\n+ *\r\n+ * @param string $key\r\n+ * @param array $data\r\n+ * @return mixed\r\n+ */\r\n+ protected function getUnserializedItem(string $key, array $data)\r\n+ {\r\n+ if (isset($data[$key])) {\r\n+ if (str_starts_with($data[$key], 'O:')) {\r\n+ return unserialize($data[$key]);\r\n+ }\r\n+\r\n+ if ($this->container->bound(Encrypter::class)) {\r\n+ return unserialize($this->container[Encrypter::class]\r\n+ ->decrypt($data[$key]));\r\n+ }\r\n+ }\r\n+\r\n+ return null;\r\n+ }\r\n+\r\n /**\r\n * Get the command from the given payload.\r\n *\r\n@@ -93,17 +114,25 @@ public function call(Job $job, array $data)\r\n */\r\n protected function getCommand(array $data)\r\n {\r\n- if (str_starts_with($data['command'], 'O:')) {\r\n- return unserialize($data['command']);\r\n- }\r\n-\r\n- if ($this->container->bound(Encrypter::class)) {\r\n- return unserialize($this->container[Encrypter::class]->decrypt($data['command']));\r\n+ $command = $this->getUnserializedItem('command', $data);\r\n+ if ($command !== null) {\r\n+ return $command;\r\n }\r\n \r\n throw new RuntimeException('Unable to extract job payload.');\r\n }\r\n \r\n+ /**\r\n+ * Get the unique handler from the given payload.\r\n+ *\r\n+ * @param array $data\r\n+ * @return \\Illuminate\\Queue\\UniqueHandler|null\r\n+ */\r\n+ protected function getUniqueHandler(array $data)\r\n+ {\r\n+ return $this->getUnserializedItem('uniqueHandler', $data);\r\n+ }\r\n+\r\n /**\r\n * Dispatch the given job / command through its specified middleware.\r\n *\r\n@@ -196,13 +225,14 @@ protected function ensureSuccessfulBatchJobIsRecorded($command)\r\n /**\r\n * Ensure the lock for a unique job is released.\r\n *\r\n- * @param mixed $command\r\n+ * @param array $data\r\n * @return void\r\n */\r\n- protected function ensureUniqueJobLockIsReleased($command)\r\n+ protected function ensureUniqueJobLockIsReleased($data)\r\n {\r\n- if ($command instanceof ShouldBeUnique) {\r\n- (new UniqueLock($this->container->make(Cache::class)))->release($command);\r\n+ $handler = $this->getUniqueHandler($data);\r\n+ if ($handler !== null) {\r\n+ $handler->withContainer($this->container)->release();\r\n }\r\n }\r\n \r\n@@ -246,7 +276,7 @@ public function failed(array $data, $e, string $uuid)\r\n $command = $this->getCommand($data);\r\n \r\n if (! $command instanceof ShouldBeUniqueUntilProcessing) {\r\n- $this->ensureUniqueJobLockIsReleased($command);\r\n+ $this->ensureUniqueJobLockIsReleased($data);\r\n }\r\n \r\n if ($command instanceof \\__PHP_Incomplete_Class) {\r\ndiff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php\r\nindex 09eb245263..95cd2448ee 100755\r\n--- a/src/Illuminate/Queue/Queue.php\r\n+++ b/src/Illuminate/Queue/Queue.php\r\n@@ -139,6 +139,8 @@ protected function createPayloadArray($job, $queue, $data = '')\r\n */\r\n protected function createObjectPayload($job, $queue)\r\n {\r\n+ $handler = UniqueHandler::forJob($job);\r\n+\r\n $payload = $this->withCreatePayloadHooks($queue, [\r\n 'uuid' => (string) Str::uuid(),\r\n 'displayName' => $this->getDisplayName($job),\r\n@@ -150,17 +152,27 @@ protected function createObjectPayload($job, $queue)\r\n 'timeout' => $job->timeout ?? null,\r\n 'retryUntil' => $this->getJobExpiration($job),\r\n 'data' => [\r\n+ 'uniqueHandler' => $handler,\r\n 'commandName' => $job,\r\n 'command' => $job,\r\n ],\r\n ]);\r\n \r\n- $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class)\r\n- ? $this->container[Encrypter::class]->encrypt(serialize(clone $job))\r\n- : serialize(clone $job);\r\n+ $handler = serialize($handler);\r\n+ $command = serialize($job);\r\n+\r\n+ if (\r\n+ $this->jobShouldBeEncrypted($job) &&\r\n+ $this->container->bound(Encrypter::class)\r\n+ ) {\r\n+ $encrypter = $this->container[Encrypter::class];\r\n+ $handler = $encrypter->encrypt($handler);\r\n+ $command = $encrypter->encrypt($command);\r\n+ }\r\n \r\n return array_merge($payload, [\r\n 'data' => array_merge($payload['data'], [\r\n+ 'uniqueHandler' => $handler,\r\n 'commandName' => get_class($job),\r\n 'command' => $command,\r\n ]),\r\ndiff --git a/src/Illuminate/Queue/UniqueHandler.php b/src/Illuminate/Queue/UniqueHandler.php\r\nnew file mode 100644\r\nindex 0000000000..2ce7156677\r\n--- /dev/null\r\n+++ b/src/Illuminate/Queue/UniqueHandler.php\r\n@@ -0,0 +1,114 @@\r\n+<?php\r\n+\r\n+namespace Illuminate\\Queue;\r\n+\r\n+use Illuminate\\Bus\\UniqueLock;\r\n+use Illuminate\\Contracts\\Cache\\Factory as CacheFactory;\r\n+use Illuminate\\Contracts\\Container\\Container;\r\n+use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\r\n+use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\r\n+\r\n+/**\r\n+ * A helper class to manage the unique ID and cache instance for a job\r\n+ * base on the data of the job itself.\r\n+ */\r\n+class UniqueHandler\r\n+{\r\n+ /**\r\n+ * Original job name\r\n+ *\r\n+ * @var string\r\n+ */\r\n+ public $jobName;\r\n+\r\n+ /**\r\n+ * The unique ID for the job.\r\n+ *\r\n+ * @var string|null\r\n+ */\r\n+ public $uniqueId = null;\r\n+\r\n+ /**\r\n+ * Cache connection name for the job.\r\n+ *\r\n+ * @var string|null\r\n+ */\r\n+ protected $uniqueVia = null;\r\n+\r\n+ /**\r\n+ * The container instance.\r\n+ * @var \\Illuminate\\Contracts\\Container\\Container\r\n+ */\r\n+ protected $container;\r\n+\r\n+ /**\r\n+ * Create a new handler instance.\r\n+ *\r\n+ * @param object $job\r\n+ */\r\n+ public function __construct(object $job)\r\n+ {\r\n+ $this->jobName = get_class($job);\r\n+\r\n+ if (method_exists($job, 'uniqueId')) {\r\n+ $this->uniqueId = $job->uniqueId();\r\n+ } else if (isset($job->uniqueId)) {\r\n+ $this->uniqueId = $job->uniqueId;\r\n+ }\r\n+\r\n+ if (method_exists($job, 'uniqueVia')) {\r\n+ $this->uniqueVia = $job->uniqueVia()->getName();\r\n+ }\r\n+ }\r\n+\r\n+ /**\r\n+ * Creates a new instance if the job should be unique.\r\n+ *\r\n+ * @param object $job\r\n+ * @return \\Illuminate\\Queue\\UniqueHandler|null\r\n+ */\r\n+ public static function forJob(object $job)\r\n+ {\r\n+ if (\r\n+ $job instanceof ShouldBeUnique ||\r\n+ $job instanceof ShouldBeUniqueUntilProcessing\r\n+ ) {\r\n+ return new static($job);\r\n+ }\r\n+\r\n+ return null;\r\n+ }\r\n+\r\n+ /**\r\n+ * Sets the container instance.\r\n+ *\r\n+ * @param \\Illuminate\\Contracts\\Container\\Container $container\r\n+ * @return \\Illuminate\\Queue\\UpdateHandler\r\n+ */\r\n+ public function withContainer(Container $container)\r\n+ {\r\n+ $this->container = $container;\r\n+ return $this;\r\n+ }\r\n+\r\n+ /**\r\n+ * Returns the cache instance for the job.\r\n+ *\r\n+ * @return \\Illuminate\\Contracts\\Cache\\Repository\r\n+ */\r\n+ protected function getCacheStore()\r\n+ {\r\n+ return $this->container->make(CacheFactory::class)\r\n+ ->store($this->uniqueVia);\r\n+ }\r\n+\r\n+ /**\r\n+ * Releases the lock for the job.\r\n+ *\r\n+ * @return void\r\n+ */\r\n+ public function release()\r\n+ {\r\n+ (new UniqueLock($this->getCacheStore()))->release($this);\r\n+ }\r\n+}\r\n```\r\n\r\n**EDIT**: doc comments types updated.\r\n**EDIT 2**: pass the cache repository directly, skip the uniqueId method\r\n**EDIT 3**: encrypt the `UniqueHandler` instance as it potentially may leak the data from the job (the unique ID)\r\n**EDIT 4**: docstrings fix",
"created_at": "2024-01-30T15:26:46Z"
},
{
"body": "Hi @naquad, can you attempt that PR? Thanks!",
"created_at": "2024-02-20T08:42:40Z"
},
{
"body": "@driesvints I've sent a PR with the fix #50211. ",
"created_at": "2024-02-23T11:04:25Z"
},
{
"body": "I'm sorry @naquad but it seems that this is a no-fix for us right now. If you could produce a much simpler PR like Taylor requested, we'd love to review it. Thanks",
"created_at": "2024-05-07T15:33:14Z"
}
],
"number": 49890,
"title": "Inconsistent ShouldBeUnique behavior for missing models"
} | {
"body": "This PR is a follow-up on #49890 and tries to fix the issue by using a memo object that stores the information required to manage the unique lock (uniqueId and the name of the uniqueVia storage if present).\r\n\r\n**EDIT: A detailed explanation.**\r\n\r\nThe unique job lock mechanism relies on the attributes and methods of the job class. However, these methods are not necessarily deterministic. For example, they might produce different outcomes or errors when called on the same object, especially if dependent objects have changed or no longer exist.\r\n\r\nAdditionally, if the job incorporates the `Illuminate\\Queue\\SerializesModels` trait and fails to unserialize due to a missing model, the unserialization process is interrupted by an `Illuminate\\Database\\Eloquent\\ModelNotFoundException`.\r\n\r\nDue to these factors, it may become impossible to retrieve the necessary information for managing the unique lock in the queue worker.\r\n\r\nThis scenario creates a special case where the job's failure to unserialize prevents the worker from releasing the lock, potentially causing a complete deadlock for that particular job class.\r\n\r\nTo resolve this issue, this pull request introduces a memo object `Illuminate\\Queue\\UniqueHandler`. This object gathers all essential information from the job object beforehand, which can later be used to manage the unique lock w/o relying on the command instance. This approach effectively separates the job lock information from the job object itself and guarantees that both the dispatcher and the worker are working with the same unique lock.",
"number": 50211,
"review_comments": [],
"title": "[10.x] Fixes `ShouldBeUnique` behavior for missing models"
} | {
"commits": [
{
"message": "fix laravel/framework#49890: ShouldBeUnique behavior for missing models"
}
],
"files": [
{
"diff": "@@ -70,6 +70,10 @@ protected function getKey($job)\n ? $job->uniqueId()\n : ($job->uniqueId ?? '');\n \n- return 'laravel_unique_job:'.get_class($job).$uniqueId;\n+ $jobName = property_exists($job, 'jobName')\n+ ? $job->jobName\n+ : get_class($job);\n+\n+ return 'laravel_unique_job:'.$jobName.$uniqueId;\n }\n }",
"filename": "src/Illuminate/Bus/UniqueLock.php",
"status": "modified"
},
{
"diff": "@@ -4,13 +4,10 @@\n \n use Exception;\n use Illuminate\\Bus\\Batchable;\n-use Illuminate\\Bus\\UniqueLock;\n use Illuminate\\Contracts\\Bus\\Dispatcher;\n-use Illuminate\\Contracts\\Cache\\Repository as Cache;\n use Illuminate\\Contracts\\Container\\Container;\n use Illuminate\\Contracts\\Encryption\\Encrypter;\n use Illuminate\\Contracts\\Queue\\Job;\n-use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\n use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\n use Illuminate\\Database\\Eloquent\\ModelNotFoundException;\n use Illuminate\\Pipeline\\Pipeline;\n@@ -60,17 +57,19 @@ public function call(Job $job, array $data)\n $job, $this->getCommand($data)\n );\n } catch (ModelNotFoundException $e) {\n+ $this->ensureUniqueJobLockIsReleased($data);\n+\n return $this->handleModelNotFound($job, $e);\n }\n \n if ($command instanceof ShouldBeUniqueUntilProcessing) {\n- $this->ensureUniqueJobLockIsReleased($command);\n+ $this->ensureUniqueJobLockIsReleased($data);\n }\n \n $this->dispatchThroughMiddleware($job, $command);\n \n if (! $job->isReleased() && ! $command instanceof ShouldBeUniqueUntilProcessing) {\n- $this->ensureUniqueJobLockIsReleased($command);\n+ $this->ensureUniqueJobLockIsReleased($data);\n }\n \n if (! $job->hasFailed() && ! $job->isReleased()) {\n@@ -83,6 +82,32 @@ public function call(Job $job, array $data)\n }\n }\n \n+ /**\n+ * Get the unserialized object from the given payload.\n+ *\n+ * @param string $key\n+ * @param array $data\n+ * @return mixed\n+ */\n+ protected function getUnserializedItem(string $key, array $data)\n+ {\n+ if (isset($data[$key])) {\n+ if (\n+ str_starts_with($data[$key], 'O:') ||\n+ $data[$key] == 'N;'\n+ ) {\n+ return unserialize($data[$key]);\n+ }\n+\n+ if ($this->container->bound(Encrypter::class)) {\n+ return unserialize($this->container[Encrypter::class]\n+ ->decrypt($data[$key]));\n+ }\n+ }\n+\n+ return null;\n+ }\n+\n /**\n * Get the command from the given payload.\n *\n@@ -93,17 +118,25 @@ public function call(Job $job, array $data)\n */\n protected function getCommand(array $data)\n {\n- if (str_starts_with($data['command'], 'O:')) {\n- return unserialize($data['command']);\n- }\n-\n- if ($this->container->bound(Encrypter::class)) {\n- return unserialize($this->container[Encrypter::class]->decrypt($data['command']));\n+ $command = $this->getUnserializedItem('command', $data);\n+ if ($command !== null) {\n+ return $command;\n }\n \n throw new RuntimeException('Unable to extract job payload.');\n }\n \n+ /**\n+ * Get the unique handler from the given payload.\n+ *\n+ * @param array $data\n+ * @return \\Illuminate\\Queue\\UniqueHandler|null\n+ */\n+ protected function getUniqueHandler(array $data)\n+ {\n+ return $this->getUnserializedItem('uniqueHandler', $data);\n+ }\n+\n /**\n * Dispatch the given job / command through its specified middleware.\n *\n@@ -196,13 +229,14 @@ protected function ensureSuccessfulBatchJobIsRecorded($command)\n /**\n * Ensure the lock for a unique job is released.\n *\n- * @param mixed $command\n+ * @param array $data\n * @return void\n */\n- protected function ensureUniqueJobLockIsReleased($command)\n+ protected function ensureUniqueJobLockIsReleased($data)\n {\n- if ($command instanceof ShouldBeUnique) {\n- (new UniqueLock($this->container->make(Cache::class)))->release($command);\n+ $handler = $this->getUniqueHandler($data);\n+ if ($handler !== null) {\n+ $handler->withContainer($this->container)->release();\n }\n }\n \n@@ -246,7 +280,7 @@ public function failed(array $data, $e, string $uuid)\n $command = $this->getCommand($data);\n \n if (! $command instanceof ShouldBeUniqueUntilProcessing) {\n- $this->ensureUniqueJobLockIsReleased($command);\n+ $this->ensureUniqueJobLockIsReleased($data);\n }\n \n if ($command instanceof \\__PHP_Incomplete_Class) {",
"filename": "src/Illuminate/Queue/CallQueuedHandler.php",
"status": "modified"
},
{
"diff": "@@ -139,6 +139,8 @@ protected function createPayloadArray($job, $queue, $data = '')\n */\n protected function createObjectPayload($job, $queue)\n {\n+ $handler = UniqueHandler::forJob($job);\n+\n $payload = $this->withCreatePayloadHooks($queue, [\n 'uuid' => (string) Str::uuid(),\n 'displayName' => $this->getDisplayName($job),\n@@ -150,17 +152,27 @@ protected function createObjectPayload($job, $queue)\n 'timeout' => $job->timeout ?? null,\n 'retryUntil' => $this->getJobExpiration($job),\n 'data' => [\n+ 'uniqueHandler' => $handler,\n 'commandName' => $job,\n 'command' => $job,\n ],\n ]);\n \n- $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class)\n- ? $this->container[Encrypter::class]->encrypt(serialize(clone $job))\n- : serialize(clone $job);\n+ $handler = serialize($handler);\n+ $command = serialize($job);\n+\n+ if (\n+ $this->jobShouldBeEncrypted($job) &&\n+ $this->container->bound(Encrypter::class)\n+ ) {\n+ $encrypter = $this->container[Encrypter::class];\n+ $handler = $encrypter->encrypt($handler);\n+ $command = $encrypter->encrypt($command);\n+ }\n \n return array_merge($payload, [\n 'data' => array_merge($payload['data'], [\n+ 'uniqueHandler' => $handler,\n 'commandName' => get_class($job),\n 'command' => $command,\n ]),",
"filename": "src/Illuminate/Queue/Queue.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,116 @@\n+<?php\n+\n+namespace Illuminate\\Queue;\n+\n+use Illuminate\\Bus\\UniqueLock;\n+use Illuminate\\Contracts\\Cache\\Factory as CacheFactory;\n+use Illuminate\\Contracts\\Container\\Container;\n+use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\n+use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\n+\n+/**\n+ * A helper class to manage the unique ID and cache instance for a job\n+ * base on the data of the job itself.\n+ */\n+class UniqueHandler\n+{\n+ /**\n+ * Original job name.\n+ *\n+ * @var string\n+ */\n+ public $jobName;\n+\n+ /**\n+ * The unique ID for the job.\n+ *\n+ * @var string|null\n+ */\n+ public $uniqueId = null;\n+\n+ /**\n+ * Cache connection name for the job.\n+ *\n+ * @var string|null\n+ */\n+ protected $uniqueVia = null;\n+\n+ /**\n+ * The container instance.\n+ *\n+ * @var \\Illuminate\\Contracts\\Container\\Container\n+ */\n+ protected $container;\n+\n+ /**\n+ * Create a new handler instance.\n+ *\n+ * @param object $job\n+ */\n+ public function __construct(object $job)\n+ {\n+ $this->jobName = get_class($job);\n+\n+ if (method_exists($job, 'uniqueId')) {\n+ $this->uniqueId = $job->uniqueId();\n+ } elseif (isset($job->uniqueId)) {\n+ $this->uniqueId = $job->uniqueId;\n+ }\n+\n+ if (method_exists($job, 'uniqueVia')) {\n+ $this->uniqueVia = $job->uniqueVia()->getName();\n+ }\n+ }\n+\n+ /**\n+ * Creates a new instance if the job should be unique.\n+ *\n+ * @param object $job\n+ * @return \\Illuminate\\Queue\\UniqueHandler|null\n+ */\n+ public static function forJob(object $job)\n+ {\n+ if (\n+ $job instanceof ShouldBeUnique ||\n+ $job instanceof ShouldBeUniqueUntilProcessing\n+ ) {\n+ return new static($job);\n+ }\n+\n+ return null;\n+ }\n+\n+ /**\n+ * Sets the container instance.\n+ *\n+ * @param \\Illuminate\\Contracts\\Container\\Container $container\n+ * @return \\Illuminate\\Queue\\UpdateHandler\n+ */\n+ public function withContainer(Container $container)\n+ {\n+ $this->container = $container;\n+\n+ return $this;\n+ }\n+\n+ /**\n+ * Returns the cache instance for the job.\n+ *\n+ * @return \\Illuminate\\Contracts\\Cache\\Repository\n+ */\n+ protected function getCacheStore()\n+ {\n+ return $this->container->make(CacheFactory::class)\n+ ->store($this->uniqueVia);\n+ }\n+\n+ /**\n+ * Releases the lock for the job.\n+ *\n+ * @return void\n+ */\n+ public function release()\n+ {\n+ (new UniqueLock($this->getCacheStore()))->release($this);\n+ }\n+}",
"filename": "src/Illuminate/Queue/UniqueHandler.php",
"status": "added"
},
{
"diff": "@@ -8,6 +8,7 @@\n use Illuminate\\Contracts\\Queue\\ShouldBeUnique;\n use Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing;\n use Illuminate\\Contracts\\Queue\\ShouldQueue;\n+use Illuminate\\Database\\Eloquent\\ModelNotFoundException;\n use Illuminate\\Foundation\\Bus\\Dispatchable;\n use Illuminate\\Queue\\InteractsWithQueue;\n use Illuminate\\Support\\Facades\\Bus;\n@@ -129,6 +130,22 @@ public function testLockCanBeReleasedBeforeProcessing()\n $this->assertTrue($this->app->get(Cache::class)->lock($this->getLockKey($job), 10)->get());\n }\n \n+ public function testLockIsReleasedForJobsWithMissingModels()\n+ {\n+ $this->markTestSkippedWhenUsingSyncQueueDriver();\n+\n+ UniqueUntilStartTestJob::$handled = false;\n+\n+ dispatch($job = new UniqueWithModelMissing);\n+\n+ $this->assertFalse($this->app->get(Cache::class)->lock($this->getLockKey($job), 10)->get());\n+\n+ $this->runQueueWorkerCommand(['--once' => true]);\n+\n+ $this->assertFalse($job::$handled);\n+ $this->assertTrue($this->app->get(Cache::class)->lock($this->getLockKey($job), 10)->get());\n+ }\n+\n protected function getLockKey($job)\n {\n return 'laravel_unique_job:'.(is_string($job) ? $job : get_class($job));\n@@ -184,3 +201,13 @@ class UniqueUntilStartTestJob extends UniqueTestJob implements ShouldBeUniqueUnt\n {\n public $tries = 2;\n }\n+\n+class UniqueWithModelMissing extends UniqueTestJob implements ShouldQueue, ShouldBeUnique\n+{\n+ public $deleteWhenMissingModels = true;\n+\n+ public function __wakeup()\n+ {\n+ throw new ModelNotFoundException('test error');\n+ }\n+}",
"filename": "tests/Integration/Queue/UniqueJobTest.php",
"status": "modified"
}
]
} |
{
"body": "In case your model using HasOne, HasMany the query building needs additional\ncheck for foreign_key != null\n\nIf don't you will receive any related item having foreign_key = null on a new object.\nExample of wrong behaviour:\n\n$foo = new Foo();\n$foo->save();\n\n$bar = new Bar();\n$this_should_not_holding_any_relation = $bar->getFoos()->getResutls()->toArray()\n\nIn fact currenctly $bar->getFoos() finds any Foo() having foreign_key = null.\nSQL is \"where bar.id = foo.foreign_key\"\nwich is in fact \"null = null\" (any unrelated foo item)\n",
"comments": [
{
"body": "Is it the same as https://github.com/laravel/framework/issues/5649?\n",
"created_at": "2015-03-17T14:20:32Z"
},
{
"body": "@RomainLanz Yes, seems to be the same issue.\n",
"created_at": "2015-03-17T14:28:25Z"
},
{
"body": "Please fix the tests.\n",
"created_at": "2015-03-18T20:32:24Z"
},
{
"body": "Ping @pumatertion.\n",
"created_at": "2015-03-20T20:13:18Z"
},
{
"body": "I have no idea how to run the tests of vendor/laravel/framework/tests.\nmaybe you can give me some informations how to run them?\n",
"created_at": "2015-03-26T12:16:27Z"
},
{
"body": "> I have no idea how to run the tests of vendor/laravel/framework/tests.\n\nClone laravel/framework. Run composer install. Run phpunit.\n",
"created_at": "2015-03-26T12:51:30Z"
},
{
"body": "Running all tests of laravel in a base distibution created with \"laravel new foo\" needs to require mockable package and also needs directory added to phpunit.xml?\n",
"created_at": "2015-03-26T12:59:47Z"
},
{
"body": "You need to clone this repository (framework), and not the default Laravel repository.\n",
"created_at": "2015-03-26T13:05:29Z"
},
{
"body": "Specifically, you need to clone your fork.\n",
"created_at": "2015-03-26T13:07:32Z"
},
{
"body": "Sorry, have no idea what this mocking stuff has to do. All these magic __call stuff in the query building process also makes me really nuts. Its a black box for me what is happening everywhere. Quitting laravel with much frustration now i think.\n",
"created_at": "2015-03-26T13:53:10Z"
},
{
"body": "Not sure if I did this right, since I don't know anything about Mockery either, but try this: https://github.com/tremby/framework/commit/99b9772c65d54e86a3c78945e5c7f9ea91016ad6 -- tests now pass.\n\nNote that my original failing unit test https://github.com/laravel/framework/pull/5695 still fails (here's the same commit rebased on to current 5.0: https://github.com/tremby/framework/commit/f45444593003b05e15409cbcc1a89abfebefd3b4). See discussion in https://github.com/laravel/framework/issues/5649 about this.\n\nSo either this fix should be implemented at a lower level to make my test pass, or there should be a new passing test for this fix as it stands, as the project maintainers see fit.\n",
"created_at": "2015-03-26T20:00:22Z"
},
{
"body": "@tremby thanks for adjusting the tests. maybe you can investigate further?\n",
"created_at": "2015-03-26T22:51:33Z"
},
{
"body": "Afraid not. As I said over in the bug report #5649 I don't know how to either write a suitable test for your bugfix or to rewrite the bugfix to satisfy the test I did write. Hopefully the maintainers can provide some guidance.\n",
"created_at": "2015-03-26T22:57:55Z"
},
{
"body": "(Would have been nice if you'd used my actual commit, so my credits are in it, but I'll deal.)\n",
"created_at": "2015-03-26T22:58:49Z"
},
{
"body": "Ping @phurni\n",
"created_at": "2015-03-27T20:29:31Z"
}
],
"number": 8033,
"title": "[5.0] hasMany or hasOne neets to check for foreign_key != null"
} | {
"body": "## Description \r\nWhen an Eloquent model is instantiated (and not retrieved from the database), accessing `hasMany` or `hasOne` relations result in SQL generated that doesn't make any sense, due to the parent key being null ie;\r\n```\r\nselect * from `books` where `books`.`user_id` is null and `books`.`user_id` is not null\r\n```\r\nAs you can see because user_id is null, the query becomes `user_id is null and user_id is not null`. This PR changes this behavior so that the generated query becomes:\r\n```\r\nselect * from `books` where `books`.`user_id` is not null\r\n```\r\nwhich also from a logical perspective makes more sense than not returning any rows at all. \r\n\r\nIn addition to that, warnings are generated by this SQL, which you can see in an explain;\r\n```\r\nmysql> explain select * from books where books.user_id is null and books.user_id is not null;\r\n+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+------------------+\r\n| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |\r\n+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+------------------+\r\n| 1 | SIMPLE | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Impossible WHERE |\r\n+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+------------------+\r\n1 row in set, 1 warning (0.00 sec)\r\n```\r\nI think as a framework we should not be generating SQL that does not make sense and gives a warning.\r\n\r\n## Discussion\r\nLooking back through the PRs and issues I can see similar problems being referenced, but with different solutions.\r\nFor example #43948 which then references #8033\r\nAlso #36905 \r\nBut I want to stress that this PR is different, as it does not remove the `IS NULL` check, the focus is on removing the parent key check on freshly instantiated models. The behavior of models retrieved from the database is completely unchanged, which appears to be what those PRs are aiming to change.\r\n\r\nAlso, this is not a theoretical problem, a real world example I can give, and the reason why I stumbled across this issue in the first place, was because I noticed when using Filament I was unable to sort by a column that had a `->latestOfMany()`. After digging into it further I realized it's because the inner most query has this SQL which always returns no rows.\r\n\r\n## Examples\r\n```\r\n public function latestBook(): HasOne\r\n {\r\n return $this->hasOne(Book::class)->latestOfMany();\r\n }\r\n\r\n public function books(): HasMany\r\n {\r\n return $this->hasMany(Book::class);\r\n }\r\n```\r\nExample queries:\r\n```\r\n // no change in behavior because parent key is set\r\n $user = User::find(1);\r\n dd($user->books()->toRawSql());\r\n // select * from `books` where `books`.`user_id` = 1 and `books`.`user_id` is not null\r\n \r\n // previous behavior (returns 0 results, generates warning) \r\n $user = new User();\r\n dd($user->books()->toRawSql());\r\n // select * from `books` where `books`.`user_id` is null and `books`.`user_id` is not null\r\n\r\n // new behavior (returns all books where a user_id is set)\r\n $user = new User();\r\n dd($user->books()->toRawSql());\r\n // select * from `books` where `books`.`user_id` is not null\r\n \r\n // old behavior (returns no books, generates warning)\r\n $user = new User();\r\n dd(($user->latestBook())->toRawSql());\r\n // select `books`.* from `books` inner join (select MAX(`books`.`id`) as `id_aggregate`, `books`.`user_id` from `books` where `books`.`user_id` is null and `books`.`user_id` is not null group by `books`.`user_id`) as `latestOfMany` on `latestOfMany`.`id_aggregate` = `books`.`id` and `latestOfMany`.`user_id` = `books`.`user_id` where `books`.`user_id` is null and `books`.`user_id` is not null\r\n \r\n // new behavior (returns the latest book of all users, generates no warning, allows sorting of joined columns)\r\n $user = new User();\r\n dd(($user->latestBook())->toRawSql());\r\n // select `books`.* from `books` inner join (select MAX(`books`.`id`) as `id_aggregate`, `books`.`user_id` from `books` where `books`.`user_id` is not null group by `books`.`user_id`) as `latestOfMany` on `latestOfMany`.`id_aggregate` = `books`.`id` and `latestOfMany`.`user_id` = `books`.`user_id` where `books`.`user_id` is not null\r\n \r\n```\r\n\r\nIf we agree that this is more logical and desirable behavior, but we do not want to risk merging it into `10.x` would you be open to merging it into `11.x`? Thanks for your time.\r\n\r\nAlso, any extra eyes on this to be sure I am not overlooking something is appreciated. I think the overall impact should be low as this changes only newly instantiated models and does not modify behavior of existing models.",
"number": 50149,
"review_comments": [],
"title": "[10.x] Fix HasOneOrMany SQL bug when parent key not present"
} | {
"commits": [
{
"message": "only add where condition if parentKey is not null"
},
{
"message": "Merge branch 'laravel:10.x' into fix-hasoneormany-sql-bug"
}
],
"files": [
{
"diff": "@@ -82,8 +82,11 @@ public function addConstraints()\n {\n if (static::$constraints) {\n $query = $this->getRelationQuery();\n+ $parentKey = $this->getParentKey();\n \n- $query->where($this->foreignKey, '=', $this->getParentKey());\n+ if (! is_null($parentKey)) {\n+ $query->where($this->foreignKey, '=', $parentKey);\n+ }\n \n $query->whereNotNull($this->foreignKey);\n }",
"filename": "src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n11.x-dev\r\n\r\n### PHP Version\r\n\r\n8.3.2\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nThe changes in #49943 use PHP's pcntl extension. In [PHP's documentation](https://www.php.net/manual/en/pcntl.installation.php), it notes that `this module will not function on non-Unix platforms (Windows)`, so the extension isn't available on PHP run in Windows environments and would result in the following error.\r\n\r\n```\r\n[2024-02-09 06:00:37] local.ERROR: Undefined constant \"Illuminate\\Foundation\\Console\\SIGTERM\" {\"exception\":\"[object] (Error(code: 0): Undefined constant \\\"Illuminate\\\\Foundation\\\\Console\\\\SIGTERM\\\" at D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Foundation\\\\Console\\\\ServeCommand.php:143)\r\n[stacktrace]\r\n#0 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Foundation\\\\Console\\\\ServeCommand.php(90): Illuminate\\\\Foundation\\\\Console\\\\ServeCommand->startProcess(true)\r\n#1 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Container\\\\BoundMethod.php(36): Illuminate\\\\Foundation\\\\Console\\\\ServeCommand->handle()\r\n#2 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Container\\\\Util.php(41): Illuminate\\\\Container\\\\BoundMethod::Illuminate\\\\Container\\\\{closure}()\r\n#3 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Container\\\\BoundMethod.php(93): Illuminate\\\\Container\\\\Util::unwrapIfClosure(Object(Closure))\r\n#4 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Container\\\\BoundMethod.php(35): Illuminate\\\\Container\\\\BoundMethod::callBoundMethod(Object(Illuminate\\\\Foundation\\\\Application), Array, Object(Closure))\r\n#5 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Container\\\\Container.php(662): Illuminate\\\\Container\\\\BoundMethod::call(Object(Illuminate\\\\Foundation\\\\Application), Array, Array, NULL)\r\n#6 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Console\\\\Command.php(212): Illuminate\\\\Container\\\\Container->call(Array)\r\n#7 D:\\\\laravel\\\\vendor\\\\symfony\\\\console\\\\Command\\\\Command.php(279): Illuminate\\\\Console\\\\Command->execute(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Illuminate\\\\Console\\\\OutputStyle))\r\n#8 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Console\\\\Command.php(181): Symfony\\\\Component\\\\Console\\\\Command\\\\Command->run(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Illuminate\\\\Console\\\\OutputStyle))\r\n#9 D:\\\\laravel\\\\vendor\\\\symfony\\\\console\\\\Application.php(1049): Illuminate\\\\Console\\\\Command->run(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#10 D:\\\\laravel\\\\vendor\\\\symfony\\\\console\\\\Application.php(318): Symfony\\\\Component\\\\Console\\\\Application->doRunCommand(Object(Illuminate\\\\Foundation\\\\Console\\\\ServeCommand), Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#11 D:\\\\laravel\\\\vendor\\\\symfony\\\\console\\\\Application.php(169): Symfony\\\\Component\\\\Console\\\\Application->doRun(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#12 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Foundation\\\\Console\\\\Kernel.php(196): Symfony\\\\Component\\\\Console\\\\Application->run(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#13 D:\\\\laravel\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Foundation\\\\Application.php(1180): Illuminate\\\\Foundation\\\\Console\\\\Kernel->handle(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#14 D:\\\\laravel\\\\artisan(13): Illuminate\\\\Foundation\\\\Application->handleCommand(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput))\r\n#15 {main}\r\n\"} \r\n```\r\n\r\nShould the trap be wrapped in `if (!windows_os()) { ... }` or, if the issue was present on Windows, perhaps another solution to be investigated?\r\n\r\n### Steps To Reproduce\r\n\r\nRun `php artisan serve` on Windows on a Laravel version that includes the changes in #49943.",
"comments": [
{
"body": "Thanks. I've sent in a PR for this: https://github.com/laravel/framework/pull/50023",
"created_at": "2024-02-09T07:16:07Z"
},
{
"body": "I am also getting this error on Windows, installed it just now. Version in composer.lock file is dev-master. PHP 8.3.2\r\n\r\nError is this: `Undefined constant \"Illuminate\\Foundation\\Console\\SIGTERM\"` at `vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\ServeCommand.php:143`",
"created_at": "2024-02-11T20:35:58Z"
},
{
"body": "Yo estoy recibiendo este error, alguien conoce una solucion rápida: C:\\Users\\nuevo\\desktop\\main>php artisan serve\r\n\r\n Error \r\n\r\n Undefined constant \"Illuminate\\Foundation\\Console\\SIGTERM\"\r\n\r\n at C:\\Users\\nuevo\\Desktop\\main\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\ServeCommand.php:143 \r\n 139▕\r\n 140▕ return in_array($key, static::$passthroughVariables) ? [$key => $value] : [$key => false]; \r\n 141▕ })->all());\r\n 142▕\r\n ➜ 143▕ $this->trap([SIGTERM, SIGINT, SIGHUP, SIGUSR1, SIGUSR2, SIGQUIT], function ($signal) use ($process) {\r\n 144▕ if ($process->isRunning()) {\r\n 145▕ $process->stop(10, $signal);\r\n 146▕ }\r\n 147▕\r\n\r\n 1 C:\\Users\\nuevo\\Desktop\\main\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\ServeCommand.php:90\r\n Illuminate\\Foundation\\Console\\ServeCommand::startProcess()\r\n\r\n 2 C:\\Users\\nuevo\\Desktop\\main\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php:36\r\n Illuminate\\Foundation\\Console\\ServeCommand::handle()\r\n\r\n\r\nC:\\Users\\nuevo\\desktop\\main>",
"created_at": "2024-02-12T01:18:13Z"
}
],
"number": 50022,
"title": "Undefined constant \"Illuminate\\Foundation\\Console\\SIGTERM\""
} | {
"body": "fixes #50022\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 50024,
"review_comments": [],
"title": "[10.x] Allows to defer resolving pcntl only if it's available"
} | {
"commits": [
{
"message": "[10.x] Allows to defer resolving pcntl only if it's available\n\nfixes #50022\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip"
}
],
"files": [
{
"diff": "@@ -17,7 +17,9 @@ trait InteractsWithSignals\n /**\n * Define a callback to be run when the given signal(s) occurs.\n *\n- * @param iterable<array-key, int>|int $signals\n+ * @template TSignals of iterable<array-key, int>|int\n+ *\n+ * @param (\\Closure():(TSignals))|TSignals $signals\n * @param callable(int $signal): void $callback\n * @return void\n */\n@@ -28,7 +30,7 @@ public function trap($signals, $callback)\n $this->getApplication()->getSignalRegistry(),\n );\n \n- collect(Arr::wrap($signals))\n+ collect(Arr::wrap(value($signals)))\n ->each(fn ($signal) => $this->signals->register($signal, $callback));\n });\n }",
"filename": "src/Illuminate/Console/Concerns/InteractsWithSignals.php",
"status": "modified"
},
{
"diff": "@@ -140,7 +140,7 @@ protected function startProcess($hasEnvironment)\n return in_array($key, static::$passthroughVariables) ? [$key => $value] : [$key => false];\n })->all());\n \n- $this->trap([SIGTERM, SIGINT, SIGHUP, SIGUSR1, SIGUSR2, SIGQUIT], function ($signal) use ($process) {\n+ $this->trap(fn () => [SIGTERM, SIGINT, SIGHUP, SIGUSR1, SIGUSR2, SIGQUIT], function ($signal) use ($process) {\n if ($process->isRunning()) {\n $process->stop(10, $signal);\n }",
"filename": "src/Illuminate/Foundation/Console/ServeCommand.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.43.0\r\n\r\n### PHP Version\r\n\r\n8.1.0\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nThis [PR](https://github.com/laravel/framework/pull/49871) breaks the validation of the field if another field plus a temporal offset is specified.\r\n\r\n### Steps To Reproduce\r\n\r\n```php\r\n<?php\r\n\r\nrequire_once(__DIR__ . '/vendor/autoload.php');\r\n$app = require __DIR__.'/bootstrap/app.php';\r\n$app->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();\r\n\r\nuse Illuminate\\Support\\Facades\\Validator;\r\n\r\n$data = [\r\n 'dt1' => '2020-01-01',\r\n 'dt2' => '2024-01-01',\r\n];\r\n\r\n$val = Validator::make($data, [\r\n 'dt1' => 'required|date',\r\n 'dt2' => 'required|date|after:dt1 +1 day',\r\n]);\r\n\r\n/**\r\n * It works in Laravel 10.42.0\r\n * And throw exception \"The dt2 field must be a date after dt1+1 day.\" in Laravel 10.43.0\r\n */\r\n$val->validate();\r\n\r\n```\r\n\r\nDetails:\r\n\r\n```\r\nIlluminate\\Validation\\ValidationException \r\n\r\nThe dt2 field must be a date after dt1+1 day.\r\n\r\nat vendor/laravel/framework/src/Illuminate/Support/helpers.php:330\r\n 326▕ function throw_if($condition, $exception = 'RuntimeException', ...$parameters)\r\n 327▕ {\r\n 328▕ if ($condition) {\r\n 329▕ if (is_string($exception) && class_exists($exception)) {\r\n➜ 330▕ $exception = new $exception(...$parameters);\r\n 331▕ }\r\n 332▕ \r\n 333▕ throw is_string($exception) ? new RuntimeException($exception) : $exception;\r\n 334▕ }\r\n```",
"comments": [
{
"body": "https://github.com/laravel/framework/issues/49955",
"created_at": "2024-02-06T12:25:59Z"
},
{
"body": "> #49955\r\n\r\nThank you, I've seen that issue. It's related, but not quite the same.",
"created_at": "2024-02-06T12:30:42Z"
},
{
"body": "We've reverted the original PR. ",
"created_at": "2024-02-08T14:47:31Z"
}
],
"number": 49988,
"title": "Error in rule \"after\" date validation"
} | {
"body": "Fixes #49955 \r\nFixes #49988\r\n\r\nThis is an alternative to #49956\r\n\r\nIn Laravel v10.42.0, we can validate that a date is `after` or `before` another one, adding/subtracting a given amount of minutes, hours, seconds:\r\n\r\n```php\r\n$data = [\r\n 'dt1' => '2020-01-01',\r\n 'dt2' => '2024-01-01',\r\n];\r\n\r\nValidator::make($data, [\r\n 'dt1' => 'required|date',\r\n 'dt2' => 'required|date|after:dt1 +1 day', //dt +1day also works\r\n]);\r\n\r\n```\r\n\r\nPR #49871 broke this behavior and the nested after date validation.\r\n\r\nI tried to fix both issues without reverting the original PR. Also added tests to make sure after and before are working as expected now.",
"number": 49994,
"review_comments": [
{
"body": "Just explaining why `count() > 1` is enough here. We have the following options:\r\n\r\n### User validates using `after:date_field`\r\nThis is the most straight forward case. The `$dateAttributes` array contains only one item and we don't execute the if block.\r\n\r\n```php\r\n[\"date_field\"] // count = 1\r\n```\r\n\r\n### User validates `after:date_field +1day`\r\n\r\nNow, `$dateAttributes` contains this array:\r\n```php\r\n[\"date_field\", \"+1day\"] // count = 2\r\n```\r\n\r\n### User validates with `after:date_field +1 day`\r\nIn this scenario, `$dateAttributes` will be\r\n```php\r\n[\"date_field\", \"+1\", \"day\"] // count = 3\r\n```\r\n\r\n### User validates with `after:date_field + 1 day`\r\nHere, `$dateAttributes` contains\r\n```php\r\n[\"date_field\", \"+\", \"1\", \"day\"] // count = 4\r\n```\r\n\r\n",
"created_at": "2024-02-07T03:09:30Z"
}
],
"title": "[10.x] Fix date validation issues"
} | {
"commits": [
{
"message": "Fix before/after behavior"
},
{
"message": "Add tests"
},
{
"message": "Add tests"
},
{
"message": "Add tests"
}
],
"files": [
{
"diff": "@@ -253,9 +253,15 @@ protected function compareDates($attribute, $value, $parameters, $operator)\n }\n \n if (is_null($date = $this->getDateTimestamp($parameters[0]))) {\n+ $dateAttributes = explode(' ', $parameters[0]);\n $comparedValue = $this->getValue($parameters[0]);\n \n- if (! is_string($comparedValue) && ! is_numeric($comparedValue) && ! $comparedValue instanceof DateTimeInterface) {\n+ if (count($dateAttributes) > 1) {\n+ $key = array_shift($dateAttributes);\n+ $comparedValue = implode(' ', [$this->getValue($key), ...$dateAttributes]);\n+ }\n+\n+ if (! is_null($comparedValue) && ! is_string($comparedValue) && ! is_numeric($comparedValue) && ! $comparedValue instanceof DateTimeInterface) {\n return false;\n }\n ",
"filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php",
"status": "modified"
},
{
"diff": "@@ -5986,6 +5986,27 @@ public function testBeforeAndAfter()\n \n $v = new Validator($trans, ['x' => ['a' => ['v' => 'c']], 'y' => 'invalid'], ['x' => 'date', 'y' => 'date|before:x']);\n $this->assertTrue($v->fails());\n+\n+ $v = new Validator($trans, ['x' => '1970-01-01'], ['x' => 'nullable|date', 'y' => 'nullable|date|after:x']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['dates' => [['start_at' => '2024-02-02 12:00:00', 'ends_at' => '2024-02-02 12:00:00']]], ['dates.*.start_at' => 'date', 'dates.*.ends_at' => 'date|after:start_at']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_end' => '2021-09-17 13:28:47'], ['date_start' => 'nullable|date', 'date_end' => 'nullable|date|after_or_equal:date_start']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_end' => '2024-01-05 00:00:01', 'date_start' => '2024-01-04 00:00:00'], ['date_start' => 'date', 'date_end' => 'date|after:date_start +1 day']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_end' => '2024-01-05 00:00:01', 'date_start' => '2024-01-04 00:00:00'], ['date_start' => 'date', 'date_end' => 'date|after:date_start +1day']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_start' => '2024-01-04 00:00:00', 'date_end' => '2024-01-05 00:00:01'], ['date_start' => 'date|before:date_end -1 day', 'date_end' => 'date']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_start' => '2024-01-04 00:00:00', 'date_end' => '2024-01-05 00:00:01'], ['date_start' => 'date|before:date_end -1day', 'date_end' => 'date']);\n+ $this->assertTrue($v->passes());\n }\n \n public function testBeforeAndAfterWithFormat()",
"filename": "tests/Validation/ValidationValidatorTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.43.0\n\n### PHP Version\n\n8.3.1\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nThis [PR](https://github.com/laravel/framework/pull/49871) broke the nested date after validation which was working fine in 10.42.0.\n\n### Steps To Reproduce\n\n```php\r\n\r\nuse Illuminate\\Support\\Facades\\Validator;\r\n\r\n$validator = Validator::make(\r\n [\r\n \"dates\" => [\r\n [\r\n \"starts_at\" => \"2024-02-02 12:00:00\",\r\n \"ends_at\" => \"2024-02-02 14:00:00\"\r\n ]\r\n ]\r\n ],\r\n [\r\n \"dates.*.starts_at\" => [\"date\"],\r\n \"dates.*.ends_at\" => [\"date\", \"after:starts_at\"]\r\n ]\r\n);\r\n\r\ndd($validator->validate()); // This should just return the array of values but is now Illuminate\\Validation\\ValidationException: The dates.0.ends_at must be a date after starts at.\r\n```",
"comments": [
{
"body": "We have been having issues with this on 10.43.0 with non-nested fields, too. The below example works in 10.42.0 but not in 10.43.0\r\n\r\n```php\r\n'from_date' => [\r\n 'nullable',\r\n 'date',\r\n 'before_or_equal:to_date',\r\n],\r\n'to_date' => [\r\n 'required',\r\n 'date',\r\n 'after_or_equal:from_date',\r\n],\r\n``` ",
"created_at": "2024-02-02T13:52:37Z"
},
{
"body": "> We have been having issues with this on 10.43.0 with non-nested fields, too. The below example works in 10.42.0 but not in 10.43.0\r\n> \r\n> ```\r\n> 'from_date' => [\r\n> 'nullable',\r\n> 'date',\r\n> 'before_or_equal:to_date',\r\n> ],\r\n> 'to_date' => [\r\n> 'required',\r\n> 'date',\r\n> 'after_or_equal:from_date',\r\n> ],\r\n> ```\r\n\r\ncan you give me the case? \r\nbecause it works for me...",
"created_at": "2024-02-02T16:22:02Z"
},
{
"body": "We also had to revert to 10.42 because of the date validation issues that caused a test to fail in our Bitbucket pipeline.\r\n\r\n```\r\n$data = [\r\n 'date_end' => '2021-09-17 13:28:47',\r\n];\r\n```\r\n\r\n```php\r\npublic function rules()\r\n {\r\n return [\r\n 'date_start' => [\r\n 'nullable',\r\n 'date',\r\n ],\r\n 'date_end' => [\r\n 'nullable',\r\n 'date',\r\n 'after_or_equal:date_start',\r\n ],\r\n ];\r\n }\r\n```\r\nAnd we receive the following error:\r\n```\r\n{\r\n \"message\": \"Validation error\",\r\n \"errors\": {\r\n \"date_end\": [\r\n \"The date end must be a date after or equal to date start.\"\r\n ]\r\n }\r\n}\r\n```",
"created_at": "2024-02-02T18:45:05Z"
},
{
"body": "We've reverted the original PR. ",
"created_at": "2024-02-08T14:47:47Z"
}
],
"number": 49955,
"title": "[BUG] Nested after date validation is broken"
} | {
"body": "Fixes #49955 \r\nFixes #49988\r\n\r\nThis is an alternative to #49956\r\n\r\nIn Laravel v10.42.0, we can validate that a date is `after` or `before` another one, adding/subtracting a given amount of minutes, hours, seconds:\r\n\r\n```php\r\n$data = [\r\n 'dt1' => '2020-01-01',\r\n 'dt2' => '2024-01-01',\r\n];\r\n\r\nValidator::make($data, [\r\n 'dt1' => 'required|date',\r\n 'dt2' => 'required|date|after:dt1 +1 day', //dt +1day also works\r\n]);\r\n\r\n```\r\n\r\nPR #49871 broke this behavior and the nested after date validation.\r\n\r\nI tried to fix both issues without reverting the original PR. Also added tests to make sure after and before are working as expected now.",
"number": 49994,
"review_comments": [
{
"body": "Just explaining why `count() > 1` is enough here. We have the following options:\r\n\r\n### User validates using `after:date_field`\r\nThis is the most straight forward case. The `$dateAttributes` array contains only one item and we don't execute the if block.\r\n\r\n```php\r\n[\"date_field\"] // count = 1\r\n```\r\n\r\n### User validates `after:date_field +1day`\r\n\r\nNow, `$dateAttributes` contains this array:\r\n```php\r\n[\"date_field\", \"+1day\"] // count = 2\r\n```\r\n\r\n### User validates with `after:date_field +1 day`\r\nIn this scenario, `$dateAttributes` will be\r\n```php\r\n[\"date_field\", \"+1\", \"day\"] // count = 3\r\n```\r\n\r\n### User validates with `after:date_field + 1 day`\r\nHere, `$dateAttributes` contains\r\n```php\r\n[\"date_field\", \"+\", \"1\", \"day\"] // count = 4\r\n```\r\n\r\n",
"created_at": "2024-02-07T03:09:30Z"
}
],
"title": "[10.x] Fix date validation issues"
} | {
"commits": [
{
"message": "Fix before/after behavior"
},
{
"message": "Add tests"
},
{
"message": "Add tests"
},
{
"message": "Add tests"
}
],
"files": [
{
"diff": "@@ -253,9 +253,15 @@ protected function compareDates($attribute, $value, $parameters, $operator)\n }\n \n if (is_null($date = $this->getDateTimestamp($parameters[0]))) {\n+ $dateAttributes = explode(' ', $parameters[0]);\n $comparedValue = $this->getValue($parameters[0]);\n \n- if (! is_string($comparedValue) && ! is_numeric($comparedValue) && ! $comparedValue instanceof DateTimeInterface) {\n+ if (count($dateAttributes) > 1) {\n+ $key = array_shift($dateAttributes);\n+ $comparedValue = implode(' ', [$this->getValue($key), ...$dateAttributes]);\n+ }\n+\n+ if (! is_null($comparedValue) && ! is_string($comparedValue) && ! is_numeric($comparedValue) && ! $comparedValue instanceof DateTimeInterface) {\n return false;\n }\n ",
"filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php",
"status": "modified"
},
{
"diff": "@@ -5986,6 +5986,27 @@ public function testBeforeAndAfter()\n \n $v = new Validator($trans, ['x' => ['a' => ['v' => 'c']], 'y' => 'invalid'], ['x' => 'date', 'y' => 'date|before:x']);\n $this->assertTrue($v->fails());\n+\n+ $v = new Validator($trans, ['x' => '1970-01-01'], ['x' => 'nullable|date', 'y' => 'nullable|date|after:x']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['dates' => [['start_at' => '2024-02-02 12:00:00', 'ends_at' => '2024-02-02 12:00:00']]], ['dates.*.start_at' => 'date', 'dates.*.ends_at' => 'date|after:start_at']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_end' => '2021-09-17 13:28:47'], ['date_start' => 'nullable|date', 'date_end' => 'nullable|date|after_or_equal:date_start']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_end' => '2024-01-05 00:00:01', 'date_start' => '2024-01-04 00:00:00'], ['date_start' => 'date', 'date_end' => 'date|after:date_start +1 day']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_end' => '2024-01-05 00:00:01', 'date_start' => '2024-01-04 00:00:00'], ['date_start' => 'date', 'date_end' => 'date|after:date_start +1day']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_start' => '2024-01-04 00:00:00', 'date_end' => '2024-01-05 00:00:01'], ['date_start' => 'date|before:date_end -1 day', 'date_end' => 'date']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['date_start' => '2024-01-04 00:00:00', 'date_end' => '2024-01-05 00:00:01'], ['date_start' => 'date|before:date_end -1day', 'date_end' => 'date']);\n+ $this->assertTrue($v->passes());\n }\n \n public function testBeforeAndAfterWithFormat()",
"filename": "tests/Validation/ValidationValidatorTest.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "Related with https://github.com/laravel/framework/pull/49895\r\n\r\n```\r\n[2024-02-01T13:24:01+01:00] production.ERROR: fopen(/app/storage/framework/cache/data/e7/da/e7da1512baf3c3cf089e9ae9a65970e0b433ec82): Failed to open stream: No such file or directory {\"exception\":\"[object] (ErrorException(code: 0): fopen(/app/storage/framework/cache/data/e7/da/e7da1512baf3c3cf089e9ae9a65970e0b433ec82): Failed to open stream: No such file or directory at /app/vendor/laravel/framework/src/Illuminate/Filesystem/LockableFile.php:69)\r\n[stacktrace]\r\n#0 /app/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(255): Illuminate\\\\Foundation\\\\Bootstrap\\\\HandleExceptions->handleError(2, 'fopen(/app/stor...', '/app/vendor/lar...', 69)\r\n#1 [internal function]: Illuminate\\\\Foundation\\\\Bootstrap\\\\HandleExceptions->Illuminate\\\\Foundation\\\\Bootstrap\\\\{closure}(2, 'fopen(/app/stor...', '/app/vendor/lar...', 69)\r\n#2 /app/vendor/laravel/framework/src/Illuminate/Filesystem/LockableFile.php(69): fopen('/app/storage/fr...', 'c+')\r\n#3 /app/vendor/laravel/framework/src/Illuminate/Filesystem/LockableFile.php(42): Illuminate\\\\Filesystem\\\\LockableFile->createResource('/app/storage/fr...', 'c+')\r\n#4 /app/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php(108): Illuminate\\\\Filesystem\\\\LockableFile->__construct('/app/storage/fr...', 'c+')\r\n#5 /app/vendor/laravel/framework/src/Illuminate/Cache/FileLock.php(14): Illuminate\\\\Cache\\\\FileStore->add('framework/sched...', 'SuAnmpSzBTNlmTR...', 5.5340232221129E+20)\r\n#6 /app/vendor/laravel/framework/src/Illuminate/Cache/Lock.php(91): Illuminate\\\\Cache\\\\FileLock->acquire()\r\n#7 /app/vendor/laravel/framework/src/Illuminate/Console/Scheduling/CacheEventMutex.php(66): Illuminate\\\\Cache\\\\Lock->get(Object(Closure))\r\n#8 /app/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Event.php(713): Illuminate\\\\Console\\\\Scheduling\\\\CacheEventMutex->exists(Object(Illuminate\\\\Console\\\\Scheduling\\\\Event))\r\n#9 /app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\\\Console\\\\Scheduling\\\\Event->Illuminate\\\\Console\\\\Scheduling\\\\{closure}()\r\n#10 /app/vendor/laravel/framework/src/Illuminate/Container/Util.php(41): Illuminate\\\\Container\\\\BoundMethod::Illuminate\\\\Container\\\\{closure}()\r\n#11 /app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(81): Illuminate\\\\Container\\\\Util::unwrapIfClosure(Object(Closure))\r\n#12 /app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\\\\Container\\\\BoundMethod::callBoundMethod(Object(Illuminate\\\\Foundation\\\\Application), Object(Closure), Object(Closure))\r\n#13 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(662): Illuminate\\\\Container\\\\BoundMethod::call(Object(Illuminate\\\\Foundation\\\\Application), Object(Closure), Array, NULL)\r\n#14 /app/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Event.php(419): Illuminate\\\\Container\\\\Container->call(Object(Closure))\r\n#15 /app/vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php(122): Illuminate\\\\Console\\\\Scheduling\\\\Event->filtersPass(Object(Illuminate\\\\Foundation\\\\Application))\r\n#16 /app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\\\Console\\\\Scheduling\\\\ScheduleRunCommand->handle(Object(Illuminate\\\\Console\\\\Scheduling\\\\Schedule), Object(Illuminate\\\\Events\\\\Dispatcher), Object(Illuminate\\\\Cache\\\\Repository), Object(App\\\\Exceptions\\\\Handler))\r\n#17 /app/vendor/laravel/framework/src/Illuminate/Container/Util.php(41): Illuminate\\\\Container\\\\BoundMethod::Illuminate\\\\Container\\\\{closure}()\r\n#18 /app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\\\Container\\\\Util::unwrapIfClosure(Object(Closure))\r\n#19 /app/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\\\\Container\\\\BoundMethod::callBoundMethod(Object(Illuminate\\\\Foundation\\\\Application), Array, Object(Closure))\r\n#20 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(662): Illuminate\\\\Container\\\\BoundMethod::call(Object(Illuminate\\\\Foundation\\\\Application), Array, Array, NULL)\r\n#21 /app/vendor/laravel/framework/src/Illuminate/Console/Command.php(211): Illuminate\\\\Container\\\\Container->call(Array)\r\n#22 /app/vendor/symfony/console/Command/Command.php(326): Illuminate\\\\Console\\\\Command->execute(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Illuminate\\\\Console\\\\OutputStyle))\r\n#23 /app/vendor/laravel/framework/src/Illuminate/Console/Command.php(180): Symfony\\\\Component\\\\Console\\\\Command\\\\Command->run(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Illuminate\\\\Console\\\\OutputStyle))\r\n#24 /app/vendor/symfony/console/Application.php(1096): Illuminate\\\\Console\\\\Command->run(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#25 /app/vendor/symfony/console/Application.php(324): Symfony\\\\Component\\\\Console\\\\Application->doRunCommand(Object(Illuminate\\\\Console\\\\Scheduling\\\\ScheduleRunCommand), Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#26 /app/vendor/symfony/console/Application.php(175): Symfony\\\\Component\\\\Console\\\\Application->doRun(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#27 /app/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(201): Symfony\\\\Component\\\\Console\\\\Application->run(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#28 /app/artisan(35): Illuminate\\\\Foundation\\\\Console\\\\Kernel->handle(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#29 {main}\r\n\"} \r\n```\r\n\r\nOnce the native file creation error is available, you may discover that the directory that should exist, does not exist.\r\n\r\nBy removing the error suppression on file creation we can drill down into the error.\r\n\r\nThe directory creation where the file is hosted should return an error in case of any problems, or the file cannot be created in the next step.\r\n\r\nBy checking the error at this point you will be able to find out what is the cause of not being able to create the lock file.",
"number": 49942,
"review_comments": [],
"title": "[10.x] Using the native mkdir exception in LockableFile.php"
} | {
"commits": [
{
"message": "[10.x] Using the native mkdir exception in LockableFile.php"
},
{
"message": "Fixed LockableFile.php code style"
}
],
"files": [
{
"diff": "@@ -47,11 +47,17 @@ public function __construct($path, $mode)\n *\n * @param string $path\n * @return void\n+ *\n+ * @throws \\Exception\n */\n protected function ensureDirectoryExists($path)\n {\n- if (! file_exists(dirname($path))) {\n- @mkdir(dirname($path), 0777, true);\n+ $dir = dirname($path);\n+\n+ clearstatcache(true, $dir);\n+\n+ if (! is_dir($dir)) {\n+ mkdir($dir, 0777, true);\n }\n }\n ",
"filename": "src/Illuminate/Filesystem/LockableFile.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.10\r\n\r\n### PHP Version\r\n\r\n8.2.14\r\n\r\n### Database Driver & Version\r\n\r\nPostgreSQL 15.1 (Ubuntu 15.1-1.pgdg20.04+1)\r\n\r\n### Description\r\n\r\nA `ManyToMany` relationship in which one or more parties casts the id column to an `Enum` will cause `Illuminate\\Database\\Query\\Builder::whereIntegerInRaw()` to throw an `ErrorException` because it tries to cast the (already cast to an enum) id on the model to an `int`. However, `Enum`s are NOT castable in PHP (I tried php 8.1 up to 8.3).\r\n\r\n### Steps To Reproduce\r\n\r\n[A minimal reproducible example is available here](https://github.com/sidquisaad/query-builder-mre).\r\n\r\nIn the MRE repo are three models: `User`, `Role`, and a pivot `RoleUser`.\r\nA regular `ManyToMany` relationship is defined between `User` and `Role` through the `RoleUser` pivot.\r\n`Role`'s `id` column is an integer column that is cast to the backed enum `App\\Enum\\Roles`.\r\nSimilarly, inside the pivot `RoleUser`, `role_id` is also cast to the same enum.\r\n\r\nWith this setup, running the following query `Role::with('users')->get();` throws an `ErrorException` with the message \"Object of class App\\Enums\\Roles could not be converted to int\", in `Illuminate\\Database\\Query\\Builder::whereIntegerInRaw()`, line 1164.\r\n\r\n**EDIT:**\r\nThe fact that the concerned column is autoincrement or not has no incidence on the issue. I have updated various sections of this issue to reflect this.",
"comments": [
{
"body": "Hey there, thanks for reporting this issue.\r\n\r\nWe'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue *as one separate commit* on the main/master branch and share the repository here?\r\n\r\nPlease make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com/) properly set up.\r\n\r\n laravel new bug-report --github=\"--public\"\r\n\r\nDo not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.\r\n\r\nThanks!",
"created_at": "2024-01-18T22:38:53Z"
},
{
"body": "Sorry for the delay. I'm unfortunately unable to use `laravel/installer` right now. I will update this later if I get into an environment where I can use it.\r\n\r\nIn the meantime, I did my best to revamp the minimum reproducible example I had already provided so that things are better separated. I have also updated the description of this issue so that it is more in line with the MRE repo. After checking out the proper commits (see below), all that is needed is a `php artisan migrate:fresh --seed` and `php artisan serve`.\r\n\r\n1. For the original issue reported, [please see commit c100f25](https://github.com/sidquisaad/query-builder-mre/commit/c100f255f8bf0ee994a971f045a7ea94b9c7dd28)\r\n2. For a second, seemingly related issue (described below), [Please see this commit f4d03ff](https://github.com/sidquisaad/query-builder-mre/commit/f4d03ffd297a64cbca4c056fb0696c48611be305)\r\n\r\nIn both cases, for a quick start, please look at `app/Http/Controllers/TestController.php`.\r\n\r\n## The first issue\r\nIn the MRE repo are three models: `User`, `Role`, and a pivot `RoleUser`.\r\nA regular `ManyToMany` relationship is defined between `User` and `Role` through the `RoleUser` pivot.\r\n`Role`'s `id` column is an integer column that is cast to the backed enum `App\\Enum\\Roles`.\r\nSimilarly, inside the pivot `RoleUser`, `role_id` is also cast to the same enum.\r\n\r\nWith this setup, running the following query `Role::with('users')->get();` throws an `ErrorException` with the message \"Object of class App\\Enums\\Roles could not be converted to int\", in `Illuminate\\Database\\Query\\Builder::whereIntegerInRaw()`, line 1164.\r\n\r\n## The second issue\r\nIn the MRE repo, the model `Permission` has a `BelongsTo` relationship to the model `Role`.\r\n`Role`'s `id` column is an integer column that is cast to the backed enum `App\\Enum\\Roles`.\r\nSimilarly, inside `Permission`, `role_id` is also cast to the same enum.\r\n\r\nWith this setup, running the following query `Permission::with('role')->get();` throws an `Error` with the message \"Object of class App\\Enums\\Roles could not be converted to string\", in `Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::getEagerModelKeys()`, line 140.\r\n\r\nIt's notable that removing the cast for `role_id` inside `Permission` makes the exception go away.",
"created_at": "2024-01-21T06:50:01Z"
},
{
"body": "Thanks for your report! We'd love to see a PR for this.",
"created_at": "2024-01-22T10:02:46Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2024-01-22T10:03:02Z"
},
{
"body": "Hello,\r\n\r\nI submitted PR #49787 . The PR description describes what it fixes.\r\n\r\nThis PR should fix the two issues at hand; BUT, I have suspicions that there are more places where BackedEnums are not properly handled. I have tried to find some more in the couple of hours I had to familiarize myself with the code. One that stood out to me is [`getRelatedKeyFrom`](https://github.com/laravel/framework/blob/d7616a176afc641e9693266920cb11e84c352241/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php#L365C24-L365C41), which seems to me should also check if the retrieved key has been cast to a `BackedEnum` to return the proper value, however, I'm not completely sure. Your input would be appreciated.\r\n\r\nIn general, my familiarity with the code is pretty limited. I would very much like to contribute some more, so any pointers on the following are very much appreciated :\r\n\r\n- How would one go about finding other instances of `BackedEnum` casts being mishandled?\r\n- If any other tests/changes should have been included in the PR.\r\n- How do you usually go about porting these changes to the next version of Laravel so they're not lost ?\r\n\r\nThank you.",
"created_at": "2024-01-23T02:40:50Z"
},
{
"body": "@sidquisaad I'd approach this with waiting until someone asks for support for other portions of the framework.",
"created_at": "2024-01-23T07:58:39Z"
},
{
"body": "We merged the PR for this one. Will be tagged today.",
"created_at": "2024-04-16T07:57:48Z"
}
],
"number": 49735,
"title": "Query Builder fails on a ManyToMany relationship that has a model with an ID that is cast to an Enum"
} | {
"body": "This PR fixes a couple of issues discussed in #49735 .\r\n\r\nAppropriate checks are added to `Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::getForeignKeyFrom()` and `Illuminate\\Database\\Query\\Builder::whereIntegerInRaw()` to return the proper value if a `BackedEnum` is encountered. This is typically the case on models where a cast has been defined, especially on keys.\r\n\r\nI have also added a couple of tests to cover these cases where it seemed appropriate.\r\n\r\nThere might be other similar cases. Please see [this comment](https://github.com/laravel/framework/issues/49735#issuecomment-1905192054).",
"number": 49787,
"review_comments": [],
"title": "[10.x] Database layer fixes"
} | {
"commits": [
{
"message": "- Illuminate\\Database\\Query::whereIntegerInRaw() now properly handles BackedEnums\n- Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::getForeignKeyFrom() handles BackedEnums properly\n\nSee #49735"
}
],
"files": [
{
"diff": "@@ -2,6 +2,7 @@\n \n namespace Illuminate\\Database\\Eloquent\\Relations;\n \n+use BackedEnum;\n use Illuminate\\Database\\Eloquent\\Builder;\n use Illuminate\\Database\\Eloquent\\Collection;\n use Illuminate\\Database\\Eloquent\\Model;\n@@ -375,7 +376,9 @@ protected function getRelatedKeyFrom(Model $model)\n */\n protected function getForeignKeyFrom(Model $model)\n {\n- return $model->{$this->foreignKey};\n+ $foreignKey = $model->{$this->foreignKey};\n+\n+ return $foreignKey instanceof BackedEnum ? $foreignKey->value : $foreignKey;\n }\n \n /**",
"filename": "src/Illuminate/Database/Eloquent/Relations/BelongsTo.php",
"status": "modified"
},
{
"diff": "@@ -1161,7 +1161,7 @@ public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = fal\n $values = Arr::flatten($values);\n \n foreach ($values as &$value) {\n- $value = (int) $value;\n+ $value = (int) ($value instanceof BackedEnum ? $value->value : $value);\n }\n \n $this->wheres[] = compact('type', 'column', 'values', 'boolean');",
"filename": "src/Illuminate/Database/Query/Builder.php",
"status": "modified"
},
{
"diff": "@@ -6,6 +6,7 @@\n use Illuminate\\Database\\Eloquent\\Collection;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Relations\\BelongsTo;\n+use Illuminate\\Tests\\Database\\Fixtures\\Enums\\Bar;\n use Mockery as m;\n use PHPUnit\\Framework\\TestCase;\n \n@@ -85,6 +86,16 @@ public function testIdsInEagerConstraintsCanBeZero()\n $relation->addEagerConstraints($models);\n }\n \n+ public function testIdsInEagerConstraintsCanBeBackedEnum()\n+ {\n+ $relation = $this->getRelation();\n+ $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id');\n+ $relation->getRelated()->shouldReceive('getKeyType')->andReturn('int');\n+ $relation->getQuery()->shouldReceive('whereIntegerInRaw')->once()->with('relation.id', [5, 'foreign.value']);\n+ $models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStubWithBackedEnumCast];\n+ $relation->addEagerConstraints($models);\n+ }\n+\n public function testRelationIsProperlyInitialized()\n {\n $relation = $this->getRelation();\n@@ -119,6 +130,15 @@ public function __toString()\n }\n };\n \n+ $result4 = new class extends Model\n+ {\n+ protected $casts = [\n+ 'id' => Bar::class,\n+ ];\n+\n+ protected $attributes = ['id' => 5];\n+ };\n+\n $model1 = new EloquentBelongsToModelStub;\n $model1->foreign_key = 1;\n $model2 = new EloquentBelongsToModelStub;\n@@ -131,11 +151,18 @@ public function __toString()\n return '3';\n }\n };\n- $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2, $result3]), 'foo');\n+ $model4 = new EloquentBelongsToModelStub;\n+ $model4->foreign_key = 5;\n+ $models = $relation->match(\n+ [$model1, $model2, $model3, $model4],\n+ new Collection([$result1, $result2, $result3, $result4]),\n+ 'foo'\n+ );\n \n $this->assertEquals(1, $models[0]->foo->getAttribute('id'));\n $this->assertEquals(2, $models[1]->foo->getAttribute('id'));\n $this->assertSame('3', (string) $models[2]->foo->getAttribute('id'));\n+ $this->assertEquals(5, $models[3]->foo->getAttribute('id')->value);\n }\n \n public function testAssociateMethodSetsForeignKeyOnModel()\n@@ -403,3 +430,14 @@ class MissingEloquentBelongsToModelStub extends Model\n {\n public $foreign_key;\n }\n+\n+class EloquentBelongsToModelStubWithBackedEnumCast extends Model\n+{\n+ protected $casts = [\n+ 'foreign_key' => Bar::class,\n+ ];\n+\n+ public $attributes = [\n+ 'foreign_key' => 5,\n+ ];\n+}",
"filename": "tests/Database/DatabaseEloquentBelongsToTest.php",
"status": "modified"
},
{
"diff": "@@ -23,6 +23,7 @@\n use Illuminate\\Pagination\\Cursor;\n use Illuminate\\Pagination\\CursorPaginator;\n use Illuminate\\Pagination\\LengthAwarePaginator;\n+use Illuminate\\Tests\\Database\\Fixtures\\Enums\\Bar;\n use InvalidArgumentException;\n use Mockery as m;\n use PHPUnit\\Framework\\TestCase;\n@@ -1039,17 +1040,20 @@ public function testEmptyWhereNotIns()\n public function testWhereIntegerInRaw()\n {\n $builder = $this->getBuilder();\n- $builder->select('*')->from('users')->whereIntegerInRaw('id', ['1a', 2]);\n- $this->assertSame('select * from \"users\" where \"id\" in (1, 2)', $builder->toSql());\n+ $builder->select('*')->from('users')->whereIntegerInRaw('id', [\n+ '1a', 2, Bar::FOO,\n+ ]);\n+ $this->assertSame('select * from \"users\" where \"id\" in (1, 2, 5)', $builder->toSql());\n $this->assertEquals([], $builder->getBindings());\n \n $builder = $this->getBuilder();\n $builder->select('*')->from('users')->whereIntegerInRaw('id', [\n ['id' => '1a'],\n ['id' => 2],\n ['any' => '3'],\n+ ['id' => Bar::FOO],\n ]);\n- $this->assertSame('select * from \"users\" where \"id\" in (1, 2, 3)', $builder->toSql());\n+ $this->assertSame('select * from \"users\" where \"id\" in (1, 2, 3, 5)', $builder->toSql());\n $this->assertEquals([], $builder->getBindings());\n }\n ",
"filename": "tests/Database/DatabaseQueryBuilderTest.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,8 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Database\\Fixtures\\Enums;\n+\n+enum Bar: int\n+{\n+ case FOO = 5;\n+}",
"filename": "tests/Database/Fixtures/Enums/Bar.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\n\n10.41.0\n\n### PHP Version\n\n8.1.23\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\n- https://github.com/illuminate/collections/blob/master/LazyCollection.php#L1742\r\n- https://github.com/laravel/framework/blob/37eea841d5955ed3902d8660d84c15da400755f1/src/Illuminate/Collections/LazyCollection.php#L1743\r\n\r\nCarbon is not a dependency of `illuminate/collections` (and should not be), it should not call `Carbon::now()`.\r\n\r\nThis was changed/broken by https://github.com/laravel/framework/pull/47200\n\n### Steps To Reproduce\n\nIn a project which only has `illuminate/collections` v10.41.0 or later:\r\n\r\n```php\r\n> (new \\Illuminate\\Support\\LazyCollection)->takeUntilTimeout(new DateTime)->all()\r\n\r\n Error Class \"Illuminate\\Support\\Carbon\" not found.\r\n```",
"comments": [],
"number": 49765,
"title": "LazyCollection calls Carbon, does not exist in `illuminate/collections` subtree split"
} | {
"body": "fixes #49765\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 49772,
"review_comments": [],
"title": "[10.x] Only use `Carbon` if accessed from Laravel or also uses `illuminate/support`"
} | {
"commits": [
{
"message": "[10.x] Only use `Carbon` if accessed from Laravel or also uses\n`illuminate/support`\n\nfixes #49765\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
}
],
"files": [
{
"diff": "@@ -1740,6 +1740,8 @@ protected function passthru($method, array $params)\n */\n protected function now()\n {\n- return Carbon::now()->timestamp;\n+ return class_exists(Carbon::class)\n+ ? Carbon::now()->timestamp\n+ : time();\n }\n }",
"filename": "src/Illuminate/Collections/LazyCollection.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.37.3\n\n### PHP Version\n\n8.2.7\n\n### Database Driver & Version\n\nMariaDB 10.3.27\n\n### Description\n\nWe had a 'phantom' problem that jobs that failed, were not logged to the failed_jobs table. After some investigation we found out that by mistake we were doing a heavy process within a db transaction which lead the specific job to timeout.\r\n\r\nAfter testing we found out that the issue only happens if the jobs timeout during an open db transaction\r\n\r\nI reported this in laravel/horizon but it turns out it has nothing to do with horizon but seems to be a framework issue.\n\n### Steps To Reproduce\n\n- Create a job with a timeout of 5 seconds\r\n- In the job handle method sleep within a db transaction\r\n\r\n```\r\n public function handle(): void\r\n {\r\n DB::transaction(function (): void {\r\n sleep(10);\r\n });\r\n }\r\n```\r\n\r\nWe would expect a job in the failed_jobs table, however this is not the case, and the JobFailed event is also not dispatched",
"comments": [
{
"body": "HI there,\r\n\r\nI added the following tests to verify the issue and was unable to replicate the problem, `jobs` and `failed_jobs` updated properly. We need to be able to replicate the issue in order to solve the problem.\r\n",
"created_at": "2023-12-19T06:40:15Z"
},
{
"body": "Hey there, thanks for reporting this issue.\r\n\r\nWe'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue *as one separate commit* on the main/master branch and share the repository here?\r\n\r\nPlease make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com/) properly set up.\r\n\r\n laravel new bug-report --github=\"--public\"\r\n\r\nDo not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.\r\n\r\nThanks!",
"created_at": "2023-12-19T06:40:27Z"
},
{
"body": "@crynobone Thank you for the time invested.\r\n\r\nWe'll as a next step try and reproduce this in a fresh laravel project to rule out the fact that this has something to do with our environment and get back to you asap.",
"created_at": "2023-12-19T08:15:31Z"
},
{
"body": "@crynobone \r\n\r\nWe have successfully reproduced the mentioned issue in a fresh standalone laravel project.\r\nAttached is a ZIP file with a docker environment ready for testing\r\n\r\n[freshLaravel.zip](https://github.com/laravel/framework/files/13725261/freshLaravel.zip)\r\n\r\n## Step to reproduce\r\n\r\nexecute the command (in root directory:\r\n- `docker-compose build`\r\n- `docker-compose up -d`\r\n- `docker-compose exec php bash`\r\n- `php artisan migrate`\r\n- `php artisan queue:work`\r\n- open browser http://localhost\r\n\r\n\r\n- There will be one job dispatched which timesout inside transaction and one without\r\n- After queue:work dies (because of 'killed') you can go to http://localhost:8080 to verify that there is NO job logged in failed_jobs table\r\n- You can run `php artisan queue:work` again to process the second job, and verify that this one WILL be logged in failed_jobs table\r\n\r\nThank you for your consideration & time\r\n\r\n\r\n",
"created_at": "2023-12-20T09:10:33Z"
},
{
"body": "Can you push the repository to github as suggested above?",
"created_at": "2023-12-20T23:43:28Z"
},
{
"body": "@graemlourens It seems that you didn't specify https://laravel.com/docs/10.x/queues#max-job-attempts-and-timeout and I don't see how it would goes to `failed_jobs` without the option as it would goes back to jobs and ready for another attempt after each failure.",
"created_at": "2023-12-21T23:39:40Z"
},
{
"body": "@crynobone We did not specify $tries as by default its 1 and therefore the setting was unnecessary, and we did set the $timeout on the job properly\r\n\r\nHowever just to rule out any error on our side, we added tries=1 on the job, as well as also on the worker, **and it had no influence, as suspected.**\r\n\r\n**One Job is logged** (the one without transaction) and **one job is NOT logged** (the one with transaction)\r\n\r\nBoth jobs **are configured exactly the same**, the only difference in them is that one has the sleep inside of a transaction and the other does not.\r\n\r\nI'm not sure how better we can show you this bug. I highly suspect that you did not execute the steps we provided to reproduce the error or else you could confirm this behaviour by proof of one entry in the failed_jobs table.\r\n\r\nIf you **reconsider to reopen this ticket**, we'll be glad to push it as a repository as you requested.",
"created_at": "2023-12-22T06:48:34Z"
},
{
"body": "@crynobone we've had further success in this matter:\r\n\r\nStrangely the bug is fixed if you use 'Batchable' on the Job.\r\n\r\nThe reason the job is then logged correctly is because of Illuminate\\Queue\\Jobs\\Job. In the 'fail' method there is a check on line 195:\r\n\r\n```\r\nif ($e instanceof TimeoutExceededException &&\r\n $commandName &&\r\n in_array(Batchable::class, class_uses_recursive($commandName))) {\r\n $batchRepository = $this->resolve(BatchRepository::class);\r\n```\r\n\r\nIn this case you're running 'rollBack' on the $batchRepository. Even if the job is not attached to a batch, this fixes the problem.\r\n\r\nHowever i don't think its correct for us to have to set all jobs as batchable to resolve this issue. I still believe this should also be handled for jobs without batches.\r\n\r\nHow do you see this?",
"created_at": "2023-12-22T07:07:11Z"
},
{
"body": "Tries doesn't have a default of `1`: https://github.com/laravel/framework/blob/047edbc3a370ccf8be58f35f2e262d59210a3852/src/Illuminate/Queue/Jobs/Job.php#L278",
"created_at": "2023-12-22T08:13:10Z"
},
{
"body": "@crynobone ok, still however as mentioned, we set tries to 1 and it still happens.\r\n\r\nPlease also refer to my temporary solution that if you use 'Batchable' on the Job, it works, without it does not.\r\n\r\nHow do you feel about this?",
"created_at": "2023-12-22T08:20:41Z"
},
{
"body": "I cannot replicate the issue and your reproduction code doesn't show what you are claiming is true. This is why we advised sending the repository to GitHub.",
"created_at": "2023-12-22T08:22:15Z"
},
{
"body": "@crynobone you are confirming you downloaded our ZIP, ran the commands we provided, and you did NOT see the outcome we described? I do not see how this is possible. I can provide a screenshare movie if you prefer.\r\n\r\nOr are you telling me that you will only reproduce it when we have pushed it to repository on github?",
"created_at": "2023-12-22T08:23:46Z"
},
{
"body": "> We'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue as one separate commit on the main/master branch and share the repository here?\n\nHaving everything in a single commit allow us to completely eliminate any other possibility outside just the affected code instead having to verify evey files inside the zip file.",
"created_at": "2023-12-22T08:26:00Z"
},
{
"body": "@crynobone a coworker of mine has uploaded the repo as requested: https://github.com/GrzegorzMorgas/laravel-bug-report\r\n\r\nWe were a little confused if to commit everything as ONE commit or the base commit of base setup and then a second commit with the changes required to reproduce the issue. The instructions are a little ambigous to us:\r\n\r\n\"commit the code ... as one separate commit\"\r\nbut then\r\n\"Do not amend and create a separate commit with your custom changes\"\r\n\r\nPlease let us know if what we created is ok and you can reproduce or you would like the repository in a different way",
"created_at": "2023-12-22T10:24:11Z"
},
{
"body": "@graemlourens use the command from here: https://github.com/laravel/framework/issues/49389#issuecomment-1862206409\r\n\r\nThen commit all custom changes separately.",
"created_at": "2023-12-22T12:32:02Z"
},
{
"body": "@driesvints @crynobone Understood. We've done as requested:\r\n\r\nhttps://github.com/GrzegorzMorgas/bug-report\r\n\r\n## Step to reproduce\r\n\r\nexecute the command (in root directory of the folder):\r\n- `docker-compose build`\r\n- `docker-compose up -d`\r\n- `docker-compose exec php bash`\r\n- `cp .env.example .env`\r\n- `composer install`\r\n- `php artisan migrate`\r\n- `php artisan queue:work`\r\n- open browser http://localhost\r\n\r\n\r\n- There will be one job dispatched which timesout inside transaction and one without\r\n- After queue:work dies (because of 'killed') you can go to http://localhost:8080 to verify that there is NO job logged in failed_jobs table\r\n- You can run `php artisan queue:work` again to process the second job, and verify that this one WILL be logged in failed_jobs table\r\n\r\n## Important find\r\n\r\nIf you 'use Batchable' on the Job, then also the one timeouting with transaction suddenly works. We have traced this back to\r\n\r\n```\r\nif ($e instanceof TimeoutExceededException &&\r\n $commandName &&\r\n in_array(Batchable::class, class_uses_recursive($commandName))) {\r\n $batchRepository = $this->resolve(BatchRepository::class);\r\n```\r\n\r\nIn `Illuminate\\Queue\\Jobs\\Job`\r\n\r\nBecause there is a rollback there, it seems to work. However we believe it should not be necessary to set all jobs as Batchable to get around this bug.\r\n\r\n\r\nThank you for your consideration & time",
"created_at": "2023-12-23T07:01:25Z"
},
{
"body": "Thanks @graemlourens. Might be a while before we can dig into this because we're all heading into holidays.",
"created_at": "2023-12-23T07:54:58Z"
},
{
"body": "I have reviewed this issue and it may not be an actual bug after all. This happens because of the async signal handler.\r\n`src/Illuminate/Queue/Worker.php` Line 167 `registerTimeoutHandler` will kill the current process if timeout reached. At this point it will try to log the failed job in the database but since the transaction was opened, the insert command will not persist. \r\n\r\nHere are two solutions:\r\n1. I recommend updating the Laravel Docs about this case and use the `public function failed(\\Throwable $exception): void` function inside your job to rollback the transaction. I tested this and it works fine (failed job is logged).\r\n2. If this issue is still found as actual bug, we will need to reset the database connection somewhere in the Worker `registerTimeoutHandler` function. I dont think this should fall under the scope of the framework though and should be handled within the job `failed` function instead (point 1)",
"created_at": "2023-12-30T16:30:20Z"
},
{
"body": "@gkmk Thank you for your insight and suggestions.\r\n\r\nThe reason i would tend to shy away from option 1) is because then behaviour would be different between jobs that are batchable, and ones that are not. This would be an unnecessary inconsistency in my opinion. (See my previous comment)\r\n\r\nOn a more subjective note, we have > 100 jobs, most of them have transactions and do not require failed methods. Option 2) would add failed methods just to handle this specific case to not loose jobs, which seems to be quite an overhead.\r\n\r\nWill be interesting to see what the core of laravel developers have to say.",
"created_at": "2023-12-30T19:03:08Z"
},
{
"body": "> is because then behaviour would be different between jobs that are batchable, and ones that are not. This would be an unnecessary inconsistency in my opinion. \r\n\r\nYes, this is intended because Batchable Jobs offer `catch` and `finally` which need to be called within the same process while normal queue typically rely on n+1 (n = number of retries) to throw error.\r\n\r\n> would add failed methods just to handle this specific case to not loose jobs, which seems to be quite an overhead.\r\n\r\nThe documentation already cover this in detail:\r\n\r\n\r\n\r\nhttps://laravel.com/docs/10.x/queues#timeout\r\n\r\n",
"created_at": "2024-01-02T00:59:09Z"
},
{
"body": "@crynobone @driesvints @themsaid we disagree with your assessment and rest our case. We hope that in future there will be a fix for this inconsistency which will reduce the chance of loosing jobs, which we find is crucial to be able to rely on laravel queues as a major component for larger applications.\r\n\r\nfor anybody else worried about this: Our solution will most likely be **to declare all Jobs as Batchable**, which seems to not have any ill-effect and even if the job is not dispatched within a batch it therefore handles the transaction correctly so that the job is logged properly in case of timeout within a transaction.",
"created_at": "2024-01-02T05:13:42Z"
},
{
"body": "> for anybody else worried about this: Our solution will most likely be to declare all Jobs as Batchable,\r\n\r\nRead the documentation, the worker can be restarted using a process manager (which should be the default usage in any production applications anyway), or use `queue:listen` (uses more CPUs if you insist to not going with process manager). ",
"created_at": "2024-01-02T05:40:48Z"
},
{
"body": "@crynobone we use laravel horizon which automatically handles that. But please be aware: If the job had $tries=1 (which most of our jobs do) the job is **NOT retried**, and **NOT logged**, and therefore **lost**.\r\n\r\nPlease correct my if i'm wrong. This is the whole point of this ticket - loosing jobs",
"created_at": "2024-01-02T05:44:18Z"
}
],
"number": 49389,
"title": "Job not logged in failed_jobs if timeout occurs within database transaction"
} | {
"body": "Verify #49389\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 49426,
"review_comments": [],
"title": "[10.x] Test Improvements"
} | {
"commits": [
{
"message": "[10.x] Test Improvements\n\nVerify #49389\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "Apply fixes from StyleCI"
}
],
"files": [
{
"diff": "@@ -0,0 +1,54 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\Queue;\n+\n+use Illuminate\\Foundation\\Testing\\DatabaseMigrations;\n+use Illuminate\\Support\\Facades\\DB;\n+use Illuminate\\Tests\\Integration\\Database\\DatabaseTestCase;\n+use Orchestra\\Testbench\\Attributes\\WithMigration;\n+use PHPUnit\\Framework\\Attributes\\RequiresPhpExtension;\n+use Symfony\\Component\\Process\\Exception\\ProcessSignaledException;\n+use Throwable;\n+\n+use function Orchestra\\Testbench\\remote;\n+\n+#[RequiresPhpExtension('pcntl')]\n+#[WithMigration('laravel', 'queue')]\n+class QueueTransactionTest extends DatabaseTestCase\n+{\n+ use DatabaseMigrations;\n+\n+ protected function defineEnvironment($app)\n+ {\n+ parent::defineEnvironment($app);\n+\n+ $config = $app['config'];\n+\n+ if ($config->get('database.default') === 'testing') {\n+ $this->markTestSkipped('Test does not support using :memory: database connection');\n+ }\n+\n+ $config->set(['queue.default' => 'database']);\n+ }\n+\n+ public function testItCanHandleTimeoutJob()\n+ {\n+ dispatch(new Fixtures\\TimeOutJobWithTransaction);\n+\n+ $this->assertSame(1, DB::table('jobs')->count());\n+ $this->assertSame(0, DB::table('failed_jobs')->count());\n+\n+ try {\n+ remote('queue:work --stop-when-empty', [\n+ 'DB_CONNECTION' => config('database.default'),\n+ 'QUEUE_CONNECTION' => config('queue.default'),\n+ ])->run();\n+ } catch (Throwable $e) {\n+ $this->assertInstanceOf(ProcessSignaledException::class, $e);\n+ $this->assertSame('The process has been signaled with signal \"9\".', $e->getMessage());\n+ }\n+\n+ $this->assertSame(0, DB::table('jobs')->count());\n+ $this->assertSame(1, DB::table('failed_jobs')->count());\n+ }\n+}",
"filename": "tests/Integration/Database/Queue/QueueTransactionTest.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\n\n10.37.1\n\n### PHP Version\n\n8.3.0\n\n### Database Driver & Version\n\nPostgres 14 + Postgis\n\n### Description\n\nAfter the inclusion of 57ae89a, dropping types is now also trying to drop types added by extensions (e.g. `postgis`). This is causing the database reset step of tests to fail.\r\n\r\n```\r\n SQLSTATE[2BP01]: Dependent objects still exist: 7 ERROR: cannot drop type spheroid because extension postgis requires it\r\n```\n\n### Steps To Reproduce\n\n1. Add ` protected bool $dropTypes = true;` to a feature test with multiple tests\r\n2. Configure the database to use Postgres and create the postgis extension\r\n3. Run the tests",
"comments": [
{
"body": "I sent PR #49358 for this. ",
"created_at": "2023-12-13T08:54:16Z"
},
{
"body": "Thanks, can confirm this has fixed the issue for me :)",
"created_at": "2023-12-13T21:40:13Z"
}
],
"number": 49349,
"title": "Clearing user types wipes extension types"
} | {
"body": "Related to #49303\r\n\r\nFixes #49349 by excluding the types dependent to an extension.\r\n\r\nThere seems to be no way to write a test for this ATM, as there is no PostgreSQL extension installed.",
"number": 49358,
"review_comments": [],
"title": "[10.x] Exclude extension types on PostgreSQL when retrieving types"
} | {
"commits": [
{
"message": "exclude extension types"
},
{
"message": "also exclude implicit extension types"
}
],
"files": [
{
"diff": "@@ -115,6 +115,7 @@ public function compileTypes()\n .'left join pg_type el on el.oid = t.typelem '\n .'left join pg_class ce on ce.oid = el.typrelid '\n .\"where ((t.typrelid = 0 and (ce.relkind = 'c' or ce.relkind is null)) or c.relkind = 'c') \"\n+ .\"and not exists (select 1 from pg_depend d where d.objid in (t.oid, t.typelem) and d.deptype = 'e') \"\n .\"and n.nspname not in ('pg_catalog', 'information_schema')\";\n }\n ",
"filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.35.0\r\n\r\n### PHP Version\r\n\r\n8.2.13\r\n\r\n### Database Driver & Version\r\n\r\nPostgreSQL 15.5 for Ubuntu on amd64\r\n\r\n### Description\r\n\r\n`db:wipe` only drops regular tables, partitioned tables are not dropped in PostgreSQL. I've noticed this while running `migrate:fresh` command (from `RefreshDatabase` trait in tests). If some migration is creating a partitioned table without checking if it exists, running tests passes the first time but fails on every following run because the table already exists. Even if table is created with `IF NOT EXISTS` migrations changing it will have the same problem.\r\n\r\nExpected behavior would be for the partitioned tables to be removed as well.\r\n\r\nIt started happening from version 10.34.0 (https://github.com/laravel/framework/pull/49020).\r\n\r\n### Steps To Reproduce\r\n\r\n- Clone https://github.com/nikazooz/postgresql-partitioned-table-failed-migration and move into the folder\r\n- Laravel Sail is installed for easy database setup so with Docker running start the containers with `vendor/bin/sail up -d`\r\n- Install dependencies with `vendor/bin/sail composer install` \r\n- Run tests with `vendor/bin/sail test` - they pass the first time.\r\n- Run tests again they fail with error `Duplicate table: 7 ERROR: relation \"groups\" already exists`\r\n",
"comments": [
{
"body": "cc @hafezdivandari ",
"created_at": "2023-12-11T13:07:31Z"
},
{
"body": "Thanks for reporting, I sent a PR for this.",
"created_at": "2023-12-11T14:52:53Z"
}
],
"number": 49321,
"title": "`db:wipe` doesn't remove partitioned tables on PostgreSQL"
} | {
"body": "Fixes #49321 by including partitioned tables on `Schema::getTables()`.\r\n\r\nFixes orchestral/testbench#388 by simply rescue compiling the query as some legacy SQLite versions doesn't support `pragma_compile_options`.",
"number": 49326,
"review_comments": [],
"title": "[10.x] Include partitioned tables on PostgreSQL when retrieving tables"
} | {
"commits": [
{
"message": "wip"
},
{
"message": "include partitioned tables on getTables query"
},
{
"message": "fix tests"
},
{
"message": "fix tests"
},
{
"message": "fix getTables on legacy sqlite version"
},
{
"message": "fix tests"
}
],
"files": [
{
"diff": "@@ -87,7 +87,7 @@ public function compileTables()\n {\n return 'select c.relname as name, n.nspname as schema, pg_total_relation_size(c.oid) as size, '\n .\"obj_description(c.oid, 'pg_class') as comment from pg_class c, pg_namespace n \"\n- .\"where c.relkind = 'r' and n.oid = c.relnamespace \"\n+ .\"where c.relkind in ('r', 'p') and n.oid = c.relnamespace and n.nspname not in ('pg_catalog', 'information_schema')\"\n .'order by c.relname';\n }\n \n@@ -98,7 +98,7 @@ public function compileTables()\n */\n public function compileViews()\n {\n- return 'select viewname as name, schemaname as schema, definition from pg_views order by viewname';\n+ return \"select viewname as name, schemaname as schema, definition from pg_views where schemaname not in ('pg_catalog', 'information_schema') order by viewname\";\n }\n \n /**",
"filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php",
"status": "modified"
},
{
"diff": "@@ -37,7 +37,7 @@ public function dropDatabaseIfExists($name)\n */\n public function getTables()\n {\n- $withSize = $this->connection->scalar($this->grammar->compileDbstatExists());\n+ $withSize = rescue(fn () => $this->connection->scalar($this->grammar->compileDbstatExists()), false, false);\n \n return $this->connection->getPostProcessor()->processTables(\n $this->connection->selectFromWriteConnection($this->grammar->compileTables($withSize))",
"filename": "src/Illuminate/Database/Schema/SQLiteBuilder.php",
"status": "modified"
},
{
"diff": "@@ -165,6 +165,29 @@ public function testGetViews()\n }));\n }\n \n+ public function testDropPartitionedTables()\n+ {\n+ DB::statement('create table groups (id bigserial, tenant_id bigint, name varchar, primary key (id, tenant_id)) partition by hash (tenant_id)');\n+ DB::statement('create table groups_1 partition of groups for values with (modulus 2, remainder 0)');\n+ DB::statement('create table groups_2 partition of groups for values with (modulus 2, remainder 1)');\n+\n+ $tables = array_column(Schema::getTables(), 'name');\n+\n+ $this->assertContains('groups', $tables);\n+ $this->assertContains('groups_1', $tables);\n+ $this->assertContains('groups_2', $tables);\n+\n+ Schema::dropAllTables();\n+\n+ $this->artisan('migrate:install');\n+\n+ $tables = array_column(Schema::getTables(), 'name');\n+\n+ $this->assertNotContains('groups', $tables);\n+ $this->assertNotContains('groups_1', $tables);\n+ $this->assertNotContains('groups_2', $tables);\n+ }\n+\n protected function hasView($schema, $table)\n {\n return DB::table('information_schema.views')",
"filename": "tests/Integration/Database/Postgres/PostgresSchemaBuilderTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.34.2\n\n### PHP Version\n\n8.2.8\n\n### Database Driver & Version\n\nPostgres\n\n### Description\n\nIf a route is registered and provides a closure rather than a Controller, calling `getController()` on the `\\Illuminate\\Routing\\Route` instance will result in an error.\r\n\r\nThis is because `getControllerClass()` returns `null`, which is then passed into `$this->container->make()` on the next lines.\r\n\r\nThe expected behavior here seems like it should return `null` instead of attempting the `make()` and throwing an error. That would prevent issues with calling this method and return an expected result of `null` for the return.\r\n\r\nI can submit a PR if y'all consider this a viable fix.\n\n### Steps To Reproduce\n\n1. Register a route with a closure instead of a Controller.\r\n2. Call `getController()` on a `\\Illuminate\\Routing\\Route` instance for that route.",
"comments": [
{
"body": "Hey there, thanks for reporting this issue.\r\n\r\nWe'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue *as one separate commit* on the main/master branch and share the repository here?\r\n\r\nPlease make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com/) properly set up.\r\n\r\n laravel new bug-report --github=\"--public\"\r\n\r\nDo not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.\r\n\r\nThanks!",
"created_at": "2023-12-07T00:19:22Z"
},
{
"body": "Thank you for the consideration and the fix @crynobone!",
"created_at": "2023-12-07T14:47:32Z"
}
],
"number": 49267,
"title": "When using closure routing calling getController() on the route throws an error"
} | {
"body": "fixes #49267\r\n\r\n<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n",
"number": 49269,
"review_comments": [],
"title": "[10.x] `Route::getController()` should return `null` when the accessing closure based route"
} | {
"commits": [
{
"message": "[10.x] `Route::getController()` should return `null` when the accessing\nclosure based route\n\nfixes #49267\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
}
],
"files": [
{
"diff": "@@ -268,6 +268,10 @@ protected function runController()\n */\n public function getController()\n {\n+ if (! $this->isControllerAction()) {\n+ return null;\n+ }\n+\n if (! $this->controller) {\n $class = $this->getControllerClass();\n ",
"filename": "src/Illuminate/Routing/Route.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.33.0\n\n### PHP Version\n\n8.1.25\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nWhen running\r\n\r\n`php artisan about --json `\r\n\r\njson output for drivers => logs is \"stack \\/ single\"\r\n\r\n`\"drivers\":{\"broadcasting\":\"log\",\"cache\":\"file\",\"database\":\"mysql\",\"logs\":\"stack \\/ single\",\"mail\":\"smtp\",\"queue\":\"sync\",\"session\":\"file\"}`\r\n\r\nwithout --json the output is colored and there's no problem, but with json format both values stack & single are printed with no distinction.\r\n\n\n### Steps To Reproduce\n\nJust run \r\n\r\n`php artisan about`\r\n\r\nand then\r\n\r\n`php artisan about --json`\r\n\r\nand try to find in json output the drivers_logs value enabled.",
"comments": [],
"number": 49147,
"title": "artisan about --json does not show explicitly which drivers logs you are using"
} | {
"body": "Fixes #49147 \r\n\r\nIntroduce new `AboutCommand::format()` helper method to make it possible to apply a different format for JSON and CLI.",
"number": 49154,
"review_comments": [],
"title": "[10.x] Improves output when using `php artisan about --json`"
} | {
"commits": [
{
"message": "[10.x] Improves output when using `php artisan about --json`\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "Apply fixes from StyleCI"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "formatting"
}
],
"files": [
{
"diff": "@@ -2,6 +2,7 @@\n \n namespace Illuminate\\Foundation\\Console;\n \n+use Closure;\n use Illuminate\\Console\\Command;\n use Illuminate\\Support\\Composer;\n use Illuminate\\Support\\Str;\n@@ -127,7 +128,7 @@ protected function displayDetail($data)\n $data->pipe(fn ($data) => $section !== 'Environment' ? $data->sort() : $data)->each(function ($detail) {\n [$label, $value] = $detail;\n \n- $this->components->twoColumnDetail($label, value($value));\n+ $this->components->twoColumnDetail($label, value($value, false));\n });\n });\n }\n@@ -143,7 +144,7 @@ protected function displayJson($data)\n $output = $data->flatMap(function ($data, $section) {\n return [\n (string) Str::of($section)->snake() => $data->mapWithKeys(fn ($item, $key) => [\n- $this->toSearchKeyword($item[0]) => value($item[1]),\n+ $this->toSearchKeyword($item[0]) => value($item[1], true),\n ]),\n ];\n });\n@@ -158,40 +159,48 @@ protected function displayJson($data)\n */\n protected function gatherApplicationInformation()\n {\n+ $formatEnabledStatus = fn ($value) => $value ? '<fg=yellow;options=bold>ENABLED</>' : 'OFF';\n+ $formatCachedStatus = fn ($value) => $value ? '<fg=green;options=bold>CACHED</>' : '<fg=yellow;options=bold>NOT CACHED</>';\n+\n static::addToSection('Environment', fn () => [\n 'Application Name' => config('app.name'),\n 'Laravel Version' => $this->laravel->version(),\n 'PHP Version' => phpversion(),\n 'Composer Version' => $this->composer->getVersion() ?? '<fg=yellow;options=bold>-</>',\n 'Environment' => $this->laravel->environment(),\n- 'Debug Mode' => config('app.debug') ? '<fg=yellow;options=bold>ENABLED</>' : 'OFF',\n+ 'Debug Mode' => static::format(config('app.debug'), console: $formatEnabledStatus),\n 'URL' => Str::of(config('app.url'))->replace(['http://', 'https://'], ''),\n- 'Maintenance Mode' => $this->laravel->isDownForMaintenance() ? '<fg=yellow;options=bold>ENABLED</>' : 'OFF',\n+ 'Maintenance Mode' => static::format($this->laravel->isDownForMaintenance(), console: $formatEnabledStatus),\n ]);\n \n static::addToSection('Cache', fn () => [\n- 'Config' => $this->laravel->configurationIsCached() ? '<fg=green;options=bold>CACHED</>' : '<fg=yellow;options=bold>NOT CACHED</>',\n- 'Events' => $this->laravel->eventsAreCached() ? '<fg=green;options=bold>CACHED</>' : '<fg=yellow;options=bold>NOT CACHED</>',\n- 'Routes' => $this->laravel->routesAreCached() ? '<fg=green;options=bold>CACHED</>' : '<fg=yellow;options=bold>NOT CACHED</>',\n- 'Views' => $this->hasPhpFiles($this->laravel->storagePath('framework/views')) ? '<fg=green;options=bold>CACHED</>' : '<fg=yellow;options=bold>NOT CACHED</>',\n+ 'Config' => static::format($this->laravel->configurationIsCached(), console: $formatCachedStatus),\n+ 'Events' => static::format($this->laravel->eventsAreCached(), console: $formatCachedStatus),\n+ 'Routes' => static::format($this->laravel->routesAreCached(), console: $formatCachedStatus),\n+ 'Views' => static::format($this->hasPhpFiles($this->laravel->storagePath('framework/views')), console: $formatCachedStatus),\n ]);\n \n- $logChannel = config('logging.default');\n-\n- if (config('logging.channels.'.$logChannel.'.driver') === 'stack') {\n- $secondary = collect(config('logging.channels.'.$logChannel.'.channels'))\n- ->implode(', ');\n-\n- $logs = '<fg=yellow;options=bold>'.$logChannel.'</> <fg=gray;options=bold>/</> '.$secondary;\n- } else {\n- $logs = $logChannel;\n- }\n-\n static::addToSection('Drivers', fn () => array_filter([\n 'Broadcasting' => config('broadcasting.default'),\n 'Cache' => config('cache.default'),\n 'Database' => config('database.default'),\n- 'Logs' => $logs,\n+ 'Logs' => function ($json) {\n+ $logChannel = config('logging.default');\n+\n+ if (config('logging.channels.'.$logChannel.'.driver') === 'stack') {\n+ $secondary = collect(config('logging.channels.'.$logChannel.'.channels'));\n+\n+ return value(static::format(\n+ value: $logChannel,\n+ console: fn ($value) => '<fg=yellow;options=bold>'.$value.'</> <fg=gray;options=bold>/</> '.$secondary->implode(', '),\n+ json: fn () => $secondary->all(),\n+ ), $json);\n+ } else {\n+ $logs = $logChannel;\n+ }\n+\n+ return $logs;\n+ },\n 'Mail' => config('mail.default'),\n 'Octane' => config('octane.server'),\n 'Queue' => config('queue.default'),\n@@ -260,6 +269,27 @@ protected function sections()\n ->all();\n }\n \n+ /**\n+ * Materialize a function that formats a given value for CLI or JSON output.\n+ *\n+ * @param mixed $value\n+ * @param (\\Closure():(mixed))|null $console\n+ * @param (\\Closure():(mixed))|null $json\n+ * @return \\Closure(bool):mixed\n+ */\n+ public static function format($value, Closure $console = null, Closure $json = null)\n+ {\n+ return function ($isJson) use ($value, $console, $json) {\n+ if ($isJson === true && $json instanceof Closure) {\n+ return value($json, $value);\n+ } elseif ($isJson === false && $console instanceof Closure) {\n+ return value($console, $value);\n+ }\n+\n+ return value($value);\n+ };\n+ }\n+\n /**\n * Format the given string for searching.\n *",
"filename": "src/Illuminate/Foundation/Console/AboutCommand.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,42 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Foundation\\Console;\n+\n+use Illuminate\\Foundation\\Console\\AboutCommand;\n+use PHPUnit\\Framework\\Attributes\\DataProvider;\n+use PHPUnit\\Framework\\TestCase;\n+\n+class AboutCommandTest extends TestCase\n+{\n+ /**\n+ * @param \\Closure(bool):mixed $format\n+ * @param mixed $expected\n+ */\n+ #[DataProvider('cliDataProvider')]\n+ public function testItCanFormatForCliInterface($format, $expected)\n+ {\n+ $this->assertSame($expected, value($format, false));\n+ }\n+\n+ public static function cliDataProvider()\n+ {\n+ yield [AboutCommand::format(true, console: fn ($value) => $value === true ? 'YES' : 'NO'), 'YES'];\n+ yield [AboutCommand::format(false, console: fn ($value) => $value === true ? 'YES' : 'NO'), 'NO'];\n+ }\n+\n+ /**\n+ * @param \\Closure(bool):mixed $format\n+ * @param mixed $expected\n+ */\n+ #[DataProvider('jsonDataProvider')]\n+ public function testItCanFormatForJsonInterface($format, $expected)\n+ {\n+ $this->assertSame($expected, value($format, true));\n+ }\n+\n+ public static function jsonDataProvider()\n+ {\n+ yield [AboutCommand::format(true, json: fn ($value) => $value === true ? 'YES' : 'NO'), 'YES'];\n+ yield [AboutCommand::format(false, json: fn ($value) => $value === true ? 'YES' : 'NO'), 'NO'];\n+ }\n+}",
"filename": "tests/Foundation/Console/AboutCommandTest.php",
"status": "added"
},
{
"diff": "@@ -0,0 +1,43 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Foundation\\Console;\n+\n+use Illuminate\\Testing\\Assert;\n+use Orchestra\\Testbench\\TestCase;\n+\n+use function Orchestra\\Testbench\\remote;\n+\n+class AboutCommandTest extends TestCase\n+{\n+ public function testItCanDisplayAboutCommandAsJson()\n+ {\n+ $process = remote('about --json')->mustRun();\n+\n+ tap(json_decode($process->getOutput(), true), function ($output) {\n+ Assert::assertArraySubset([\n+ 'application_name' => 'Laravel',\n+ 'php_version' => PHP_VERSION,\n+ 'environment' => 'testing',\n+ 'debug_mode' => true,\n+ 'url' => 'localhost',\n+ 'maintenance_mode' => false,\n+ ], $output['environment']);\n+\n+ Assert::assertArraySubset([\n+ 'config' => false,\n+ 'events' => false,\n+ 'routes' => false,\n+ ], $output['cache']);\n+\n+ Assert::assertArraySubset([\n+ 'broadcasting' => 'log',\n+ 'cache' => 'file',\n+ 'database' => 'testing',\n+ 'logs' => ['single'],\n+ 'mail' => 'smtp',\n+ 'queue' => 'sync',\n+ 'session' => 'file',\n+ ], $output['drivers']);\n+ });\n+ }\n+}",
"filename": "tests/Integration/Foundation/Console/AboutCommandTest.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.31.0\r\n\r\n### PHP Version\r\n\r\n8.2.11\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nWhen passing multi-word blade component attributes to a child component they don't make it to the child component. Probably best explained with an example:\r\n\r\n\r\n\r\n### Steps To Reproduce\r\n\r\nI have a blade component called `foo`:\r\n\r\n```blade\r\n@props([\r\n 'one' => 'none',\r\n 'twoWord' => 'none',\r\n])\r\n{{ $one }} {{ $twoWord }}\r\n```\r\n\r\nAnd I have another blade component called `bar` which simply wraps `foo` and passes everything down:\r\n\r\n```blade\r\n<x-foo :attributes=\"$attributes\"></x-foo>\r\n```\r\n\r\nIf I render these two components like this:\r\n\r\n```blade\r\n<x-foo one=\"ok\" two-word=\"ok\"></x-foo>\r\n<x-bar one=\"ok\" two-word=\"ok\"></x-bar>\r\n```\r\n\r\nI would expect this output:\r\n\r\n```\r\nok ok\r\nok ok\r\n```\r\n\r\nHowever instead I get:\r\n\r\n```\r\nok ok\r\nok none\r\n```\r\n\r\nIn both instances if I dump the attribute bag inside `foo` it's empty, which I would expect.\r\n\r\nThe `two-word`/`$twoWord` value just seems to disappear when passed via `bar`, but the `one`/`$one` value works fine.\r\n\r\n\r\n\r\n`foo` and `bar` are both anonymous components.",
"comments": [
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-11-09T13:13:44Z"
},
{
"body": "Hello!\r\n\r\nI do not have a great amount of experience using Blade components, but I noticed something a while ago that made me realize I might not fully understand all the concepts about Blade components, and perhaps I was the one making mistakes.\r\n\r\nMaybe it is a bug, but I'm not sure. I'd prefer to share this here and see if someone with more experience can figure it out.\r\n\r\nLet's consider the scenario that @jacksleight mentioned above.\r\n\r\n\"foo\" anonymous Blade component:\r\n\r\n```blade\r\n// resources/views/components/foo.blade.php\r\n@props([\r\n 'one' => 'none',\r\n 'twoWord' => 'none',\r\n])\r\n<div>\r\n One: {{ $one }} <br>\r\n Two: {{ $twoWord }} <br>\r\n</div>\r\n```\r\n\r\nAnd the \"bar\" anonymous blade component\r\n```blade\r\n// resources/views/components/bar.blade.php\r\n<div>\r\n <x-foo :attributes=\"$attributes\" />\r\n</div>\r\n```\r\n\r\nIf we use them like this on the welcome.blade.php file\r\n```blade\r\nfoo\r\n<x-foo one=\"ok\" two-word=\"ok\" />\r\n\r\nbar (kebab-case):\r\n<x-bar one=\"ok\" two-word=\"ok\" />\r\n\r\nbar (camelCase):\r\n<x-bar one=\"ok\" twoWord=\"ok\" />\r\n```\r\n\r\nFor some reason, the `kebab-case` version of the bar component won't work as expected, but the camelCase version will.\r\n\r\nThis is the output:\r\n\r\n\r\nTo make the kebab-case version work, I had to use `@ aware` on the foo component and put the name of the prop. \r\n\r\n```blade\r\n@props([\r\n 'one' => 'none',\r\n 'twoWord' => 'none',\r\n])\r\n@aware(['twoWord'])\r\n<div>\r\n One: {{ $one }} <br>\r\n Two: {{ $twoWord }} <br>\r\n</div>\r\n``` \r\n\r\n\r\n\r\n\r\nBut I think this is not how it's supposed to work. \r\n\r\nThe docs says this about components:\r\n```\r\nComponent constructor arguments should be specified using camelCase, while kebab-case should be used when referencing the argument names in your HTML attributes. For example, given the following component constructor\r\n```\r\n\r\nAgain, there is a good chance that I am misunderstanding something, but I just wanted to contribute this information with the bug the @jacksleight mentioned.\r\n\r\n",
"created_at": "2023-11-09T17:36:06Z"
},
{
"body": "Yeah my understanding is that you should always use kebab case in the tag and camel case in `@props`.\r\n\r\nAnd that does work as expected if you make `$twoWords` a prop in `bar`, but something is preventing that from working when the values are passed down to `foo` from `bar`.",
"created_at": "2023-11-09T18:06:23Z"
},
{
"body": "If you know it is a prop you should declare it as such in your wrapped component and pass it as a propped to the final child component.",
"created_at": "2023-11-27T15:26:24Z"
},
{
"body": "Ah OK, the thing is you wouldn't always know it's a prop.\r\n\r\nThe idea here is that the `bar` component is a simple wrapper around a `foo` component, and will blindly pass everything it receives down to `foo` while setting one or more props/attrs of it's own. (The example above is simplified obviously, in my actual app I have a `button` component and a `button.loading` component. `button.loading` accepts and passes on everything `button` accepts, while setting a couple of values in the process.)\r\n\r\nWhile I could define all of `foo`'s props in `bar` as well, that would create a whole load of duplication, and it gets tricky if `foo` is a component from a 3rd party package where you wont always know when new props have been added.",
"created_at": "2023-11-27T16:52:13Z"
}
],
"number": 48956,
"title": "Multi-word blade component attributes aren't passed to child component"
} | {
"body": "Fixes #48956 ",
"number": 48983,
"review_comments": [],
"title": "[10.x] Add camel case conversion for component data keys if they are …"
} | {
"commits": [
{
"message": "[10.x] Add camel case conversion for component data keys if they are in kebab-case"
}
],
"files": [
{
"diff": "@@ -5,6 +5,7 @@\n use Illuminate\\Contracts\\Support\\Htmlable;\n use Illuminate\\Contracts\\View\\View;\n use Illuminate\\Support\\Arr;\n+use Illuminate\\Support\\Str;\n use Illuminate\\View\\ComponentSlot;\n \n trait ManagesComponents\n@@ -95,6 +96,12 @@ public function renderComponent()\n try {\n $view = value($view, $data);\n \n+ $data = array_combine(\n+ array_map(fn ($key) => preg_match('/^[a-z]+(-[a-z]+)*$/', $key)\n+ ? Str::camel($key) : $key, array_keys($data)),\n+ array_values($data)\n+ );\n+\n if ($view instanceof View) {\n return $view->with($data)->render();\n } elseif ($view instanceof Htmlable) {",
"filename": "src/Illuminate/View/Concerns/ManagesComponents.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.30.1\n\n### PHP Version\n\n8.2.11\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nOwing to how concurrent HTTP requests using the HTTP client are executed (using promises), an exception can be encountered due to a sometimes incorrect type hint. Specifically line 1010 within the `makePromise` method of `Illuminate/Http/Client/PendingRequest`.\r\n\r\nIn some situations, the exception that is thrown is not a `TransferException`, but an `OutOfBoundsException`. It may be preferable to remove the type hint.\n\n### Steps To Reproduce\n\nWhen using the Http Client to send concurrent requests e.g.\r\n\r\n```php\r\nHttp::pool(fn (Pool $pool) => [\r\n $pool->get('http://localhost/first'),\r\n $pool->get('http://localhost/second'),\r\n $pool->get('http://localhost/third'),\r\n]);\r\n```\r\n\r\nAnd writing a test that fakes a corresponding Http response sequence e.g.\r\n\r\n```php\r\nuse Illuminate\\Support\\Facades\\Http;\r\n\r\nHttp::fakeSequence()\r\n ->push(null, 401)\r\n ->push(null, 403) \r\n ->push(null, 405);\r\n```\r\n\r\nThe following exception is thrown:\r\n\r\n```bash\r\nTypeError: Illuminate\\Http\\Client\\PendingRequest::Illuminate\\Http\\Client\\{closure}(): Argument #1 ($e) must be of type GuzzleHttp\\Exception\\TransferException, OutOfBoundsException given, called in /vendor/guzzlehttp/promises/src/RejectedPromise.php on line 49\r\n```\r\n\r\nThe error relates to the `TransferException` type hint within `Illuminate/Http/Client/PendingRequest` on line 1010. If the type hint is removed the test runs as expected.\r\n\r\nThis error is not present when sending requests separately (not concurrently) as promises are not used.",
"comments": [
{
"body": "Thanks @mattkingshott. Maybe a union type is in order here?",
"created_at": "2023-11-07T15:50:34Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-11-07T15:50:54Z"
},
{
"body": "That's the simplest option, for sure. I'll PR",
"created_at": "2023-11-07T15:52:44Z"
}
],
"number": 48938,
"title": "Using a Http Client Fake sequence with Pool triggers a TypeError exception"
} | {
"body": "As suggested by Dries, this PR fixes #48938 by altering the `otherwise` closure of the `makePromise` method on `Illuminate\\Http\\Client\\PendingRequest` so that the exception parameter becomes a union type.\r\n\r\nCurrently, any exception sent to `otherwise()` had to be a `TransferException`, however when using concurrent requests (via the HTTP client's Pool method), you can also encounter an `OutOfBoundsException`.\r\n\r\nThis is particularly noticeable when trying to create a fake sequence within a test e.g.\r\n\r\n```php\r\nuse Illuminate\\Support\\Facades\\Http;\r\n\r\nHttp::fakeSequence()\r\n ->push(null, 401)\r\n ->push(null, 403) \r\n ->push(null, 405);\r\n```\r\n\r\nAnother option is to remove the type hint altogether, however this may have unintended consequences that I'm not aware of. \r\n\r\nP.S. Since this simply adds a secondary type hint, I haven't added a test. TBH, I'm not sure how you'd specifically check for it. ",
"number": 48939,
"review_comments": [],
"title": "Update PendingRequest.php"
} | {
"commits": [
{
"message": "Update PendingRequest.php\n\nThis fixes #48938 by making the parameter a union type and adding `OutOfBoundsException`."
},
{
"message": "Update PendingRequest.php\n\nFix styling."
},
{
"message": "Update PendingRequest.php"
},
{
"message": "formatting"
}
],
"files": [
{
"diff": "@@ -23,6 +23,7 @@\n use Illuminate\\Support\\Traits\\Conditionable;\n use Illuminate\\Support\\Traits\\Macroable;\n use JsonSerializable;\n+use OutOfBoundsException;\n use Psr\\Http\\Message\\MessageInterface;\n use Psr\\Http\\Message\\RequestInterface;\n use RuntimeException;\n@@ -1007,7 +1008,7 @@ protected function makePromise(string $method, string $url, array $options = [])\n $this->dispatchResponseReceivedEvent($response);\n });\n })\n- ->otherwise(function (TransferException $e) {\n+ ->otherwise(function (OutOfBoundsException|TransferException $e) {\n if ($e instanceof ConnectException) {\n $this->dispatchConnectionFailedEvent();\n }",
"filename": "src/Illuminate/Http/Client/PendingRequest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.30.0\n\n### PHP Version\n\n8.2.11\n\n### Database Driver & Version\n\nPostgreSQL 15.1\n\n### Description\n\nThe native column attributes implementation introduced in https://github.com/laravel/framework/pull/48357 has broken inserts using Postgres models with guarded attributes and column names matching PostgreSQL reserved words in my application.\r\n\r\nThe [`compileColumns()`](https://github.com/laravel/framework/commit/85a514632e410ae8f90c2b32c79a2788ba9d1076#diff-653f90bd1ee0a1c7c7970912484e98c8bbd30c8e9a3d2f544d53834d54e7ce7cR104) query in the Postgres schema grammar makes use of PostgreSQL's `quote_ident()` function which quotes reserves words. \r\n\r\n`SELECT quote_ident('foo') as value;` -> `foo`\r\n`SELECT quote_ident('end') as value;` -> `\"end\"`\r\n\r\nThis is causing the [`GuardsAttributes`](https://github.com/laravel/framework/blob/10.x/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php#L218) trait to improperly detect fillable columns. \r\n\r\nChanging `select quote_ident(a.attname) as name` to `select a.attname as name` in the Postgres Grammar resolves the issue, but I'm not sure if there are other downstream consequences to that. \r\n\r\nEx:\r\n\r\nGiven a table like the following:\r\n\r\n```php\r\nSchema::create('my_table', function (Blueprint $table) {\r\n $table->id();\r\n $table->string('label');\r\n $table->timestamp('start');\r\n $table->timestamp('end');\r\n $table->boolean('analyze');\r\n});\r\n```\r\n\r\nThe output of `Schema::getColumns('my_table');` is the following.\r\n\r\n```php\r\narray:5 [\r\n 0 => array:8 [\r\n \"name\" => \"id\"\r\n \"type_name\" => \"int8\"\r\n \"type\" => \"bigint\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => true\r\n \"comment\" => null\r\n ]\r\n 1 => array:8 [\r\n \"name\" => \"label\"\r\n \"type_name\" => \"varchar\"\r\n \"type\" => \"character varying(255)\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n 2 => array:8 [\r\n \"name\" => \"start\"\r\n \"type_name\" => \"timestamp\"\r\n \"type\" => \"timestamp(0) without time zone\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n 3 => array:8 [\r\n \"name\" => \"\"end\"\"\r\n \"type_name\" => \"timestamp\"\r\n \"type\" => \"timestamp(0) without time zone\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n 4 => array:8 [\r\n \"name\" => \"\"analyze\"\"\r\n \"type_name\" => \"bool\"\r\n \"type\" => \"boolean\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n]\r\n```\n\n### Steps To Reproduce\n\n```php\r\nclass LaravelTest extends TestCase\r\n{\r\n public function testInsertRecordWithReservedWordFieldName()\r\n {\r\n Schema::create('my_table', function (Blueprint $table) {\r\n $table->id();\r\n $table->string('label');\r\n $table->timestamp('start');\r\n $table->timestamp('end');\r\n $table->boolean('analyze');\r\n });\r\n\r\n $model = new class extends \\Illuminate\\Database\\Eloquent\\Model {\r\n protected $table = 'my_table';\r\n protected $guarded = ['id'];\r\n public $timestamps = false;\r\n };\r\n \r\n $result = $model::query()->create([\r\n 'label' => 'test',\r\n 'start' => '2023-01-01 00:00:00',\r\n 'end' => '2024-01-01 00:00:00',\r\n 'analyze' => true,\r\n ]);\r\n\r\n $this->assertTrue($result->exists);\r\n }\r\n}\r\n```\r\n\r\nFails with error...\r\n\r\n```\r\nSQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"end\" of relation \"my_table\" violates not-null constraint\r\nDETAIL: Failing row contains (1, test, 2023-01-01 00:00:00, null, null). (Connection: pgsql, SQL: insert into \"my_table\" (\"label\", \"start\") values (test, 2023-01-01 00:00:00) returning \"id\")\r\n```\r\n\r\nPasses under Laravel 10.29.0.",
"comments": [
{
"body": "Seems like a side-effect of this fix is that the compileColumns query now appears in tools like debugbar. It may be a \"cosmetic issue\" only, but in the debugbar timeline those queries not only appear but seem to be a bit slower than the rest.",
"created_at": "2023-11-03T15:04:20Z"
}
],
"number": 48870,
"title": "PostgreSQL reserved word column names w/ guarded attributes broken in native column attributes implementation"
} | {
"body": "Fixes #48870\r\n\r\nThe solution was to unquote quoted reserved names on PostgreSQL processor, [the same approach is used on Doctrine DBAL](https://github.com/doctrine/dbal/blob/45941c67dd0505dab2fb970786d93055b7cbd2b6/src/Schema/AbstractAsset.php#L154-L169).\r\n\r\nThanks @crynobone and @damiantw for reporting the issue.",
"number": 48877,
"review_comments": [
{
"body": "isn't the issue was with `end` column?",
"created_at": "2023-11-01T10:31:34Z"
},
{
"body": "I brought 'end' back in a commit but The `analyze` is also a keyword on PostgreSQL: https://www.postgresql.org/docs/current/sql-keywords-appendix.html\r\nI removed 'end' because of unrelated MySQL 5.7 test failure when creating a table with 2 not null timestamp columns. \r\n",
"created_at": "2023-11-01T10:45:39Z"
}
],
"title": "[10.x] Fix postgreSQL reserved word column names w/ guarded attributes broken in native column attributes implementation"
} | {
"commits": [
{
"message": "unquote quoted names on postgresql"
},
{
"message": "add test"
},
{
"message": "fix mysql 5.7 error"
},
{
"message": "fix table prefixed twice"
},
{
"message": "revert removing 'end' keyword"
}
],
"files": [
{
"diff": "@@ -59,7 +59,7 @@ public function processColumns($results)\n $autoincrement = $result->default !== null && str_starts_with($result->default, 'nextval(');\n \n return [\n- 'name' => $result->name,\n+ 'name' => str_starts_with($result->name, '\"') ? str_replace('\"', '', $result->name) : $result->name,\n 'type_name' => $result->type_name,\n 'type' => $result->type,\n 'collation' => $result->collation,",
"filename": "src/Illuminate/Database/Query/Processors/PostgresProcessor.php",
"status": "modified"
},
{
"diff": "@@ -238,9 +238,9 @@ public function whenTableDoesntHaveColumn(string $table, string $column, Closure\n */\n public function getColumnType($table, $column, $fullDefinition = false)\n {\n- $table = $this->connection->getTablePrefix().$table;\n-\n if (! $this->connection->usingNativeSchemaOperations()) {\n+ $table = $this->connection->getTablePrefix().$table;\n+\n return $this->connection->getDoctrineColumn($table, $column)->getType()->getName();\n }\n ",
"filename": "src/Illuminate/Database/Schema/Builder.php",
"status": "modified"
},
{
"diff": "@@ -94,6 +94,38 @@ public function testDiscardChanges()\n $user->save();\n $this->assertFalse($user->wasChanged());\n }\n+\n+ public function testInsertRecordWithReservedWordFieldName()\n+ {\n+ Schema::create('actions', function (Blueprint $table) {\n+ $table->id();\n+ $table->string('label');\n+ $table->timestamp('start');\n+ $table->timestamp('end')->nullable();\n+ $table->boolean('analyze');\n+ });\n+\n+ $model = new class extends Model\n+ {\n+ protected $table = 'actions';\n+ protected $guarded = ['id'];\n+ public $timestamps = false;\n+ };\n+\n+ $model->newInstance()->create([\n+ 'label' => 'test',\n+ 'start' => '2023-01-01 00:00:00',\n+ 'end' => '2024-01-01 00:00:00',\n+ 'analyze' => true,\n+ ]);\n+\n+ $this->assertDatabaseHas('actions', [\n+ 'label' => 'test',\n+ 'start' => '2023-01-01 00:00:00',\n+ 'end' => '2024-01-01 00:00:00',\n+ 'analyze' => true,\n+ ]);\n+ }\n }\n \n class TestModel1 extends Model",
"filename": "tests/Integration/Database/EloquentModelTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.30.0\n\n### PHP Version\n\n8.2.11\n\n### Database Driver & Version\n\nPostgreSQL 15.1\n\n### Description\n\nThe native column attributes implementation introduced in https://github.com/laravel/framework/pull/48357 has broken inserts using Postgres models with guarded attributes and column names matching PostgreSQL reserved words in my application.\r\n\r\nThe [`compileColumns()`](https://github.com/laravel/framework/commit/85a514632e410ae8f90c2b32c79a2788ba9d1076#diff-653f90bd1ee0a1c7c7970912484e98c8bbd30c8e9a3d2f544d53834d54e7ce7cR104) query in the Postgres schema grammar makes use of PostgreSQL's `quote_ident()` function which quotes reserves words. \r\n\r\n`SELECT quote_ident('foo') as value;` -> `foo`\r\n`SELECT quote_ident('end') as value;` -> `\"end\"`\r\n\r\nThis is causing the [`GuardsAttributes`](https://github.com/laravel/framework/blob/10.x/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php#L218) trait to improperly detect fillable columns. \r\n\r\nChanging `select quote_ident(a.attname) as name` to `select a.attname as name` in the Postgres Grammar resolves the issue, but I'm not sure if there are other downstream consequences to that. \r\n\r\nEx:\r\n\r\nGiven a table like the following:\r\n\r\n```php\r\nSchema::create('my_table', function (Blueprint $table) {\r\n $table->id();\r\n $table->string('label');\r\n $table->timestamp('start');\r\n $table->timestamp('end');\r\n $table->boolean('analyze');\r\n});\r\n```\r\n\r\nThe output of `Schema::getColumns('my_table');` is the following.\r\n\r\n```php\r\narray:5 [\r\n 0 => array:8 [\r\n \"name\" => \"id\"\r\n \"type_name\" => \"int8\"\r\n \"type\" => \"bigint\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => true\r\n \"comment\" => null\r\n ]\r\n 1 => array:8 [\r\n \"name\" => \"label\"\r\n \"type_name\" => \"varchar\"\r\n \"type\" => \"character varying(255)\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n 2 => array:8 [\r\n \"name\" => \"start\"\r\n \"type_name\" => \"timestamp\"\r\n \"type\" => \"timestamp(0) without time zone\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n 3 => array:8 [\r\n \"name\" => \"\"end\"\"\r\n \"type_name\" => \"timestamp\"\r\n \"type\" => \"timestamp(0) without time zone\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n 4 => array:8 [\r\n \"name\" => \"\"analyze\"\"\r\n \"type_name\" => \"bool\"\r\n \"type\" => \"boolean\"\r\n \"collation\" => null\r\n \"nullable\" => false\r\n \"default\" => null\r\n \"auto_increment\" => false\r\n \"comment\" => null\r\n ]\r\n]\r\n```\n\n### Steps To Reproduce\n\n```php\r\nclass LaravelTest extends TestCase\r\n{\r\n public function testInsertRecordWithReservedWordFieldName()\r\n {\r\n Schema::create('my_table', function (Blueprint $table) {\r\n $table->id();\r\n $table->string('label');\r\n $table->timestamp('start');\r\n $table->timestamp('end');\r\n $table->boolean('analyze');\r\n });\r\n\r\n $model = new class extends \\Illuminate\\Database\\Eloquent\\Model {\r\n protected $table = 'my_table';\r\n protected $guarded = ['id'];\r\n public $timestamps = false;\r\n };\r\n \r\n $result = $model::query()->create([\r\n 'label' => 'test',\r\n 'start' => '2023-01-01 00:00:00',\r\n 'end' => '2024-01-01 00:00:00',\r\n 'analyze' => true,\r\n ]);\r\n\r\n $this->assertTrue($result->exists);\r\n }\r\n}\r\n```\r\n\r\nFails with error...\r\n\r\n```\r\nSQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"end\" of relation \"my_table\" violates not-null constraint\r\nDETAIL: Failing row contains (1, test, 2023-01-01 00:00:00, null, null). (Connection: pgsql, SQL: insert into \"my_table\" (\"label\", \"start\") values (test, 2023-01-01 00:00:00) returning \"id\")\r\n```\r\n\r\nPasses under Laravel 10.29.0.",
"comments": [
{
"body": "Seems like a side-effect of this fix is that the compileColumns query now appears in tools like debugbar. It may be a \"cosmetic issue\" only, but in the debugbar timeline those queries not only appear but seem to be a bit slower than the rest.",
"created_at": "2023-11-03T15:04:20Z"
}
],
"number": 48870,
"title": "PostgreSQL reserved word column names w/ guarded attributes broken in native column attributes implementation"
} | {
"body": "verify issue #48870\r\n",
"number": 48873,
"review_comments": [],
"title": "Regression Test for PostgreSQL reserved word column names w/ guarded attributes broken in native column attributes implementation"
} | {
"commits": [
{
"message": "Regression Test for PostgreSQL reserved word column names w/ guarded attributes broken in native column attributes implementation\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
}
],
"files": [
{
"diff": "@@ -0,0 +1,42 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database;\n+\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Support\\Facades\\Schema;\n+\n+class EloquentCreateTest extends DatabaseTestCase\n+{\n+ public function testInsertRecordWithReservedWordFieldName()\n+ {\n+ Schema::create('actions', function (Blueprint $table) {\n+ $table->id();\n+ $table->string('label');\n+ $table->timestamp('start');\n+ $table->timestamp('end');\n+ $table->boolean('analyze');\n+ });\n+\n+ $model = new class extends Model\n+ {\n+ protected $table = 'actions';\n+ protected $guarded = ['id'];\n+ public $timestamps = false;\n+ };\n+\n+ $result = $model->newInstance()->create([\n+ 'label' => 'test',\n+ 'start' => '2023-01-01 00:00:00',\n+ 'end' => '2024-01-01 00:00:00',\n+ 'analyze' => true,\n+ ]);\n+\n+ $this->assertDatabaseHas('actions', [\n+ 'label' => 'test',\n+ 'start' => '2023-01-01 00:00:00',\n+ 'end' => '2024-01-01 00:00:00',\n+ 'analyze' => true,\n+ ]);\n+ }\n+}",
"filename": "tests/Integration/Database/EloquentCreateTest.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.26.2\r\n\r\n### PHP Version\r\n\r\n8.1.24\r\n\r\n### Database Driver & Version\r\n\r\n_No response_\r\n\r\n### Description\r\n\r\nRecreating JSON request bodies was changed in v2.3.1 of `symfony/psr-http-message-bridge`.\r\n\r\nhttps://github.com/symfony/psr-http-message-bridge/commit/ef03b6dfb040da9615a11679306d707da7fee51f\r\n\r\nThe JSON request body is read using `$symfonyRequest->getContent()` instead of `$symfonyRequest->getPayload()->all()` in v2.3.0, and `$symfonyRequest->request->all()` in v2.2.0.\r\n\r\nBecause of this, the modifications made to a Laravel request object by the `ConvertEmptyStringsToNull` middleware gets lost, i.e. empty string values for JSON request keys are not converted to `null`, and remain as empty strings.\r\n\r\nThis only affects controller methods that have `$request` type hinted as `Psr\\Http\\Message\\ServerRequestInterface`.\r\n\r\n### Steps To Reproduce\r\n\r\n```shell\r\ncomposer create-project laravel/laravel=^10.0 example-app && cd example-app\r\n```\r\n\r\n```shell\r\ncomposer require laravel/framework=10.26.2\r\n```\r\n\r\n```\r\n{\r\n echo \"<?php\"\r\n echo\r\n echo \"namespace Tests\\Feature;\"\r\n echo\r\n echo \"use Tests\\TestCase;\"\r\n echo\r\n echo \"class ExampleTest extends TestCase\"\r\n echo \"{\"\r\n echo \" public function test_the_application_returns_a_successful_response(): void\"\r\n echo \" {\"\r\n echo \" \\$this->postJson('/', ['string' => ''])->assertExactJson(['string' => null]);\"\r\n echo \" }\"\r\n echo \"}\"\r\n} | tee tests/Feature/ExampleTest.php\r\n```\r\n\r\nTests should fail:\r\n\r\n```shell\r\nphp artisan test\r\n```\r\n\r\nIf we install the previous version:\r\n\r\n```shell\r\ncomposer require symfony/psr-http-message-bridge=2.3.0\r\n```\r\n\r\nWe should see the tests pass:\r\n\r\n```\r\nphp artisan test\r\n```",
"comments": [
{
"body": "I've created a PR to fix this. We can track it there: https://github.com/laravel/framework/pull/48696",
"created_at": "2023-10-11T03:25:54Z"
}
],
"number": 48626,
"title": "symfony/psr-http-message-bridge v2.3.1 loses the transformations of ConvertEmptyStringsToNull middleware"
} | {
"body": "There was a breaking change, for us, in `symfony/psr-http-message-bridge` (https://github.com/symfony/psr-http-message-bridge/pull/122) that means merged data for JSON requests is no longer added to the PSR request. \r\n\r\nThe original PR was a fix for a different Laravel issue (although I'm not entirely sure what as the issue tracker for that repo is no longer visible).\r\n\r\nfixes #48626",
"number": 48696,
"review_comments": [
{
"body": "`Request::getPayload` method is only available from `6.3`.",
"created_at": "2023-10-11T23:11:25Z"
},
{
"body": "The optional dependencies are required to run these tests.",
"created_at": "2023-10-11T23:11:48Z"
},
{
"body": "@timacdonald can we add these to `require-dev` instead please? Also, `nyholm/psr7` needs to be `^1.2` at minimum (see `suggest`).",
"created_at": "2023-10-12T10:25:32Z"
},
{
"body": "Done!",
"created_at": "2023-10-12T22:28:58Z"
}
],
"title": "[10.x] Allow creation of PSR request with merged data"
} | {
"commits": [
{
"message": "Allow creation of PSR request with merged data"
},
{
"message": "Add dependencies to require-dev"
}
],
"files": [
{
"diff": "@@ -44,7 +44,7 @@\n \"symfony/console\": \"^6.2\",\n \"symfony/error-handler\": \"^6.2\",\n \"symfony/finder\": \"^6.2\",\n- \"symfony/http-foundation\": \"^6.2\",\n+ \"symfony/http-foundation\": \"^6.3\",\n \"symfony/http-kernel\": \"^6.2\",\n \"symfony/mailer\": \"^6.2\",\n \"symfony/mime\": \"^6.2\",\n@@ -104,13 +104,15 @@\n \"league/flysystem-read-only\": \"^3.3\",\n \"league/flysystem-sftp-v3\": \"^3.0\",\n \"mockery/mockery\": \"^1.5.1\",\n+ \"nyholm/psr7\": \"^1.2\",\n \"orchestra/testbench-core\": \"^8.12\",\n \"pda/pheanstalk\": \"^4.0\",\n \"phpstan/phpstan\": \"^1.4.7\",\n \"phpunit/phpunit\": \"^10.0.7\",\n \"predis/predis\": \"^2.0.2\",\n \"symfony/cache\": \"^6.2\",\n- \"symfony/http-client\": \"^6.2.4\"\n+ \"symfony/http-client\": \"^6.2.4\",\n+ \"symfony/psr-http-message-bridge\": \"^2.0\"\n },\n \"provide\": {\n \"psr/container-implementation\": \"1.1|2.0\",",
"filename": "composer.json",
"status": "modified"
},
{
"diff": "@@ -137,8 +137,10 @@ protected function registerPsrRequest()\n if (class_exists(Psr17Factory::class) && class_exists(PsrHttpFactory::class)) {\n $psr17Factory = new Psr17Factory;\n \n- return (new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory))\n- ->createRequest($app->make('request'));\n+ return with((new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory))\n+ ->createRequest($illuminateRequest = $app->make('request')), fn ($request) => $request->withParsedBody(\n+ array_merge($request->getParsedBody(), $illuminateRequest->getPayload()->all())\n+ ));\n }\n \n throw new BindingResolutionException('Unable to resolve PSR request. Please install the symfony/psr-http-message-bridge and nyholm/psr7 packages.');",
"filename": "src/Illuminate/Routing/RoutingServiceProvider.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,109 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Foundation;\n+\n+use Illuminate\\Http\\Request;\n+use Illuminate\\Support\\Facades\\Route;\n+use Orchestra\\Testbench\\TestCase;\n+use Psr\\Http\\Message\\ServerRequestInterface;\n+\n+class RoutingServiceProviderTest extends TestCase\n+{\n+ public function testItIncludesMergedDataInServerRequestInterfaceInstancesUsingGetRequests()\n+ {\n+ Route::get('test-route', function (ServerRequestInterface $request) {\n+ return $request->getParsedBody();\n+ })->middleware(MergeDataMiddleware::class);\n+\n+ $response = $this->withoutExceptionHandling()->get('test-route?'.http_build_query([\n+ 'sent' => 'sent-data',\n+ 'overridden' => 'overriden-sent-data',\n+ ]));\n+\n+ $response->assertOk();\n+ $response->assertExactJson([\n+ 'request-data' => 'request-data',\n+ ]);\n+ }\n+\n+ public function testItIncludesMergedDataInServerRequestInterfaceInstancesUsingGetJsonRequests()\n+ {\n+ Route::get('test-route', function (ServerRequestInterface $request) {\n+ return $request->getParsedBody();\n+ })->middleware(MergeDataMiddleware::class);\n+\n+ $response = $this->getJson('test-route?'.http_build_query([\n+ 'sent' => 'sent-data',\n+ 'overridden' => 'overriden-sent-data',\n+ ]));\n+\n+ $response->assertOk();\n+ $response->assertExactJson([\n+ 'json-data' => 'json-data',\n+ 'merged' => 'replaced-merged-data',\n+ 'overridden' => 'overriden-merged-data',\n+ 'request-data' => 'request-data',\n+ ]);\n+ }\n+\n+ public function testItIncludesMergedDataInServerRequestInterfaceInstancesUsingPostRequests()\n+ {\n+ Route::post('test-route', function (ServerRequestInterface $request) {\n+ return $request->getParsedBody();\n+ })->middleware(MergeDataMiddleware::class);\n+\n+ $response = $this->post('test-route', [\n+ 'sent' => 'sent-data',\n+ 'overridden' => 'overriden-sent-data',\n+ ]);\n+\n+ $response->assertOk();\n+ $response->assertExactJson([\n+ 'sent' => 'sent-data',\n+ 'merged' => 'replaced-merged-data',\n+ 'overridden' => 'overriden-merged-data',\n+ 'request-data' => 'request-data',\n+ ]);\n+ }\n+\n+ public function testItIncludesMergedDataInServerRequestInterfaceInstancesUsingPostJsonRequests()\n+ {\n+ Route::post('test-route', function (ServerRequestInterface $request) {\n+ return $request->getParsedBody();\n+ })->middleware(MergeDataMiddleware::class);\n+\n+ $response = $this->postJson('test-route', [\n+ 'sent' => 'sent-data',\n+ 'overridden' => 'overriden-sent-data',\n+ ]);\n+\n+ $response->assertOk();\n+ $response->assertExactJson([\n+ 'json-data' => 'json-data',\n+ 'sent' => 'sent-data',\n+ 'merged' => 'replaced-merged-data',\n+ 'overridden' => 'overriden-merged-data',\n+ 'request-data' => 'request-data',\n+ ]);\n+ }\n+}\n+\n+class MergeDataMiddleware\n+{\n+ public function handle(Request $request, $next)\n+ {\n+ $request->merge(['merged' => 'first-merged-data']);\n+\n+ $request->merge(['merged' => 'replaced-merged-data']);\n+\n+ $request->merge(['overridden' => 'overriden-merged-data']);\n+\n+ $request->request->set('request-data', 'request-data');\n+\n+ $request->query->set('query-data', 'query-data');\n+\n+ $request->json()->set('json-data', 'json-data');\n+\n+ return $next($request);\n+ }\n+}",
"filename": "tests/Integration/Foundation/RoutingServiceProviderTest.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\n\n10.22.0\n\n### PHP Version\n\n8.2.10\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nActually, the helper Str::password() does not always generate password containing numbers.\n\n### Steps To Reproduce\n\nSimply use Pest as it allows to repeat a test, creating a password using Str::password() with default parameters:\r\n\r\n```php\r\ntest('generate password', function () {\r\n $password = \\Illuminate\\Support\\Str::password(\r\n length: 32,\r\n letters: true,\r\n numbers: true,\r\n symbols: true,\r\n spaces: false,\r\n );\r\n expect(\r\n str($password)->contains(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']))\r\n ->toBeTrue();\r\n}\r\n)->repeat(100);\r\n```",
"comments": [
{
"body": "IMO, it is not a bug.\r\n\r\nThe parameters refer to allowed character's categories that MAY be on the generated password.\r\n\r\nNowhere in the documentation, it states those categories MUST be on the output.\r\n\r\nnote: MAY and MUST are in caps, like in RFC vocabulary, not like a rant\r\n",
"created_at": "2023-10-09T21:51:19Z"
},
{
"body": "While this may not be considered a bug, if we rely on `Str::password()` to generate a secure password and use the same logic for password validation, the provided password will fail if it's expected to contain symbols but doesn't have one because `Str::password()` **MAY** contain symbol instead of **MUST** contain symbol.",
"created_at": "2023-10-10T00:49:14Z"
}
],
"number": 48677,
"title": "Str::password() does not always generate password with numbers"
} | {
"body": "fixes #48677\r\n\r\nIf we rely on `Str::password()` to generate a secure password and use the same logic for password validation, the provided password will fail if it's expected to contain symbols but doesn't have one because `Str::password()` **MAY** contain symbol instead of **MUST** contain symbol. \r\n\r\nThe expected behavior should be `Str::password(letters: true, numbers: true)` should indicate that the password **MUST** contain letters and numbers.",
"number": 48681,
"review_comments": [
{
"body": "It seems to be sufficient to determine if a value is true or not:\r\n\r\n```suggestion\r\n $options = (new Collection([\r\n 'letters' => $letters ? [\r\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\r\n 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\r\n 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',\r\n 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',\r\n 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\r\n ] : null,\r\n 'numbers' => $numbers ? [\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n ] : null,\r\n 'symbols' => $symbols ? [\r\n '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',\r\n '_', '.', ',', '<', '>', '?', '/', '\\\\', '{', '}', '[',\r\n ']', '|', ':', ';',\r\n ] : null,\r\n 'spaces' => $spaces ? [' '] : null,\r\n```\r\n\r\nSince there is no native PHP type declaration, it is safer to treat all truthy values as true.",
"created_at": "2023-10-10T08:02:05Z"
},
{
"body": "but the parameter isn't typehinted as `bool`",
"created_at": "2023-10-10T08:06:11Z"
},
{
"body": "> but the parameter isn't typehinted as `bool`\r\n\r\nYes, I rather think so, which is **why `=== true` should be omitted**. For example, if you pass `(int)1` here, I think it should be handled as `true` because it is a truthy value.\r\n\r\nIn a situation where either `true` or `false` is determined, it seems somewhat unnatural that all truthy values other than `true` would be `false`. It would be also consistent in the case of adopting a native PHP type constraint, where `1` would be cast to `true` at the start of function execution.\r\n\r\n----\r\n\r\nIf we move to using native type constraints somewhere in the roadmap, using `=== true` at this stage would be a breaking change.\r\n\r\nhttps://3v4l.org/buI6E",
"created_at": "2023-10-10T08:16:47Z"
},
{
"body": "https://github.com/laravel/framework/blob/09137f50f715c1efc649788a26092dcb1ec4ab6e/src/Illuminate/Support/Str.php#L842\r\n\r\nWhat's your expectation with without `=== true` and the following example:\r\n\r\n```php\r\nStr::password(numbers: 'nah');\r\n```",
"created_at": "2023-10-10T13:24:01Z"
},
{
"body": "`Str::password(numbers: 'nah');` should be `Str::password(numbers: true);` because PHP treats `\"nah\"` as truthy. The important thing is that **we should follow the interpretation of the PHP standard, not determine \"what should be true\" at the the framework.**\r\n\r\nYou would be correct if Laravel were to adopt the rule of always treating truthy values other than `true` as `false`, but it is not actually happened so far. I don't think there is a lot of code that judges `=== true` for something received with `@param bool $arg`, so I think that needs to be consistent throughout the framework.\r\n\r\n",
"created_at": "2023-10-10T13:38:41Z"
},
{
"body": "> You would be correct if Laravel were to adopt the rule of always treating truthy values other than true as false, but it is not actually happened so far\r\n\r\nI would disagree https://github.com/search?q=repo%3Alaravel%2Fframework%20%3D%3D%3D%20true&type=code",
"created_at": "2023-10-10T14:13:53Z"
},
{
"body": "@crynobone I see, that is certainly the case in some codes. But apparently it is not consistent across the board. Somewhat confused.\r\n\r\n- https://github.com/search?q=repo%3Alaravel%2Fframework+path%3A*.php+%2F%5C%24%5Cw%2B+%5C%3F%2F+AND+%2F%40param%5Cs%2Bbool%5Cs%2B%2F&type=code\r\n- https://github.com/search?q=repo%3Alaravel%2Fframework+path%3A*.php+%2Fif+%5C%28%5C%24%5Cw%2B%5C%29%2F+AND+%2F%40param%5Cs%2Bbool%5Cs%2B%2F&type=code\r\n\r\nFor the moment, I see that there seems to be no need to discuss this excessively here. I think this has been an off-topic discussion, but thank you for your patience.",
"created_at": "2023-10-10T14:36:05Z"
}
],
"title": "[10.x] Fixes `Str::password()` does not always generate password with numbers"
} | {
"commits": [
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "formatting"
},
{
"message": "Apply fixes from StyleCI"
}
],
"files": [
{
"diff": "@@ -841,25 +841,33 @@ public static function pluralStudly($value, $count = 2)\n */\n public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false)\n {\n- return (new Collection)\n- ->when($letters, fn ($c) => $c->merge([\n- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\n- 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n- 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',\n- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',\n- 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n- ]))\n- ->when($numbers, fn ($c) => $c->merge([\n- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n- ]))\n- ->when($symbols, fn ($c) => $c->merge([\n- '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',\n- '_', '.', ',', '<', '>', '?', '/', '\\\\', '{', '}', '[',\n- ']', '|', ':', ';',\n- ]))\n- ->when($spaces, fn ($c) => $c->merge([' ']))\n- ->pipe(fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)]))\n- ->implode('');\n+ $password = new Collection();\n+\n+ $options = (new Collection([\n+ 'letters' => $letters === true ? [\n+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\n+ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n+ 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',\n+ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',\n+ 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n+ ] : null,\n+ 'numbers' => $numbers === true ? [\n+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n+ ] : null,\n+ 'symbols' => $symbols === true ? [\n+ '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',\n+ '_', '.', ',', '<', '>', '?', '/', '\\\\', '{', '}', '[',\n+ ']', '|', ':', ';',\n+ ] : null,\n+ 'spaces' => $spaces === true ? [' '] : null,\n+ ]))->filter()->each(fn ($c) => $password->push($c[random_int(0, count($c) - 1)])\n+ )->flatten();\n+\n+ $length = $length - $password->count();\n+\n+ return $password->merge($options->pipe(\n+ fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)])\n+ ))->shuffle()->implode('');\n }\n \n /**",
"filename": "src/Illuminate/Support/Str.php",
"status": "modified"
},
{
"diff": "@@ -1288,6 +1288,13 @@ public function testItCanSpecifyAFallbackForAUlidSequence()\n public function testPasswordCreation()\n {\n $this->assertTrue(strlen(Str::password()) === 32);\n+\n+ $this->assertStringNotContainsString(' ', Str::password());\n+ $this->assertStringContainsString(' ', Str::password(spaces: true));\n+\n+ $this->assertTrue(\n+ Str::of(Str::password())->contains(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])\n+ );\n }\n }\n ",
"filename": "tests/Support/SupportStrTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.25.2 & 10.25.1\n\n### PHP Version\n\n8.2.10\n\n### Database Driver & Version\n\nPostgreSQL\n\n### Description\n\nThe project I am working on uses nested transactions and they used to work flawlesly however I've updated laravel framework from version 10.25.0 to 10.25.2 and now I keep getting errors:\r\n`PDOException: SQLSTATE[25P01]: No active sql transaction: 7 ERROR: SAVEPOINT can only be used in transaction blocks in /var/www/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:159`\r\n\r\nI reverted back to v10.25.0 and the problem has gone away, then changed to v10.25.1 and problem re-appeared.\r\n\r\nI then looked into the changes in vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php and it turned out that if I revert logic of this trait back to [https://github.com/laravel/framework/blob/4b5ef9e96e15eff8b1a8f848419feba8dc0be50f/src/Illuminate/Database/Concerns/ManagesTransactions.php](url) then issue vanished as well.\r\n\r\nPlease see below steps to reproduce and let me know if anything is unclear.\r\n\r\nFYI (I hope you don't mid) : @mpyw, @tonysm @crynobone \n\n### Steps To Reproduce\n\nStep 1 - below code is executed, however ActionQueue \"created\" event is observerd. ActionQueue observer has got `$afterCommit` set to true.\r\n\r\n```\r\n DB::transaction(function () {\r\n $actionQueue = new ActionQueue([\r\n 'action_id' => Action::TEST->actionId(),\r\n 'delay' => 0,\r\n 'payload' => ['data' => 'test'],\r\n ]);\r\n $actionQueue->save();\r\n });\r\n```\r\n\r\nStep2 - in ActionQueue observer I dispatch below job using dispatchSync() method.\r\n\r\n```\r\n<?php\r\n\r\nnamespace App\\Jobs;\r\n\r\nuse App\\Models\\ActionNote;\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Queue\\InteractsWithQueue;\r\nuse Illuminate\\Queue\\SerializesModels;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Spatie\\InteractsWithPayload\\Concerns\\InteractsWithPayload;\r\n\r\nclass Test implements ShouldQueue\r\n{\r\n use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, InteractsWithPayload;\r\n\r\n public function handle(): void\r\n {\r\n DB::transaction(function () {\r\n $note = new ActionNote(['note' => mt_rand(1, 10)]);\r\n return $note->save();\r\n });\r\n }\r\n}\r\n```\r\n\r\nThis is when I get error:\r\n\r\nSQLSTATE[25P01]: No active sql transaction: 7 ERROR: SAVEPOINT can only be used in transaction blocks\r\n\r\n",
"comments": [
{
"body": "I was able to reproduce this. The issue seems to be with `$afterCommit` and `dispatchSync`... I didn't have much time to dig in, but I created a sample test. With this code in my `routes/web.php` file I was able to reproduce it on latest Laravel:\r\n\r\n<details>\r\n<summary>routes/web.php</summary>\r\n\r\n```php\r\n<?php\r\n\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Notifications\\Notifiable;\r\nuse Illuminate\\Queue\\InteractsWithQueue;\r\nuse Illuminate\\Queue\\SerializesModels;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Illuminate\\Support\\Facades\\Route;\r\nuse Laravel\\Sanctum\\HasApiTokens;\r\n\r\nclass User extends Authenticatable\r\n{\r\n use HasApiTokens, HasFactory, Notifiable;\r\n\r\n /**\r\n * The attributes that are mass assignable.\r\n *\r\n * @var array<int, string>\r\n */\r\n protected $fillable = [\r\n 'name',\r\n 'email',\r\n 'password',\r\n ];\r\n\r\n /**\r\n * The attributes that should be hidden for serialization.\r\n *\r\n * @var array<int, string>\r\n */\r\n protected $hidden = [\r\n 'password',\r\n 'remember_token',\r\n ];\r\n\r\n /**\r\n * The attributes that should be cast.\r\n *\r\n * @var array<string, string>\r\n */\r\n protected $casts = [\r\n 'email_verified_at' => 'datetime',\r\n 'password' => 'hashed',\r\n ];\r\n}\r\n\r\nclass UserObserver\r\n{\r\n public $afterCommit = true;\r\n\r\n public function created(User $user)\r\n {\r\n logger('[observer] before dispatching the job');\r\n\r\n LogUserCreation::dispatchSync($user);\r\n\r\n logger('[observer] after dispatching job');\r\n }\r\n}\r\n\r\nUser::observe(UserObserver::class);\r\n\r\nclass LogUserCreation implements ShouldQueue\r\n{\r\n use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;\r\n\r\n public function __construct(public User $user)\r\n {\r\n }\r\n\r\n public function handle(): void\r\n {\r\n DB::transaction(function () {\r\n logger('[job] before updating user');\r\n\r\n $this->user->update(['name' => 'changed']);\r\n\r\n logger('[job] after updating user but before transaction commits');\r\n });\r\n\r\n logger('[job] after transaction committed...');\r\n }\r\n}\r\n\r\nRoute::get('/', function () {\r\n DB::transaction(function () {\r\n logger('[request] before creating the user (level 1)');\r\n\r\n DB::transaction(function () {\r\n logger('[request] before creating the user (level 2)');\r\n\r\n $user = User::make(User::factory()->raw());\r\n $user->save();\r\n\r\n logger('[request] after creating the user, but before transaction (level 2)');\r\n });\r\n\r\n logger('[request] after creating the user, but before transaction (level 1)');\r\n });\r\n\r\n return view('welcome');\r\n});\r\n\r\n```\r\n\r\n</details>\r\n\r\nIt looks like when the transaction inside the job tries to begin, it \"thinks\" there's an open transaction running...",
"created_at": "2023-10-06T17:50:28Z"
},
{
"body": "I'll try to dig in deeper this weekend, but if anyone wants to take it over, feel free (I'm at a conference today and tomorrow, so don't have that much time available).",
"created_at": "2023-10-06T17:52:14Z"
},
{
"body": "~Somehow I can't reproduct it with v10.25.1 in my environment...~\r\n\r\nConfirmed. \r\n\r\n```\r\n[2023-10-06 18:24:25] local.DEBUG: creating real transaction \r\n[2023-10-06 18:24:25] local.DEBUG: [request] before creating the user (level 1) \r\n[2023-10-06 18:24:25] local.DEBUG: creating savepoint \r\n[2023-10-06 18:24:25] local.DEBUG: [request] before creating the user (level 2) \r\n[2023-10-06 18:24:25] local.DEBUG: [request] after creating the user, but before transaction (level 2) \r\n[2023-10-06 18:24:25] local.DEBUG: [request] after creating the user, but before transaction (level 1) \r\n[2023-10-06 18:24:25] local.DEBUG: [observer] before dispatching the job \r\n[2023-10-06 18:24:25] local.DEBUG: creating savepoint <--- !!!\r\n[2023-10-06 18:24:25] local.DEBUG: [job] before updating user \r\n[2023-10-06 18:24:25] local.DEBUG: [job] after updating user but before transaction commits \r\n[2023-10-06 18:24:25] local.DEBUG: [job] after transaction committed... \r\n[2023-10-06 18:24:25] local.DEBUG: [observer] after dispatching job \r\n\r\n```",
"created_at": "2023-10-06T18:17:16Z"
},
{
"body": "Probably the following block causing problems.\r\n\r\n```php\r\ntry {\r\n if ($this->transactions == 1) {\r\n $this->fireConnectionEvent('committing');\r\n $this->getPdo()->commit();\r\n }\r\n\r\n if ($this->afterCommitCallbacksShouldBeExecuted()) {\r\n $this->transactionsManager?->commit($this->getName());\r\n }\r\n} catch (Throwable $e) {\r\n $this->handleCommitTransactionException(\r\n $e, $currentAttempt, $attempts\r\n );\r\n\r\n continue;\r\n} finally {\r\n $this->transactions = max(0, $this->transactions - 1);\r\n}\r\n```\r\n\r\nIt might be like:\r\n\r\n```diff\r\n+$decreaseLevel = function (): void {\r\n+ static $applied = false;\r\n+ if ($applied) {\r\n+ return;\r\n+ }\r\n+ $this->transactions = max(0, $this->transactions - 1);\r\n+ $applied = true;\r\n+};\r\n \r\n try {\r\n if ($this->transactions == 1) {\r\n $this->fireConnectionEvent('committing');\r\n $this->getPdo()->commit();\r\n }\r\n+\r\n+ $decreaseLevel();\r\n \r\n if ($this->afterCommitCallbacksShouldBeExecuted()) {\r\n $this->transactionsManager?->commit($this->getName());\r\n }\r\n } catch (Throwable $e) {\r\n $this->handleCommitTransactionException(\r\n $e, $currentAttempt, $attempts\r\n );\r\n \r\n continue;\r\n } finally {\r\n- $this->transactions = max(0, $this->transactions - 1);\r\n+ $decreaseLevel();\r\n }\r\n```",
"created_at": "2023-10-06T18:36:42Z"
},
{
"body": "@crynobone I think the three methods `trasaction()` `commit()` `rollback()` should be reviewed at the same time, since the order of level decreasing and callback executions must be consistent.",
"created_at": "2023-10-06T18:48:25Z"
},
{
"body": "Also this seems to be PostgreSQL specific, not reproducible on SQLite. SQLite probably ignores `SAVEPOINT` calls outside of transactions.",
"created_at": "2023-10-06T18:51:33Z"
},
{
"body": "Thank you for getting involved and I am really pleased that you were able to reproduce the issue.",
"created_at": "2023-10-06T19:24:34Z"
},
{
"body": "Hey @crynobone we may need to revert that change to transactions, this looks a bit serious for apps using transactions. I won't have time to dig into it until Sunday 😔",
"created_at": "2023-10-06T21:54:56Z"
},
{
"body": "We already tested the code using `DatabaseMigration` trait which uses the default Laravel Transaction Manager without any issue (and tested with Postgres), should add failing tests example https://github.com/laravel/framework/blob/10.x/tests/Integration/Database/EloquentTransactionWithAfterCommitTests.php",
"created_at": "2023-10-06T22:52:19Z"
}
],
"number": 48658,
"title": "SQLSTATE[25P01]: No active sql transaction: 7 ERROR: SAVEPOINT can only be used in transaction blocks error when using $afterCommit = true;"
} | {
"body": "Reproduce failing tests for #48658",
"number": 48670,
"review_comments": [],
"title": "Failing Tests for #48658"
} | {
"commits": [
{
"message": "[10.x] Test Improvements\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
}
],
"files": [
{
"diff": "@@ -2,7 +2,11 @@\n \n namespace Illuminate\\Tests\\Integration\\Database;\n \n+use Illuminate\\Bus\\Queueable;\n+use Illuminate\\Contracts\\Queue\\ShouldQueue;\n use Illuminate\\Foundation\\Auth\\User;\n+use Illuminate\\Foundation\\Bus\\Dispatchable;\n+use Illuminate\\Queue\\InteractsWithQueue;\n use Illuminate\\Support\\Facades\\DB;\n use Orchestra\\Testbench\\Concerns\\WithLaravelMigrations;\n use Orchestra\\Testbench\\Factories\\UserFactory;\n@@ -41,6 +45,21 @@ public function testObserverCalledWithAfterCommitWhenInsideTransaction()\n $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n }\n \n+ public function testObserverCalledWithAfterCommitWhenInsideTransactionWithDispatchSync()\n+ {\n+ User::observe($observer = EloquentTransactionWithAfterCommitTestsUserObserverUsingDispatchSync::resetting());\n+\n+ $user1 = DB::transaction(fn () => User::create(UserFactory::new()->raw()));\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+\n+ $this->assertDatabaseHas('password_reset_tokens', [\n+ 'email' => $user1->email,\n+ 'token' => sha1($user1->email),\n+ ]);\n+ }\n+\n public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepoint()\n {\n User::observe($observer = EloquentTransactionWithAfterCommitTestsUserObserver::resetting());\n@@ -102,3 +121,32 @@ public function created($user)\n static::$calledTimes++;\n }\n }\n+\n+class EloquentTransactionWithAfterCommitTestsUserObserverUsingDispatchSync extends EloquentTransactionWithAfterCommitTestsUserObserver\n+{\n+ public function created($user)\n+ {\n+ dispatch_sync(new EloquentTransactionWithAfterCommitTestsJob($user->email));\n+\n+ parent::created($user);\n+ }\n+}\n+\n+class EloquentTransactionWithAfterCommitTestsJob implements ShouldQueue\n+{\n+ use Dispatchable, InteractsWithQueue, Queueable;\n+\n+ public function __construct(public string $email)\n+ {\n+ // ...\n+ }\n+\n+ public function handle(): void\n+ {\n+ DB::transaction(function () {\n+ DB::table('password_reset_tokens')->insert([\n+ ['email' => $this->email, 'token' => sha1($this->email), 'created_at' => now()],\n+ ]);\n+ });\n+ }\n+}",
"filename": "tests/Integration/Database/EloquentTransactionWithAfterCommitTests.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.25.2 & 10.25.1\n\n### PHP Version\n\n8.2.10\n\n### Database Driver & Version\n\nPostgreSQL\n\n### Description\n\nThe project I am working on uses nested transactions and they used to work flawlesly however I've updated laravel framework from version 10.25.0 to 10.25.2 and now I keep getting errors:\r\n`PDOException: SQLSTATE[25P01]: No active sql transaction: 7 ERROR: SAVEPOINT can only be used in transaction blocks in /var/www/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:159`\r\n\r\nI reverted back to v10.25.0 and the problem has gone away, then changed to v10.25.1 and problem re-appeared.\r\n\r\nI then looked into the changes in vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php and it turned out that if I revert logic of this trait back to [https://github.com/laravel/framework/blob/4b5ef9e96e15eff8b1a8f848419feba8dc0be50f/src/Illuminate/Database/Concerns/ManagesTransactions.php](url) then issue vanished as well.\r\n\r\nPlease see below steps to reproduce and let me know if anything is unclear.\r\n\r\nFYI (I hope you don't mid) : @mpyw, @tonysm @crynobone \n\n### Steps To Reproduce\n\nStep 1 - below code is executed, however ActionQueue \"created\" event is observerd. ActionQueue observer has got `$afterCommit` set to true.\r\n\r\n```\r\n DB::transaction(function () {\r\n $actionQueue = new ActionQueue([\r\n 'action_id' => Action::TEST->actionId(),\r\n 'delay' => 0,\r\n 'payload' => ['data' => 'test'],\r\n ]);\r\n $actionQueue->save();\r\n });\r\n```\r\n\r\nStep2 - in ActionQueue observer I dispatch below job using dispatchSync() method.\r\n\r\n```\r\n<?php\r\n\r\nnamespace App\\Jobs;\r\n\r\nuse App\\Models\\ActionNote;\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Queue\\InteractsWithQueue;\r\nuse Illuminate\\Queue\\SerializesModels;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Spatie\\InteractsWithPayload\\Concerns\\InteractsWithPayload;\r\n\r\nclass Test implements ShouldQueue\r\n{\r\n use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, InteractsWithPayload;\r\n\r\n public function handle(): void\r\n {\r\n DB::transaction(function () {\r\n $note = new ActionNote(['note' => mt_rand(1, 10)]);\r\n return $note->save();\r\n });\r\n }\r\n}\r\n```\r\n\r\nThis is when I get error:\r\n\r\nSQLSTATE[25P01]: No active sql transaction: 7 ERROR: SAVEPOINT can only be used in transaction blocks\r\n\r\n",
"comments": [
{
"body": "I was able to reproduce this. The issue seems to be with `$afterCommit` and `dispatchSync`... I didn't have much time to dig in, but I created a sample test. With this code in my `routes/web.php` file I was able to reproduce it on latest Laravel:\r\n\r\n<details>\r\n<summary>routes/web.php</summary>\r\n\r\n```php\r\n<?php\r\n\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Notifications\\Notifiable;\r\nuse Illuminate\\Queue\\InteractsWithQueue;\r\nuse Illuminate\\Queue\\SerializesModels;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Illuminate\\Support\\Facades\\Route;\r\nuse Laravel\\Sanctum\\HasApiTokens;\r\n\r\nclass User extends Authenticatable\r\n{\r\n use HasApiTokens, HasFactory, Notifiable;\r\n\r\n /**\r\n * The attributes that are mass assignable.\r\n *\r\n * @var array<int, string>\r\n */\r\n protected $fillable = [\r\n 'name',\r\n 'email',\r\n 'password',\r\n ];\r\n\r\n /**\r\n * The attributes that should be hidden for serialization.\r\n *\r\n * @var array<int, string>\r\n */\r\n protected $hidden = [\r\n 'password',\r\n 'remember_token',\r\n ];\r\n\r\n /**\r\n * The attributes that should be cast.\r\n *\r\n * @var array<string, string>\r\n */\r\n protected $casts = [\r\n 'email_verified_at' => 'datetime',\r\n 'password' => 'hashed',\r\n ];\r\n}\r\n\r\nclass UserObserver\r\n{\r\n public $afterCommit = true;\r\n\r\n public function created(User $user)\r\n {\r\n logger('[observer] before dispatching the job');\r\n\r\n LogUserCreation::dispatchSync($user);\r\n\r\n logger('[observer] after dispatching job');\r\n }\r\n}\r\n\r\nUser::observe(UserObserver::class);\r\n\r\nclass LogUserCreation implements ShouldQueue\r\n{\r\n use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;\r\n\r\n public function __construct(public User $user)\r\n {\r\n }\r\n\r\n public function handle(): void\r\n {\r\n DB::transaction(function () {\r\n logger('[job] before updating user');\r\n\r\n $this->user->update(['name' => 'changed']);\r\n\r\n logger('[job] after updating user but before transaction commits');\r\n });\r\n\r\n logger('[job] after transaction committed...');\r\n }\r\n}\r\n\r\nRoute::get('/', function () {\r\n DB::transaction(function () {\r\n logger('[request] before creating the user (level 1)');\r\n\r\n DB::transaction(function () {\r\n logger('[request] before creating the user (level 2)');\r\n\r\n $user = User::make(User::factory()->raw());\r\n $user->save();\r\n\r\n logger('[request] after creating the user, but before transaction (level 2)');\r\n });\r\n\r\n logger('[request] after creating the user, but before transaction (level 1)');\r\n });\r\n\r\n return view('welcome');\r\n});\r\n\r\n```\r\n\r\n</details>\r\n\r\nIt looks like when the transaction inside the job tries to begin, it \"thinks\" there's an open transaction running...",
"created_at": "2023-10-06T17:50:28Z"
},
{
"body": "I'll try to dig in deeper this weekend, but if anyone wants to take it over, feel free (I'm at a conference today and tomorrow, so don't have that much time available).",
"created_at": "2023-10-06T17:52:14Z"
},
{
"body": "~Somehow I can't reproduct it with v10.25.1 in my environment...~\r\n\r\nConfirmed. \r\n\r\n```\r\n[2023-10-06 18:24:25] local.DEBUG: creating real transaction \r\n[2023-10-06 18:24:25] local.DEBUG: [request] before creating the user (level 1) \r\n[2023-10-06 18:24:25] local.DEBUG: creating savepoint \r\n[2023-10-06 18:24:25] local.DEBUG: [request] before creating the user (level 2) \r\n[2023-10-06 18:24:25] local.DEBUG: [request] after creating the user, but before transaction (level 2) \r\n[2023-10-06 18:24:25] local.DEBUG: [request] after creating the user, but before transaction (level 1) \r\n[2023-10-06 18:24:25] local.DEBUG: [observer] before dispatching the job \r\n[2023-10-06 18:24:25] local.DEBUG: creating savepoint <--- !!!\r\n[2023-10-06 18:24:25] local.DEBUG: [job] before updating user \r\n[2023-10-06 18:24:25] local.DEBUG: [job] after updating user but before transaction commits \r\n[2023-10-06 18:24:25] local.DEBUG: [job] after transaction committed... \r\n[2023-10-06 18:24:25] local.DEBUG: [observer] after dispatching job \r\n\r\n```",
"created_at": "2023-10-06T18:17:16Z"
},
{
"body": "Probably the following block causing problems.\r\n\r\n```php\r\ntry {\r\n if ($this->transactions == 1) {\r\n $this->fireConnectionEvent('committing');\r\n $this->getPdo()->commit();\r\n }\r\n\r\n if ($this->afterCommitCallbacksShouldBeExecuted()) {\r\n $this->transactionsManager?->commit($this->getName());\r\n }\r\n} catch (Throwable $e) {\r\n $this->handleCommitTransactionException(\r\n $e, $currentAttempt, $attempts\r\n );\r\n\r\n continue;\r\n} finally {\r\n $this->transactions = max(0, $this->transactions - 1);\r\n}\r\n```\r\n\r\nIt might be like:\r\n\r\n```diff\r\n+$decreaseLevel = function (): void {\r\n+ static $applied = false;\r\n+ if ($applied) {\r\n+ return;\r\n+ }\r\n+ $this->transactions = max(0, $this->transactions - 1);\r\n+ $applied = true;\r\n+};\r\n \r\n try {\r\n if ($this->transactions == 1) {\r\n $this->fireConnectionEvent('committing');\r\n $this->getPdo()->commit();\r\n }\r\n+\r\n+ $decreaseLevel();\r\n \r\n if ($this->afterCommitCallbacksShouldBeExecuted()) {\r\n $this->transactionsManager?->commit($this->getName());\r\n }\r\n } catch (Throwable $e) {\r\n $this->handleCommitTransactionException(\r\n $e, $currentAttempt, $attempts\r\n );\r\n \r\n continue;\r\n } finally {\r\n- $this->transactions = max(0, $this->transactions - 1);\r\n+ $decreaseLevel();\r\n }\r\n```",
"created_at": "2023-10-06T18:36:42Z"
},
{
"body": "@crynobone I think the three methods `trasaction()` `commit()` `rollback()` should be reviewed at the same time, since the order of level decreasing and callback executions must be consistent.",
"created_at": "2023-10-06T18:48:25Z"
},
{
"body": "Also this seems to be PostgreSQL specific, not reproducible on SQLite. SQLite probably ignores `SAVEPOINT` calls outside of transactions.",
"created_at": "2023-10-06T18:51:33Z"
},
{
"body": "Thank you for getting involved and I am really pleased that you were able to reproduce the issue.",
"created_at": "2023-10-06T19:24:34Z"
},
{
"body": "Hey @crynobone we may need to revert that change to transactions, this looks a bit serious for apps using transactions. I won't have time to dig into it until Sunday 😔",
"created_at": "2023-10-06T21:54:56Z"
},
{
"body": "We already tested the code using `DatabaseMigration` trait which uses the default Laravel Transaction Manager without any issue (and tested with Postgres), should add failing tests example https://github.com/laravel/framework/blob/10.x/tests/Integration/Database/EloquentTransactionWithAfterCommitTests.php",
"created_at": "2023-10-06T22:52:19Z"
}
],
"number": 48658,
"title": "SQLSTATE[25P01]: No active sql transaction: 7 ERROR: SAVEPOINT can only be used in transaction blocks error when using $afterCommit = true;"
} | {
"body": "### Overview\r\nfixes #48658\r\n\r\nHi\r\n\r\nI checked the implementation regarding `afterCommit`, fixed defects, and deleted unused functions.\r\n\r\n### Cause of the problem\r\n\r\nThe cause was that by calling `afterCommit` before lowering the transaction level, the transaction behaved as if it existed, even though it actually did not.\r\n\r\nI solved this problem by lowering the transaction level before calling `afterCommit`, and by lowering the level expected by `afterCommitCallbacksShouldBeExecuted()` by one step.\r\n\r\nI also fixed commit() in the same way.\r\n\r\n### Other problem\r\n\r\nThe `finally` of `ManagesTransactions::transaction` is unnecessary, so it has been removed. Since the transaction level is lowered with `handleCommitTransactionException()`, using finally will lower the transaction level by two levels.\r\n\r\n### Removed unnecessary features\r\n\r\nI removed the functionality related to `callbacksShouldIgnore` as it is no longer used anywhere.\r\n\r\n### How should TransactionsManager behave?\r\n\r\nDuring normal execution, `afterCommit` is expected to be executed when the transaction no longer exists. That is, when the transaction level is 0.\r\n\r\nWhen testing using `RefreshDatabase`, the transaction level is increased by +1 first, as shown in the following link.\r\nhttps://github.com/laravel/framework/blob/cddb4f3bb5231f44f18fce304dbf190ad8348ddc/src/Illuminate/Foundation/Testing/RefreshDatabase.php#L100\r\n\r\nSo in this case, transaction level 1 will be the lowest, and we would expect `afterCommit` to be called when level drops to 1.\r\n\r\n### notes\r\n\r\nI swapped the order of the `OR` in `afterCommitCallbacksShouldBeExecuted`.\r\nThis should basically all be handled with `$this->transactionsManager?->afterCommitCallbacksShouldBeExecuted($this->transactions)`, and to make it clear that `$this->transactions == 0` is a fallback is.\r\n\r\nBest regards.",
"number": 48662,
"review_comments": [],
"title": "[10.x] Fixed implementation related to `afterCommit` on Postgres and MSSQL database drivers"
} | {
"commits": [
{
"message": "fix expected level in afterCommitCallbacksShouldBeExecuted"
},
{
"message": "remove callbacksShouldIgnore"
},
{
"message": "Fixed transaction level down timing"
},
{
"message": "Fixed transaction level down timing"
},
{
"message": "Add test - after commit is executed on final commit"
},
{
"message": "style fix\n\nstyle fix"
},
{
"message": "[10.x] Test Improvements\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "Add regression tests."
},
{
"message": "Merge pull request #2 from laravel/patch-gh-48658"
}
],
"files": [
{
"diff": "@@ -47,6 +47,8 @@ public function transaction(Closure $callback, $attempts = 1)\n $this->getPdo()->commit();\n }\n \n+ $this->transactions = max(0, $this->transactions - 1);\n+\n if ($this->afterCommitCallbacksShouldBeExecuted()) {\n $this->transactionsManager?->commit($this->getName());\n }\n@@ -56,8 +58,6 @@ public function transaction(Closure $callback, $attempts = 1)\n );\n \n continue;\n- } finally {\n- $this->transactions = max(0, $this->transactions - 1);\n }\n \n $this->fireConnectionEvent('committed');\n@@ -194,12 +194,12 @@ public function commit()\n $this->getPdo()->commit();\n }\n \n+ $this->transactions = max(0, $this->transactions - 1);\n+\n if ($this->afterCommitCallbacksShouldBeExecuted()) {\n $this->transactionsManager?->commit($this->getName());\n }\n \n- $this->transactions = max(0, $this->transactions - 1);\n-\n $this->fireConnectionEvent('committed');\n }\n \n@@ -210,8 +210,7 @@ public function commit()\n */\n protected function afterCommitCallbacksShouldBeExecuted()\n {\n- return $this->transactions == 0 ||\n- $this->transactionsManager?->afterCommitCallbacksShouldBeExecuted($this->transactions);\n+ return $this->transactionsManager?->afterCommitCallbacksShouldBeExecuted($this->transactions) || $this->transactions == 0;\n }\n \n /**",
"filename": "src/Illuminate/Database/Concerns/ManagesTransactions.php",
"status": "modified"
},
{
"diff": "@@ -11,13 +11,6 @@ class DatabaseTransactionsManager\n */\n protected $transactions;\n \n- /**\n- * The database transaction that should be ignored by callbacks.\n- *\n- * @var \\Illuminate\\Database\\DatabaseTransactionRecord|null\n- */\n- protected $callbacksShouldIgnore;\n-\n /**\n * Create a new database transactions manager instance.\n *\n@@ -54,10 +47,6 @@ public function rollback($connection, $level)\n $this->transactions = $this->transactions->reject(\n fn ($transaction) => $transaction->connection == $connection && $transaction->level > $level\n )->values();\n-\n- if ($this->transactions->isEmpty()) {\n- $this->callbacksShouldIgnore = null;\n- }\n }\n \n /**\n@@ -75,10 +64,6 @@ public function commit($connection)\n $this->transactions = $forOtherConnections->values();\n \n $forThisConnection->map->executeCallbacks();\n-\n- if ($this->transactions->isEmpty()) {\n- $this->callbacksShouldIgnore = null;\n- }\n }\n \n /**\n@@ -96,19 +81,6 @@ public function addCallback($callback)\n $callback();\n }\n \n- /**\n- * Specify that callbacks should ignore the given transaction when determining if they should be executed.\n- *\n- * @param \\Illuminate\\Database\\DatabaseTransactionRecord $transaction\n- * @return $this\n- */\n- public function callbacksShouldIgnore(DatabaseTransactionRecord $transaction)\n- {\n- $this->callbacksShouldIgnore = $transaction;\n-\n- return $this;\n- }\n-\n /**\n * Get the transactions that are applicable to callbacks.\n *\n@@ -127,7 +99,7 @@ public function callbackApplicableTransactions()\n */\n public function afterCommitCallbacksShouldBeExecuted($level)\n {\n- return $level === 1;\n+ return $level === 0;\n }\n \n /**",
"filename": "src/Illuminate/Database/DatabaseTransactionsManager.php",
"status": "modified"
},
{
"diff": "@@ -42,6 +42,6 @@ public function callbackApplicableTransactions()\n */\n public function afterCommitCallbacksShouldBeExecuted($level)\n {\n- return $level === 2;\n+ return $level === 1;\n }\n }",
"filename": "src/Illuminate/Foundation/Testing/DatabaseTransactionsManager.php",
"status": "modified"
},
{
"diff": "@@ -7,6 +7,7 @@\n use Exception;\n use Illuminate\\Contracts\\Events\\Dispatcher;\n use Illuminate\\Database\\Connection;\n+use Illuminate\\Database\\DatabaseTransactionsManager;\n use Illuminate\\Database\\Events\\QueryExecuted;\n use Illuminate\\Database\\Events\\TransactionBeginning;\n use Illuminate\\Database\\Events\\TransactionCommitted;\n@@ -289,6 +290,20 @@ public function testCommittingFiresEventsIfSet()\n $connection->commit();\n }\n \n+ public function testAfterCommitIsExecutedOnFinalCommit()\n+ {\n+ $pdo = $this->getMockBuilder(DatabaseConnectionTestMockPDO::class)->onlyMethods(['beginTransaction', 'commit'])->getMock();\n+ $transactionsManager = $this->getMockBuilder(DatabaseTransactionsManager::class)->onlyMethods(['afterCommitCallbacksShouldBeExecuted'])->getMock();\n+ $transactionsManager->expects($this->once())->method('afterCommitCallbacksShouldBeExecuted')->with(0)->willReturn(true);\n+\n+ $connection = $this->getMockConnection([], $pdo);\n+ $connection->setTransactionManager($transactionsManager);\n+\n+ $connection->transaction(function () {\n+ // do nothing\n+ });\n+ }\n+\n public function testRollBackedFiresEventsIfSet()\n {\n $pdo = $this->createMock(DatabaseConnectionTestMockPDO::class);",
"filename": "tests/Database/DatabaseConnectionTest.php",
"status": "modified"
},
{
"diff": "@@ -2,7 +2,11 @@\n \n namespace Illuminate\\Tests\\Integration\\Database;\n \n+use Illuminate\\Bus\\Queueable;\n+use Illuminate\\Contracts\\Queue\\ShouldQueue;\n use Illuminate\\Foundation\\Auth\\User;\n+use Illuminate\\Foundation\\Bus\\Dispatchable;\n+use Illuminate\\Queue\\InteractsWithQueue;\n use Illuminate\\Support\\Facades\\DB;\n use Orchestra\\Testbench\\Concerns\\WithLaravelMigrations;\n use Orchestra\\Testbench\\Factories\\UserFactory;\n@@ -41,6 +45,21 @@ public function testObserverCalledWithAfterCommitWhenInsideTransaction()\n $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n }\n \n+ public function testObserverCalledWithAfterCommitWhenInsideTransactionWithDispatchSync()\n+ {\n+ User::observe($observer = EloquentTransactionWithAfterCommitTestsUserObserverUsingDispatchSync::resetting());\n+\n+ $user1 = DB::transaction(fn () => User::create(UserFactory::new()->raw()));\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+\n+ $this->assertDatabaseHas('password_reset_tokens', [\n+ 'email' => $user1->email,\n+ 'token' => sha1($user1->email),\n+ ]);\n+ }\n+\n public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepoint()\n {\n User::observe($observer = EloquentTransactionWithAfterCommitTestsUserObserver::resetting());\n@@ -102,3 +121,32 @@ public function created($user)\n static::$calledTimes++;\n }\n }\n+\n+class EloquentTransactionWithAfterCommitTestsUserObserverUsingDispatchSync extends EloquentTransactionWithAfterCommitTestsUserObserver\n+{\n+ public function created($user)\n+ {\n+ dispatch_sync(new EloquentTransactionWithAfterCommitTestsJob($user->email));\n+\n+ parent::created($user);\n+ }\n+}\n+\n+class EloquentTransactionWithAfterCommitTestsJob implements ShouldQueue\n+{\n+ use Dispatchable, InteractsWithQueue, Queueable;\n+\n+ public function __construct(public string $email)\n+ {\n+ // ...\n+ }\n+\n+ public function handle(): void\n+ {\n+ DB::transaction(function () {\n+ DB::table('password_reset_tokens')->insert([\n+ ['email' => $this->email, 'token' => sha1($this->email), 'created_at' => now()],\n+ ]);\n+ });\n+ }\n+}",
"filename": "tests/Integration/Database/EloquentTransactionWithAfterCommitTests.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.23.1\r\n\r\n### PHP Version\r\n\r\n8.2.10\r\n\r\n### Database Driver & Version\r\n\r\n8.0.33\r\n\r\n### Description\r\n\r\nIn tests, model observer `created` does not run if all condition applies:\r\n1. Test uses mysql DB connection.\r\n2. Test uses `RefreshDatabase` trait.\r\n3. Using `createOrFirst()` or `firstOrCreate()` method and the method is inside `DB::transaction()`.\r\n\r\nThis issue started to appear in laravel/framework 10.21. I think it was introduced in https://github.com/laravel/framework/pull/48144\r\n\r\ncc: @tonysm / @mpyw \r\n\r\n### Steps To Reproduce\r\n\r\n1. Clone [TestDBTransaction](https://github.com/ryanldy/TestDBTransaction) sample project.\r\n2. Make sure to update mysql database connection in your .env file.\r\n3. Run `vendor/bin/phpunit`. Test should pass but it fails.\r\n4. Try to comment the lines under Failing Test (line 27 and 30) section and uncomment a line from the Passing Tests (line 35 or 38) in `NoteObserverTest`. Test now passes.",
"comments": [
{
"body": "Confirmed. Thanks for reporting",
"created_at": "2023-09-20T02:59:40Z"
},
{
"body": "It appears to be a problem related to the `RefreshDatabase` trait. Both succeed when no trait is used",
"created_at": "2023-09-20T03:23:29Z"
},
{
"body": "I have disabled the savepoint fixes and double-wrap in `DB::transaction()` in the test case, but the test still fails. In short, I don't think the bug is caused by the `createOrFirst()` related changes, but by **the incompatibility of the `RefreshDatabase` trace and the `$afterCommit` feature.**\r\n\r\n```diff\r\n public function withSavepointIfNeeded(Closure $scope): mixed\r\n {\r\n+ return $scope();\r\n- return $this->getQuery()->getConnection()->transactionLevel() > 0\r\n- ? $this->getQuery()->getConnection()->transaction($scope)\r\n- : $scope();\r\n }\r\n```\r\n\r\n```php\r\nDB::transaction(fn () => DB::transaction(fn () => $user->notes()->createOrFirst(['notes' => 'abc'])));\r\n```\r\n\r\nThis is a more serious problem than we thought.\r\n\r\nRelated to:\r\n\r\n- #35422 (@themsaid)\r\n- #35857 (@mariomka)\r\n- #41782 (@taylorotwell)",
"created_at": "2023-09-20T03:44:16Z"
},
{
"body": "@ryanldy Would you rename the issue into the following?\r\n\r\n```\r\n`RefreshDatabase` + double wrapping in `DB::transaction()` breaks `$afterCommit` functionality\r\n```",
"created_at": "2023-09-20T03:47:18Z"
},
{
"body": "@pabloelcolombiano has also mentioned this problem: https://github.com/laravel/framework/pull/35422#issuecomment-768154666",
"created_at": "2023-09-20T03:50:14Z"
},
{
"body": "@mpyw thank you. Done renaming the issue. ",
"created_at": "2023-09-20T03:53:05Z"
},
{
"body": "@taylorotwell already tried to fix this issue in #41782, but it was not enough when transactions were nested. Would you review the changes?\r\n",
"created_at": "2023-09-20T03:58:35Z"
},
{
"body": "@mpyw do you think #48466 fixes this issue?",
"created_at": "2023-09-20T04:54:37Z"
},
{
"body": "@tonysm I'm not sure... At least, I don't think that dealing specifically for `withSavePointIfNeeded()` is the best solution, since this problem is reproduced **even if `DB::transaction()` is simply nested on the user code side**.",
"created_at": "2023-09-20T05:06:02Z"
},
{
"body": "Perhaps we should pass the following test with `RefreshDatabase`.\r\n\r\n```php\r\nDB::transaction(fn () => DB::transaction(fn () => $user->notes()->create(['notes' => 'abc'])));\r\n```",
"created_at": "2023-09-20T05:07:47Z"
},
{
"body": "I don't think it's a problem in real apps. It's only when testing (because the tests run in a transaction), so I think this should be a good fix for now.",
"created_at": "2023-09-20T05:08:16Z"
},
{
"body": "I think it is not bad as a temporary fix, but not enough as a permanent solution. Let @taylorotwell decide on that.",
"created_at": "2023-09-20T05:09:33Z"
},
{
"body": "@tonysm How about leaving `FIXME: ` comment on your code? That would be perfect as temporary fixes.",
"created_at": "2023-09-20T05:15:55Z"
},
{
"body": "Hmmm...\r\nOf course, this may solve the problem, but it seems to be a temporary solution.\r\nAnd isn't this destructive?\r\nWithout deep consideration of various patterns, inconsistencies may occur in transaction management.\r\nI think there are many projects that take advantage of the ease of transaction nesting in Laravel, and nest transactions rather easily (like putting them in the Repository layer, but also in the UseCase layer just to be safe).\r\n\r\nI don't have any concrete ideas, but I think it would be better if RefreshDatabase Trait can do something about it.",
"created_at": "2023-09-20T05:25:22Z"
},
{
"body": "A better solution is not to use `RefreshDatabase` for such usage as it's always going to include a database transaction.",
"created_at": "2023-09-20T06:06:18Z"
},
{
"body": "> A better solution is not to use `RefreshDatabase` for such usage as it's always going to include a database transaction.\r\n\r\nFair enough, but it's still just a work-around. I think this is clearly a bug and would be happy to see a fundamental fix.",
"created_at": "2023-09-20T06:19:45Z"
},
{
"body": "Commented on the PR: https://github.com/laravel/framework/pull/48466#issuecomment-1727275743",
"created_at": "2023-09-20T09:00:21Z"
},
{
"body": "While working on this issue I found a new bug. It appears that multiple connections are not being handled correctly.\r\n\r\n- #48472",
"created_at": "2023-09-20T12:48:25Z"
},
{
"body": "@tonysm According to #48472, the multiple `$callbacksShouldIgnore` support in PR #48466 itself is probably useful. However, I don't like the idea of only focusing the support to `createOrFirst()`, and think it should be more in line with PR #48471.",
"created_at": "2023-09-20T13:27:18Z"
}
],
"number": 48451,
"title": "`RefreshDatabase` + double wrapping in `DB::transaction()` breaks `$afterCommit` functionality"
} | {
"body": "https://github.com/laravel/framework/pull/48466#issuecomment-1727275743\r\n\r\nWIP\r\n\r\n- Fixes #48451 \r\n- Replaces #48466 ",
"number": 48471,
"review_comments": [],
"title": "[PoC] [10.x] Fix nested transaction callbacks handling"
} | {
"commits": [
{
"message": "Fix nested transaction callbacks handling"
}
],
"files": [
{
"diff": "@@ -48,10 +48,7 @@ public function transaction(Closure $callback, $attempts = 1)\n }\n \n $this->transactions = max(0, $this->transactions - 1);\n-\n- if ($this->afterCommitCallbacksShouldBeExecuted()) {\n- $this->transactionsManager?->commit($this->getName());\n- }\n+ $this->transactionsManager?->commit($this->getName());\n } catch (Throwable $e) {\n $this->handleCommitTransactionException(\n $e, $currentAttempt, $attempts\n@@ -195,26 +192,11 @@ public function commit()\n }\n \n $this->transactions = max(0, $this->transactions - 1);\n-\n- if ($this->afterCommitCallbacksShouldBeExecuted()) {\n- $this->transactionsManager?->commit($this->getName());\n- }\n+ $this->transactionsManager?->commit($this->getName());\n \n $this->fireConnectionEvent('committed');\n }\n \n- /**\n- * Determine if after commit callbacks should be executed.\n- *\n- * @return bool\n- */\n- protected function afterCommitCallbacksShouldBeExecuted()\n- {\n- return $this->transactions == 0 ||\n- ($this->transactionsManager &&\n- $this->transactionsManager->callbackApplicableTransactions()->count() === 1);\n- }\n-\n /**\n * Handle an exception encountered when committing a transaction.\n *",
"filename": "src/Illuminate/Database/Concerns/ManagesTransactions.php",
"status": "modified"
},
{
"diff": "@@ -68,19 +68,52 @@ public function rollback($connection, $level)\n */\n public function commit($connection)\n {\n- [$forThisConnection, $forOtherConnections] = $this->transactions->partition(\n+ if ($this->afterCommitCallbacksShouldBeExecuted()) {\n+ [$forThisConnection, $forOtherConnections] = $this->transactions->partition(\n+ fn ($transaction) => $transaction->connection == $connection\n+ );\n+\n+ $this->transactions = $forOtherConnections->values();\n+\n+ $forThisConnection->map->executeCallbacks();\n+\n+ if ($this->transactions->isEmpty()) {\n+ $this->callbacksShouldIgnore = null;\n+ }\n+\n+ return;\n+ }\n+\n+ $last = $this->transactions->last(\n fn ($transaction) => $transaction->connection == $connection\n );\n+ $parent = $this->transactions->last(\n+ fn ($transaction) => $transaction->connection == $connection && $last !== $transaction,\n+ );\n \n- $this->transactions = $forOtherConnections->values();\n+ $this->transactions = $this->transactions->reject(\n+ fn ($transaction) => $transaction === $last,\n+ )->values();\n \n- $forThisConnection->map->executeCallbacks();\n+ foreach ($last?->getCallbacks() ?? [] as $callback) {\n+ $parent?->addCallback($callback);\n+ }\n \n if ($this->transactions->isEmpty()) {\n $this->callbacksShouldIgnore = null;\n }\n }\n \n+ /**\n+ * Determine if after commit callbacks should be executed.\n+ *\n+ * @return bool\n+ */\n+ protected function afterCommitCallbacksShouldBeExecuted()\n+ {\n+ return $this->callbackApplicableTransactions()->count() === 1;\n+ }\n+\n /**\n * Register a transaction callback.\n *",
"filename": "src/Illuminate/Database/DatabaseTransactionsManager.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.23.1\r\n\r\n### PHP Version\r\n\r\n8.2.10\r\n\r\n### Database Driver & Version\r\n\r\n8.0.33\r\n\r\n### Description\r\n\r\nIn tests, model observer `created` does not run if all condition applies:\r\n1. Test uses mysql DB connection.\r\n2. Test uses `RefreshDatabase` trait.\r\n3. Using `createOrFirst()` or `firstOrCreate()` method and the method is inside `DB::transaction()`.\r\n\r\nThis issue started to appear in laravel/framework 10.21. I think it was introduced in https://github.com/laravel/framework/pull/48144\r\n\r\ncc: @tonysm / @mpyw \r\n\r\n### Steps To Reproduce\r\n\r\n1. Clone [TestDBTransaction](https://github.com/ryanldy/TestDBTransaction) sample project.\r\n2. Make sure to update mysql database connection in your .env file.\r\n3. Run `vendor/bin/phpunit`. Test should pass but it fails.\r\n4. Try to comment the lines under Failing Test (line 27 and 30) section and uncomment a line from the Passing Tests (line 35 or 38) in `NoteObserverTest`. Test now passes.",
"comments": [
{
"body": "Confirmed. Thanks for reporting",
"created_at": "2023-09-20T02:59:40Z"
},
{
"body": "It appears to be a problem related to the `RefreshDatabase` trait. Both succeed when no trait is used",
"created_at": "2023-09-20T03:23:29Z"
},
{
"body": "I have disabled the savepoint fixes and double-wrap in `DB::transaction()` in the test case, but the test still fails. In short, I don't think the bug is caused by the `createOrFirst()` related changes, but by **the incompatibility of the `RefreshDatabase` trace and the `$afterCommit` feature.**\r\n\r\n```diff\r\n public function withSavepointIfNeeded(Closure $scope): mixed\r\n {\r\n+ return $scope();\r\n- return $this->getQuery()->getConnection()->transactionLevel() > 0\r\n- ? $this->getQuery()->getConnection()->transaction($scope)\r\n- : $scope();\r\n }\r\n```\r\n\r\n```php\r\nDB::transaction(fn () => DB::transaction(fn () => $user->notes()->createOrFirst(['notes' => 'abc'])));\r\n```\r\n\r\nThis is a more serious problem than we thought.\r\n\r\nRelated to:\r\n\r\n- #35422 (@themsaid)\r\n- #35857 (@mariomka)\r\n- #41782 (@taylorotwell)",
"created_at": "2023-09-20T03:44:16Z"
},
{
"body": "@ryanldy Would you rename the issue into the following?\r\n\r\n```\r\n`RefreshDatabase` + double wrapping in `DB::transaction()` breaks `$afterCommit` functionality\r\n```",
"created_at": "2023-09-20T03:47:18Z"
},
{
"body": "@pabloelcolombiano has also mentioned this problem: https://github.com/laravel/framework/pull/35422#issuecomment-768154666",
"created_at": "2023-09-20T03:50:14Z"
},
{
"body": "@mpyw thank you. Done renaming the issue. ",
"created_at": "2023-09-20T03:53:05Z"
},
{
"body": "@taylorotwell already tried to fix this issue in #41782, but it was not enough when transactions were nested. Would you review the changes?\r\n",
"created_at": "2023-09-20T03:58:35Z"
},
{
"body": "@mpyw do you think #48466 fixes this issue?",
"created_at": "2023-09-20T04:54:37Z"
},
{
"body": "@tonysm I'm not sure... At least, I don't think that dealing specifically for `withSavePointIfNeeded()` is the best solution, since this problem is reproduced **even if `DB::transaction()` is simply nested on the user code side**.",
"created_at": "2023-09-20T05:06:02Z"
},
{
"body": "Perhaps we should pass the following test with `RefreshDatabase`.\r\n\r\n```php\r\nDB::transaction(fn () => DB::transaction(fn () => $user->notes()->create(['notes' => 'abc'])));\r\n```",
"created_at": "2023-09-20T05:07:47Z"
},
{
"body": "I don't think it's a problem in real apps. It's only when testing (because the tests run in a transaction), so I think this should be a good fix for now.",
"created_at": "2023-09-20T05:08:16Z"
},
{
"body": "I think it is not bad as a temporary fix, but not enough as a permanent solution. Let @taylorotwell decide on that.",
"created_at": "2023-09-20T05:09:33Z"
},
{
"body": "@tonysm How about leaving `FIXME: ` comment on your code? That would be perfect as temporary fixes.",
"created_at": "2023-09-20T05:15:55Z"
},
{
"body": "Hmmm...\r\nOf course, this may solve the problem, but it seems to be a temporary solution.\r\nAnd isn't this destructive?\r\nWithout deep consideration of various patterns, inconsistencies may occur in transaction management.\r\nI think there are many projects that take advantage of the ease of transaction nesting in Laravel, and nest transactions rather easily (like putting them in the Repository layer, but also in the UseCase layer just to be safe).\r\n\r\nI don't have any concrete ideas, but I think it would be better if RefreshDatabase Trait can do something about it.",
"created_at": "2023-09-20T05:25:22Z"
},
{
"body": "A better solution is not to use `RefreshDatabase` for such usage as it's always going to include a database transaction.",
"created_at": "2023-09-20T06:06:18Z"
},
{
"body": "> A better solution is not to use `RefreshDatabase` for such usage as it's always going to include a database transaction.\r\n\r\nFair enough, but it's still just a work-around. I think this is clearly a bug and would be happy to see a fundamental fix.",
"created_at": "2023-09-20T06:19:45Z"
},
{
"body": "Commented on the PR: https://github.com/laravel/framework/pull/48466#issuecomment-1727275743",
"created_at": "2023-09-20T09:00:21Z"
},
{
"body": "While working on this issue I found a new bug. It appears that multiple connections are not being handled correctly.\r\n\r\n- #48472",
"created_at": "2023-09-20T12:48:25Z"
},
{
"body": "@tonysm According to #48472, the multiple `$callbacksShouldIgnore` support in PR #48466 itself is probably useful. However, I don't like the idea of only focusing the support to `createOrFirst()`, and think it should be more in line with PR #48471.",
"created_at": "2023-09-20T13:27:18Z"
}
],
"number": 48451,
"title": "`RefreshDatabase` + double wrapping in `DB::transaction()` breaks `$afterCommit` functionality"
} | {
"body": "### Changed\r\n\r\n- Deprecates the `Illuminate\\Database\\DatabaseTransactionsManager::callbackApplicableTransactions` method (no longer used in the framework)\r\n- Deprecates the `Illuminate\\Database\\DatabaseTransactionsManager::callbacksShouldIgnore` method (no longer used in the framework. We're now using the new `withAfterCommitCallbacksInTestTransactionAwareMode` method, which this one is forwarding to\r\n- Adds a new `Illuminate\\Database\\DatabaseTransactionsManager::withAfterCommitCallbacksInTestTransactionAwareMode` method meant to be used by the test database traits when they start a transaction. This should make sure that we execute the callbacks properly at the right level of the transaction (since the tests using the database traits start a wrapping transaction and never actually commit)\r\n- Adds a new param to the `Illuminate\\Database\\DatabaseTransactionsManager::commit($connection, $level = 1)` method. Now, instead of only having to pass the connection name, callers should also pass the transaction level. It's based on that level (and the fact that we're in test mode or not) that we're going to decide if the callbacks should run or not). All calls within the framework were updated.\r\n- Also, the `Illuminate\\Database\\DatabaseTransactionsManager::commit($connection, $level = 1)` is now called everytime there's a commit. Before it was only being called on the \"last one\", but now it receives the transaction level and it should decide if the callbacks should be triggered or not.\r\n\r\n---\r\n\r\n#### A More In-Depth Explanation\r\n\r\nChanges the way \"after commit\" callbacks are executed to avoid\r\nremembering which transactions to ignore.\r\n\r\nBefore, we remembered the test transaction, so we\r\ncould ignore it when deciding to run the \"after commit\"\r\ncallbacks or not.\r\n\r\nWe're still handling the \"after commit\" callbacks like that,\r\nbut now, instead of remembering which transactions to ignore,\r\nwe're always calling the `DatabaseTransactionManager::commit`\r\nmethod. The difference is that now we're passing the current\r\ntransaction level to it. The method will decide whether to run the\r\ncallbacks based on that level and whether or not this\r\nis in test mode.\r\n\r\nWhen in tests, instead of setting the current transaction to be\r\nremembered so it could be ignored, we're now only setting the\r\nDatabaseTransactionManager to test mode. When in test mode, it\r\nwill execute the callbacks when the transaction count reaches 1\r\n(remember that the test runs in a transaction, so that's the\r\n\"root\" level). Otherwise, it runs the callbacks when the transaction\r\nlevel is on level 0 (like in production).\r\n\r\nThere's also a change in the `DatabaseTransactionManager::addCallback`\r\nmethod. It now also checks if it's in test mode. When not in test mode,\r\nit only adds the callback to the execution queue if there's an open\r\ntransaction. Otherwise, the callback is executed right away. When in\r\ntest mode, the number of transactions has to be greater than one for\r\nit to be added to the callbacks queue.\r\n\r\n---\r\n\r\n#### Context\r\n\r\nWith the addition of the `withSavepointIfNeeded` in #48144, we added a new transition level that affects tests when you're using \"after commit\" callbacks and nesting transactions. This wasn't an issue before because we generally have one transaction wrapping. When the `createOrFirst` was added to other `*OrCreate` methods (`firstOrCreate` and `updateOrCreate`), this issue became more apparent.\r\n\r\nfixes #48451",
"number": 48466,
"review_comments": [
{
"body": "The switch from pulling the `->first()` transaction to `->last()` was intentional. Otherwise, it keeps re-adding the first transition to the list. We want to add the most recent, so we're taking the last instead.",
"created_at": "2023-09-20T04:57:19Z"
},
{
"body": "In Octane environment, should `$this->transactionsManager` get unset via `disconnect()` method? \r\n\r\nhttps://github.com/laravel/octane/blob/2.x/src/Listeners/DisconnectFromDatabases.php#L15C26-L15C36",
"created_at": "2023-09-20T08:05:02Z"
},
{
"body": "```suggestion\r\n * @var \\Illuminate\\Support\\Collection<int, \\Illuminate\\Database\\DatabaseTransactionRecord>\r\n```",
"created_at": "2023-09-20T08:32:24Z"
},
{
"body": "Yeah, I've changed the implementation. We won't have to clean it up (it's gone now)",
"created_at": "2023-09-21T01:38:56Z"
},
{
"body": "Would it be possible if we set `$level = 1` here since this would be the normal default value except during tests?",
"created_at": "2023-09-21T01:58:33Z"
},
{
"body": "Hmm, I don't see a value in adding the default value here. The method is only called from within the `ManagesTransactions` trait inside the framework. Are you worried about other libs calling this method manually? Adding the default value might give the wrong impression that this is optional. If we add a default value of `1` and people call this method without passing the transaction level, we'll always execute the callbacks no matter which transaction level we're currently in... so I'd be careful there. 🤔 ",
"created_at": "2023-09-21T02:19:06Z"
},
{
"body": "`db.transaction` binding has been available since Laravel 9, so someone might already extend or override the class to cater for other use cases such as databases without transactions; Mongodb, etc. \r\n\r\nAlso while it's only called from the class the visibility of the method is still `public`, wouldn't mind much if it was `protected` or `private`.",
"created_at": "2023-09-21T02:28:10Z"
},
{
"body": "Added",
"created_at": "2023-09-21T02:36:31Z"
},
{
"body": "*`TestMode`* naming seems a bit imprecise. Not all tests use `RefreshDatabase` (and `DatabaseTransactions`), so wouldn't something like ***`DatabaseTransactionsTestMode`*** be more descriptive? Since this method is automatically called by the trait initialization process rather than by the user, I don't think we need to worry about the verbosity of the name.\r\n\r\nThe other perspective is LGTM!",
"created_at": "2023-09-21T05:25:33Z"
},
{
"body": "What name do you suggest?",
"created_at": "2023-09-21T12:45:57Z"
},
{
"body": "Oh, on a re-read, it seems you're suggesting renaming the class. If so, I'm not sure about that. I thought about renaming it to `DatabaseTransactionCallbacksManager` or something, but renaming the class would be a bigger change to the FW itself.",
"created_at": "2023-09-21T14:28:49Z"
},
{
"body": "No no, I'm just suggesting the method renaming. How about ~`withAfterCommitCallbacksInDatabaseTransactionsTestMode`~? It's a bit verbose but very clear.\r\n\r\n<ins>`withAfterCommitCallbacksInTestTransactionAwareMode` would be better</ins>",
"created_at": "2023-09-21T14:59:47Z"
},
{
"body": "Should I add back this method signature?",
"created_at": "2023-09-22T13:18:08Z"
},
{
"body": "This one too, should I add back the signature? We could probably implement it to return all transactions when not in test mode and, if in test mode, skip the first one.",
"created_at": "2023-09-22T13:18:56Z"
},
{
"body": "I've added this method back with an implementation I believe should work the same as the previous one. We're also marking the method as deprecated.",
"created_at": "2023-09-22T13:38:27Z"
},
{
"body": "I've added this method back and we're marking it as deprecated. It forwards to the new `withAfterCommitCallbacksInTestTransactionAwareMode` method for now.",
"created_at": "2023-09-22T13:39:20Z"
},
{
"body": "Done",
"created_at": "2023-09-22T13:55:42Z"
}
],
"title": "[10.x] Fix \"after commit\" callbacks not running on nested transactions"
} | {
"commits": [
{
"message": "Tests observer using afterCommit"
},
{
"message": "Adds failing test for savepoint and observers using afterCommit"
},
{
"message": "Ignore the createOrFirst savepoint to run callbacks"
},
{
"message": "Fix typo"
},
{
"message": "Remove DatabaseEloquentAppTest to see if CI passes"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "wip\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "Update src/Illuminate/Database/DatabaseTransactionsManager.php\n\nCo-authored-by: Mior Muhammad Zaki <crynobone@gmail.com>"
},
{
"message": "Changes the way the after commit callbacks are executed\nto avoid remembering which transactions to ignore\n\nBefore, we were remembering the test transaction so we\ncould ignore it when deciding to run the after commit\ncallbacks or not.\n\nWe're still handling the after commit callbacks like that\nbut now instead of remembering which transactions to ignore,\nwe're always calling the DatabaseTransactionManager::commit\nmethod. The difference is that now we're passing the current\ntransaction level to it. The method will decide to call the\ncallbacks or not based on that level and whether or not this\nis on in test mode.\n\nWhen in tests, instead of setting the current transaction to be\nremembered so it could be ignored, we're now only setting the\nDatabaseTransactionManager to test mode. When in test mode, it\nwill execute the callbacks when the transactions count reaches\n1 (remember that the test runs in a transaction, so that's the\n\"root\" level). Otherwise, it runs the callbacks when the transactions\nlevel is on level 0 (like in production).\n\nThere's also a change in the DatabaseTransactionManager::addCallback\nmethod. It now also checks if it's in test mode. When not in test mode,\nit only adds the callback to the execution queue if there's an open\ntransaction. Otherwise, the callback is executed right away. When in\ntest mode, the number of transactions has to be greater than one for\nit to be added to the callbacks queue."
},
{
"message": "Fix DatabaseTransactionsTest"
},
{
"message": "Fix DatabaseTransactionsManagerTest"
},
{
"message": "CSFixer"
},
{
"message": "wip"
},
{
"message": "Rename method and property and inline usage"
},
{
"message": "Adds a depply nested transaction test"
},
{
"message": "Simplify deeply nesting test"
},
{
"message": "Sets default level value to one (since it's a new parameter)"
},
{
"message": "Rename method"
},
{
"message": "Adds back the removed methods from the db.transactions and mark them as deprecated"
},
{
"message": "StyleCI"
},
{
"message": "Inline the if statement using then collection when() method"
},
{
"message": "wip"
}
],
"files": [
{
"diff": "@@ -104,7 +104,7 @@\n \"league/flysystem-read-only\": \"^3.3\",\n \"league/flysystem-sftp-v3\": \"^3.0\",\n \"mockery/mockery\": \"^1.5.1\",\n- \"orchestra/testbench-core\": \"^8.10\",\n+ \"orchestra/testbench-core\": \"^8.11.3\",\n \"pda/pheanstalk\": \"^4.0\",\n \"phpstan/phpstan\": \"^1.4.7\",\n \"phpunit/phpunit\": \"^10.0.7\",",
"filename": "composer.json",
"status": "modified"
},
{
"diff": "@@ -47,11 +47,9 @@ public function transaction(Closure $callback, $attempts = 1)\n $this->getPdo()->commit();\n }\n \n- $this->transactions = max(0, $this->transactions - 1);\n+ $this->transactionsManager?->commit($this->getName(), $this->transactions);\n \n- if ($this->afterCommitCallbacksShouldBeExecuted()) {\n- $this->transactionsManager?->commit($this->getName());\n- }\n+ $this->transactions = max(0, $this->transactions - 1);\n } catch (Throwable $e) {\n $this->handleCommitTransactionException(\n $e, $currentAttempt, $attempts\n@@ -194,27 +192,13 @@ public function commit()\n $this->getPdo()->commit();\n }\n \n- $this->transactions = max(0, $this->transactions - 1);\n+ $this->transactionsManager?->commit($this->getName(), $this->transactions);\n \n- if ($this->afterCommitCallbacksShouldBeExecuted()) {\n- $this->transactionsManager?->commit($this->getName());\n- }\n+ $this->transactions = max(0, $this->transactions - 1);\n \n $this->fireConnectionEvent('committed');\n }\n \n- /**\n- * Determine if after commit callbacks should be executed.\n- *\n- * @return bool\n- */\n- protected function afterCommitCallbacksShouldBeExecuted()\n- {\n- return $this->transactions == 0 ||\n- ($this->transactionsManager &&\n- $this->transactionsManager->callbackApplicableTransactions()->count() === 1);\n- }\n-\n /**\n * Handle an exception encountered when committing a transaction.\n *",
"filename": "src/Illuminate/Database/Concerns/ManagesTransactions.php",
"status": "modified"
},
{
"diff": "@@ -12,11 +12,11 @@ class DatabaseTransactionsManager\n protected $transactions;\n \n /**\n- * The database transaction that should be ignored by callbacks.\n+ * When in test mode, we'll run the after commit callbacks on the top-level transaction.\n *\n- * @var \\Illuminate\\Database\\DatabaseTransactionRecord\n+ * @var bool\n */\n- protected $callbacksShouldIgnore;\n+ protected $afterCommitCallbacksRunningInTestTransaction = false;\n \n /**\n * Create a new database transactions manager instance.\n@@ -26,6 +26,19 @@ class DatabaseTransactionsManager\n public function __construct()\n {\n $this->transactions = collect();\n+ $this->afterCommitCallbacksRunningInTestTransaction = false;\n+ }\n+\n+ /**\n+ * Sets the transaction manager to test mode.\n+ *\n+ * @return self\n+ */\n+ public function withAfterCommitCallbacksInTestTransactionAwareMode()\n+ {\n+ $this->afterCommitCallbacksRunningInTestTransaction = true;\n+\n+ return $this;\n }\n \n /**\n@@ -54,30 +67,28 @@ public function rollback($connection, $level)\n $this->transactions = $this->transactions->reject(\n fn ($transaction) => $transaction->connection == $connection && $transaction->level > $level\n )->values();\n-\n- if ($this->transactions->isEmpty()) {\n- $this->callbacksShouldIgnore = null;\n- }\n }\n \n /**\n * Commit the active database transaction.\n *\n * @param string $connection\n+ * @param int $level\n * @return void\n */\n- public function commit($connection)\n+ public function commit($connection, $level = 1)\n {\n- [$forThisConnection, $forOtherConnections] = $this->transactions->partition(\n- fn ($transaction) => $transaction->connection == $connection\n- );\n-\n- $this->transactions = $forOtherConnections->values();\n+ // If the transaction level being commited reaches 1 (meaning it was the root\n+ // transaction), we'll run the callbacks. In test mode, since we wrap each\n+ // test in a transaction, we'll run the callbacks when reaching level 2.\n+ if ($level == 1 || ($this->afterCommitCallbacksRunningInTestTransaction && $level == 2)) {\n+ [$forThisConnection, $forOtherConnections] = $this->transactions->partition(\n+ fn ($transaction) => $transaction->connection == $connection\n+ );\n \n- $forThisConnection->map->executeCallbacks();\n+ $this->transactions = $forOtherConnections->values();\n \n- if ($this->transactions->isEmpty()) {\n- $this->callbacksShouldIgnore = null;\n+ $forThisConnection->map->executeCallbacks();\n }\n }\n \n@@ -89,36 +100,42 @@ public function commit($connection)\n */\n public function addCallback($callback)\n {\n- if ($current = $this->callbackApplicableTransactions()->last()) {\n- return $current->addCallback($callback);\n+ // If there are no transactions, we'll run the callbacks right away. Also, we'll run it\n+ // right away when we're in test mode and we only have the wrapping transaction. For\n+ // every other case, we'll queue up the callback to run after the commit happens.\n+ if ($this->transactions->isEmpty() || ($this->afterCommitCallbacksRunningInTestTransaction && $this->transactions->count() == 1)) {\n+ return $callback();\n }\n \n- $callback();\n+ return $this->transactions->last()->addCallback($callback);\n }\n \n /**\n * Specify that callbacks should ignore the given transaction when determining if they should be executed.\n *\n * @param \\Illuminate\\Database\\DatabaseTransactionRecord $transaction\n * @return $this\n+ *\n+ * @deprecated Will be removed in a future Laravel version. Use withAfterCommitCallbacksInTestTransactionAwareMode() instead.\n */\n public function callbacksShouldIgnore(DatabaseTransactionRecord $transaction)\n {\n- $this->callbacksShouldIgnore = $transaction;\n-\n- return $this;\n+ // This method was meant for testing only, so we're forwarding the call to the new method...\n+ return $this->withAfterCommitCallbacksInTestTransactionAwareMode();\n }\n \n /**\n * Get the transactions that are applicable to callbacks.\n *\n * @return \\Illuminate\\Support\\Collection\n+ *\n+ * @deprecated Will be removed in a future Laravel version.\n */\n public function callbackApplicableTransactions()\n {\n- return $this->transactions->reject(function ($transaction) {\n- return $transaction === $this->callbacksShouldIgnore;\n- })->values();\n+ return $this->transactions\n+ ->when($this->afterCommitCallbacksRunningInTestTransaction, fn ($transactions) => $transactions->skip(1))\n+ ->values();\n }\n \n /**",
"filename": "src/Illuminate/Database/DatabaseTransactionsManager.php",
"status": "modified"
},
{
"diff": "@@ -22,9 +22,7 @@ public function beginDatabaseTransaction()\n $connection->setEventDispatcher($dispatcher);\n \n if ($this->app->resolved('db.transactions')) {\n- $this->app->make('db.transactions')->callbacksShouldIgnore(\n- $this->app->make('db.transactions')->getTransactions()->first()\n- );\n+ $this->app->make('db.transactions')->withAfterCommitCallbacksInTestTransactionAwareMode();\n }\n }\n ",
"filename": "src/Illuminate/Foundation/Testing/DatabaseTransactions.php",
"status": "modified"
},
{
"diff": "@@ -98,9 +98,7 @@ public function beginDatabaseTransaction()\n $connection->setEventDispatcher($dispatcher);\n \n if ($this->app->resolved('db.transactions')) {\n- $this->app->make('db.transactions')->callbacksShouldIgnore(\n- $this->app->make('db.transactions')->getTransactions()->first()\n- );\n+ $this->app->make('db.transactions')->withAfterCommitCallbacksInTestTransactionAwareMode();\n }\n }\n ",
"filename": "src/Illuminate/Foundation/Testing/RefreshDatabase.php",
"status": "modified"
},
{
"diff": "@@ -67,7 +67,7 @@ public function testCommittingTransactions()\n $manager->begin('default', 2);\n $manager->begin('admin', 1);\n \n- $manager->commit('default');\n+ $manager->commit('default', 1);\n \n $this->assertCount(1, $manager->getTransactions());\n \n@@ -118,7 +118,11 @@ public function testCommittingTransactionsExecutesCallbacks()\n \n $manager->begin('admin', 1);\n \n- $manager->commit('default');\n+ $manager->commit('default', 2);\n+\n+ $this->assertEmpty($callbacks, 'Should not have ran the callbacks.');\n+\n+ $manager->commit('default', 1);\n \n $this->assertCount(2, $callbacks);\n $this->assertEquals(['default', 1], $callbacks[0]);\n@@ -144,7 +148,11 @@ public function testCommittingExecutesOnlyCallbacksOfTheConnection()\n $callbacks[] = ['admin', 1];\n });\n \n- $manager->commit('default');\n+ $manager->commit('default', 2);\n+\n+ $this->assertEmpty($callbacks, 'Should not have run the callbacks.');\n+\n+ $manager->commit('default', 1);\n \n $this->assertCount(1, $callbacks);\n $this->assertEquals(['default', 1], $callbacks[0]);",
"filename": "tests/Database/DatabaseTransactionsManagerTest.php",
"status": "modified"
},
{
"diff": "@@ -64,7 +64,7 @@ public function testTransactionIsRecordedAndCommitted()\n {\n $transactionManager = m::mock(new DatabaseTransactionsManager);\n $transactionManager->shouldReceive('begin')->once()->with('default', 1);\n- $transactionManager->shouldReceive('commit')->once()->with('default');\n+ $transactionManager->shouldReceive('commit')->once()->with('default', 1);\n \n $this->connection()->setTransactionManager($transactionManager);\n \n@@ -83,7 +83,7 @@ public function testTransactionIsRecordedAndCommittedUsingTheSeparateMethods()\n {\n $transactionManager = m::mock(new DatabaseTransactionsManager);\n $transactionManager->shouldReceive('begin')->once()->with('default', 1);\n- $transactionManager->shouldReceive('commit')->once()->with('default');\n+ $transactionManager->shouldReceive('commit')->once()->with('default', 1);\n \n $this->connection()->setTransactionManager($transactionManager);\n \n@@ -103,7 +103,8 @@ public function testNestedTransactionIsRecordedAndCommitted()\n $transactionManager = m::mock(new DatabaseTransactionsManager);\n $transactionManager->shouldReceive('begin')->once()->with('default', 1);\n $transactionManager->shouldReceive('begin')->once()->with('default', 2);\n- $transactionManager->shouldReceive('commit')->once()->with('default');\n+ $transactionManager->shouldReceive('commit')->once()->with('default', 2);\n+ $transactionManager->shouldReceive('commit')->once()->with('default', 1);\n \n $this->connection()->setTransactionManager($transactionManager);\n \n@@ -130,8 +131,9 @@ public function testNestedTransactionIsRecordeForDifferentConnectionsdAndCommitt\n $transactionManager->shouldReceive('begin')->once()->with('default', 1);\n $transactionManager->shouldReceive('begin')->once()->with('second_connection', 1);\n $transactionManager->shouldReceive('begin')->once()->with('second_connection', 2);\n- $transactionManager->shouldReceive('commit')->once()->with('default');\n- $transactionManager->shouldReceive('commit')->once()->with('second_connection');\n+ $transactionManager->shouldReceive('commit')->once()->with('second_connection', 2);\n+ $transactionManager->shouldReceive('commit')->once()->with('second_connection', 1);\n+ $transactionManager->shouldReceive('commit')->once()->with('default', 1);\n \n $this->connection()->setTransactionManager($transactionManager);\n $this->connection('second_connection')->setTransactionManager($transactionManager);",
"filename": "tests/Database/DatabaseTransactionsTest.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,101 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database;\n+\n+use Illuminate\\Foundation\\Auth\\User;\n+use Illuminate\\Foundation\\Testing\\RefreshDatabase;\n+use Illuminate\\Support\\Facades\\DB;\n+use Orchestra\\Testbench\\Concerns\\WithLaravelMigrations;\n+use Orchestra\\Testbench\\Factories\\UserFactory;\n+\n+class EloquentTransactionUsingRefreshDatabaseTest extends DatabaseTestCase\n+{\n+ use RefreshDatabase, WithLaravelMigrations;\n+\n+ protected function setUp(): void\n+ {\n+ $this->afterApplicationCreated(fn () => User::unguard());\n+ $this->beforeApplicationDestroyed(fn () => User::reguard());\n+\n+ parent::setUp();\n+ }\n+\n+ public function testObserverIsCalledOnTestsWithAfterCommit()\n+ {\n+ User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());\n+\n+ $user1 = User::create(UserFactory::new()->raw());\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+ }\n+\n+ public function testObserverCalledWithAfterCommitWhenInsideTransaction()\n+ {\n+ User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());\n+\n+ $user1 = DB::transaction(fn () => User::create(UserFactory::new()->raw()));\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+ }\n+\n+ public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepoint()\n+ {\n+ User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());\n+\n+ $user1 = User::createOrFirst(UserFactory::new()->raw());\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+ }\n+\n+ public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepointAndInsideTransaction()\n+ {\n+ User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());\n+\n+ $user1 = DB::transaction(fn () => User::createOrFirst(UserFactory::new()->raw()));\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+ }\n+\n+ public function testObserverIsCalledEvenWhenDeeplyNestingTransactions()\n+ {\n+ User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());\n+\n+ $user1 = DB::transaction(function () use ($observer) {\n+ return tap(DB::transaction(function () use ($observer) {\n+ return tap(DB::transaction(function () {\n+ return User::createOrFirst(UserFactory::new()->raw());\n+ }), function () use ($observer) {\n+ $this->assertEquals(0, $observer::$calledTimes, 'Should not have been called');\n+ });\n+ }), function () use ($observer) {\n+ $this->assertEquals(0, $observer::$calledTimes, 'Should not have been called');\n+ });\n+ });\n+\n+ $this->assertTrue($user1->exists);\n+ $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');\n+ }\n+}\n+\n+class EloquentTransactionUsingRefreshDatabaseUserObserver\n+{\n+ public static $calledTimes = 0;\n+\n+ public $afterCommit = true;\n+\n+ public static function resetting()\n+ {\n+ static::$calledTimes = 0;\n+\n+ return new static();\n+ }\n+\n+ public function created($user)\n+ {\n+ static::$calledTimes++;\n+ }\n+}",
"filename": "tests/Integration/Database/EloquentTransactionUsingRefreshDatabaseTest.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\n\n10.20.0\n\n### PHP Version\n\n8.2.2\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nWhen you create a primary key index in Postgres it is given the name `\"{$table}_pkey\"`. This is added by postgres so the name has the table prefix automatically.\r\n\r\nWhen you drop the primary key, the prefix is not added to the SQL so it fails. The code is in `src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php` line 430:\r\n```php\r\n public function compileDropPrimary(Blueprint $blueprint, Fluent $command)\r\n {\r\n $index = $this->wrap(\"{$blueprint->getTable()}_pkey\");\r\n\r\n return 'alter table '.$this->wrapTable($blueprint).\" drop constraint {$index}\";\r\n }\r\n```\r\n\r\nThe `wrap` method does not automatically add the prefix to the string. It requires a second argument (`$prefixAlias = true`) I think. But I'm not to confident with this code, so I don't know what sort of effect that will have. There may be a better way to do it.\n\n### Steps To Reproduce\n\n1. Start a new Laravel project\r\n2. Add a prefix to the `database` config\r\n3. Connect it to a postgres DB\r\n4. Run a migration to generate a table with a primary key column\r\n5. Run another migration to remove the primary key",
"comments": [
{
"body": "Hey 👋 \r\n\r\nI was trying to reproduce this issue, but no luck s far. \r\n\r\nCan you please share your migration code + version of Postgres ? \r\nThank you !",
"created_at": "2023-08-26T03:04:22Z"
},
{
"body": "Hey there, thanks for reporting this issue.\r\n\r\nWe'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue *as one separate commit* on the main/master branch and share the repository here?\r\n\r\nPlease make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com/) properly set up.\r\n\r\n laravel new bug-report --github=\"--public\"\r\n\r\nDo not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.\r\n\r\nThanks!",
"created_at": "2023-08-28T00:57:57Z"
},
{
"body": "Thanks for looking into it. \r\nI have been able to reproduce it in this repository: https://github.com/ChrisExP/bug-report\r\n\r\nJust hook that up to a postgres DB and run `php artisan migrate`. The last migration will fail when it tries to drop the primary key in the `test` table.\r\n\r\nI don't think this is relevant, but I will mention it just in case. I am on an M1 mac, and Postgres is still not natively supported on Homestead-ARM, so I have been using Docker with Rosetta to use Postgres locally.",
"created_at": "2023-08-30T14:34:17Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-08-31T09:42:18Z"
},
{
"body": "I can confirm this but can't immediately find a good solution. Would appreciate any help here. Using `$prefixAlias` on `wrap` does not solve it.",
"created_at": "2023-08-31T09:42:41Z"
},
{
"body": "@driesvints Please let me know if my solution works 👀 ",
"created_at": "2023-09-01T04:39:02Z"
},
{
"body": "Hey there,\r\n\r\nv10.21.1 with the relevant changes has been released, please try again and open up a new issue if you're still experiencing this problem.",
"created_at": "2023-09-05T07:41:56Z"
}
],
"number": 48189,
"title": "Dropping a primary key in PostgreSQL does not take into account the table prefix"
} | {
"body": "This PR addresses Issue #48189 by modifying the `compileDropPrimary` method in `PostgresGrammar`. The updated implementation now incorporates the table prefix when generating the primary key constraint name to drop.",
"number": 48268,
"review_comments": [],
"title": "[10.x] Combine prefix with table for `compileDropPrimary` PostgreSQL"
} | {
"commits": [
{
"message": "Combine prefix with table"
},
{
"message": "StyleCI fix"
}
],
"files": [
{
"diff": "@@ -1785,6 +1785,16 @@ public function getTable()\n return $this->table;\n }\n \n+ /**\n+ * Get the table prefix.\n+ *\n+ * @return string\n+ */\n+ public function getPrefix()\n+ {\n+ return $this->prefix;\n+ }\n+\n /**\n * Get the columns on the blueprint.\n *",
"filename": "src/Illuminate/Database/Schema/Blueprint.php",
"status": "modified"
},
{
"diff": "@@ -427,7 +427,7 @@ public function compileDropColumn(Blueprint $blueprint, Fluent $command)\n */\n public function compileDropPrimary(Blueprint $blueprint, Fluent $command)\n {\n- $index = $this->wrap(\"{$blueprint->getTable()}_pkey\");\n+ $index = $this->wrap(\"{$blueprint->getPrefix()}{$blueprint->getTable()}_pkey\");\n \n return 'alter table '.$this->wrapTable($blueprint).\" drop constraint {$index}\";\n }",
"filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.4.1\n\n### PHP Version\n\n8.1.2\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nWhen using \"RequiredIf\" validation rule that is dependant on another boolean field, if the boolean field gets a non empty array as input, an ErrorException is thrown when trying to get the displayable value of the boolean field.\r\n\n\n### Steps To Reproduce\n\n```\r\n$validator = \\Illuminate\\Support\\Facades\\Validator::make([\r\n 'is_customer' => ['test'],\r\n 'fullname' => null\r\n], [\r\n 'is_customer' => 'required|boolean',\r\n 'fullname' => 'required_if:is_customer,true'\r\n]);\r\n \r\n$validator->fails(); // <= ErrorException\r\n```",
"comments": [
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-08-28T07:18:33Z"
}
],
"number": 48187,
"title": "Array to string conversion ErrorException"
} | {
"body": "Hi, I fixed #48187 issue. The issue was to find the related translation line for a `boolean` validation rule while its value is an array.\r\n\r\nBefore\r\n```php\r\n$validator = \\Illuminate\\Support\\Facades\\Validator::make([\r\n 'is_customer' => ['test'],\r\n 'fullname' => null\r\n], [\r\n 'is_customer' => 'required|boolean',\r\n 'fullname' => 'required_if:is_customer,true'\r\n]);\r\n \r\n$validator->fails(); // ErrorException\r\n```\r\n\r\nAfter\r\n```php\r\n$validator = \\Illuminate\\Support\\Facades\\Validator::make([\r\n 'is_customer' => ['test'],\r\n 'fullname' => null\r\n], [\r\n 'is_customer' => 'required|boolean',\r\n 'fullname' => 'required_if:is_customer,true'\r\n]);\r\n \r\n$validator->fails(); // Return true\r\n```",
"number": 48219,
"review_comments": [],
"title": "[10.x] Array to string conversion error exception"
} | {
"commits": [
{
"message": "handling array type in FormatsMessages;"
},
{
"message": "Tests for added;"
},
{
"message": "Apply fixes from StyleCI"
}
],
"files": [
{
"diff": "@@ -442,6 +442,10 @@ public function getDisplayableValue($attribute, $value)\n return $this->customValues[$attribute][$value];\n }\n \n+ if (is_array($value)) {\n+ return 'array';\n+ }\n+\n $key = \"validation.values.{$attribute}.{$value}\";\n \n if (($line = $this->translator->get($key)) !== $key) {",
"filename": "src/Illuminate/Validation/Concerns/FormatsMessages.php",
"status": "modified"
},
{
"diff": "@@ -1416,6 +1416,29 @@ public function testRequiredIf()\n $this->assertSame('The baz field is required when foo is empty.', $v->messages()->first('baz'));\n }\n \n+ public function testRequiredIfArrayToStringConversationErrorException()\n+ {\n+ $trans = $this->getIlluminateArrayTranslator();\n+ $v = new Validator($trans, [\n+ 'is_customer' => 1,\n+ 'fullname' => null,\n+ ], [\n+ 'is_customer' => 'required|boolean',\n+ 'fullname' => 'required_if:is_customer,true',\n+ ]);\n+ $this->assertTrue($v->fails());\n+\n+ $trans = $this->getIlluminateArrayTranslator();\n+ $v = new Validator($trans, [\n+ 'is_customer' => ['test'],\n+ 'fullname' => null,\n+ ], [\n+ 'is_customer' => 'required|boolean',\n+ 'fullname' => 'required_if:is_customer,true',\n+ ]);\n+ $this->assertTrue($v->fails());\n+ }\n+\n public function testRequiredUnless()\n {\n $trans = $this->getIlluminateArrayTranslator();",
"filename": "tests/Validation/ValidationValidatorTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.4.1\n\n### PHP Version\n\n8.1.2\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nWhen using \"RequiredIf\" validation rule that is dependant on another boolean field, if the boolean field gets a non empty array as input, an ErrorException is thrown when trying to get the displayable value of the boolean field.\r\n\n\n### Steps To Reproduce\n\n```\r\n$validator = \\Illuminate\\Support\\Facades\\Validator::make([\r\n 'is_customer' => ['test'],\r\n 'fullname' => null\r\n], [\r\n 'is_customer' => 'required|boolean',\r\n 'fullname' => 'required_if:is_customer,true'\r\n]);\r\n \r\n$validator->fails(); // <= ErrorException\r\n```",
"comments": [
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-08-28T07:18:33Z"
}
],
"number": 48187,
"title": "Array to string conversion ErrorException"
} | {
"body": "This a minor change addressing the issue #48187 .\r\n\r\nThe change is checking that the dependant field's value is not an array before processing it as a basic data type.\r\n",
"number": 48188,
"review_comments": [],
"title": "[10.x] Fix ErrorException array to string conversion"
} | {
"commits": [
{
"message": "Fix ErrorException array to string conversion"
},
{
"message": "Include a test for RequiredIf rule when dependant on boolean field"
}
],
"files": [
{
"diff": "@@ -442,6 +442,10 @@ public function getDisplayableValue($attribute, $value)\n return $this->customValues[$attribute][$value];\n }\n \n+ if (is_array($value)) {\n+ $value = 'array';\n+ }\n+ \n $key = \"validation.values.{$attribute}.{$value}\";\n \n if (($line = $this->translator->get($key)) !== $key) {",
"filename": "src/Illuminate/Validation/Concerns/FormatsMessages.php",
"status": "modified"
},
{
"diff": "@@ -51,4 +51,17 @@ public function testItReturnedRuleIsNotSerializable()\n return true;\n }));\n }\n+\n+ public function testThatNoArrayToStringErrorExceptionIsThrownWhenDealingWithDependantBooleanField()\n+ {\n+ $validator = \\Illuminate\\Support\\Facades\\Validator::make([\n+ 'boolean_input' => ['test'],\n+ 'dependant_input' => null,\n+ ], [\n+ 'boolean_input' => 'required|boolean',\n+ 'dependant_input' => 'required_if:boolean_input,true',\n+ ]);\n+\n+ $this->assertIsBool($validator->fails());\n+ }\n }",
"filename": "tests/Validation/ValidationRequiredIfTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.13.2\n\n### PHP Version\n\n8.2.7\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\n_apologies for duplicating an unanswered discussion #47506 but I believe this is a bug requiring attention_\r\n\r\nWe are making use of a legacy database written for an ancient framework in Laravel. One \"feature\" of this framework is that integer unix timestamps are used for the updated_at column instead of datetime strings.\r\n\r\nWe can deal with this by setting `protected $dateFormat = 'U';` on the model classes however ideally we would like to use datetimes for application-specific time-related columns going forward so don't want to force the format on all new columns.\r\n\r\nWe wrote a cast to juggle the value from an instance of Carbon to `$carbon->timestamp` and all seemed well until we went to write unit tests for the functionality.\r\n\r\nThe tests failed because data was being truncated for the updated_at column as it was receiving a datetime string instead of the timestamp from the cast.\r\n\r\n```\r\nWarning: 1265 Data truncated for column 'updated_at' at row 1 (Connection: mysql, SQL: update `customers` set `name` = redacted, `customers`.`updated_at` = 2023-07-18 10:49:06 where `id` = 138)\r\n```\r\n\r\nI believe this is occurring here as it does not seem to check for casts before appending an updated_at value\r\n\r\nhttps://github.com/laravel/framework/blob/31b3d29cea6974674da5296a30442f4d803f28e2/src/Illuminate/Database/Eloquent/Builder.php#L1140\r\n\r\nI think that updated_at is not marked as dirty because the value has not changed because the change has been within the same second as the creation or another update.\r\n\r\nA quick resolution to this problem within tests is to include `$this->travelTo(now()->addMinute());` before every change made to a particular model so that the casted value is picked up with the dirty attributes\r\n\r\nhttps://github.com/laravel/framework/blob/31b3d29cea6974674da5296a30442f4d803f28e2/src/Illuminate/Database/Eloquent/Model.php#L1212\r\n\r\nObviously this is not possible within the main application so this problem may occur there if there are saves within the same second from different parts of the code.\r\n\r\n_if you create an entity in the database and then update the entity via a queued job then you encounter this error and must delay the job being dispatched_\r\n\r\nI am unsure as to whether the resolution is for the builder to cast the value before appending it or for any dirty attributes check to always include the updated_at value if any other changed values are present.\n\n### Steps To Reproduce\n\nHave the following database schema and code\r\n\r\n```sql\r\nCREATE TABLE `customers` (\r\n `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\r\n `customer_name` varchar(100) DEFAULT NULL,\r\n `created_at` int(11) DEFAULT NULL,\r\n `updated_at` int(11) DEFAULT NULL,\r\n PRIMARY KEY (`id`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\r\n```\r\n```php\r\n<?php\r\n\r\nnamespace App\\Models;\r\n\r\nuse App\\Casts\\UnixTimeStampToCarbon;\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Customer extends Model\r\n{\r\n use HasFactory;\r\n\r\n protected $casts = [\r\n 'created_at' => UnixTimeStampToCarbon::class,\r\n 'updated_at' => UnixTimeStampToCarbon::class,\r\n ];\r\n}\r\n```\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App\\Casts;\r\n\r\nuse Carbon\\Carbon;\r\nuse Illuminate\\Contracts\\Database\\Eloquent\\CastsAttributes;\r\n\r\n/**\r\n * @implements CastsAttributes<Carbon|null, Carbon>\r\n */\r\nclass UnixTimeStampToCarbon implements CastsAttributes\r\n{\r\n /**\r\n * Cast the given value.\r\n *\r\n * @param \\Illuminate\\Database\\Eloquent\\Model $model\r\n * @param mixed $value\r\n * @param array<mixed> $attributes\r\n * @return Carbon|null\r\n */\r\n public function get($model, string $key, $value, array $attributes)\r\n {\r\n return $value ? Carbon::createFromTimestampUTC($value) : null;\r\n }\r\n\r\n /**\r\n * Prepare the given value for storage.\r\n *\r\n * @param \\Illuminate\\Database\\Eloquent\\Model $model\r\n * @param mixed $value\r\n * @param array<mixed> $attributes\r\n * @return int|float|string|null\r\n */\r\n public function set($model, string $key, $value, array $attributes)\r\n {\r\n if (is_string($value) || is_numeric($value) || ($value instanceof \\DateTime && ! $value instanceof Carbon)) {\r\n $value = Carbon::parse($value);\r\n }\r\n\r\n return $value ? $value->timestamp : null;\r\n }\r\n}\r\n```\r\n```php\r\n<?php\r\n\r\nnamespace Tests\\Feature\\Http\\Controllers;\r\n\r\nuse App\\Models\\Customer;\r\nuse App\\Models\\User;\r\nuse Illuminate\\Contracts\\Auth\\Authenticatable;\r\nuse Tests\\TestCase;\r\n\r\nclass CustomerControllerTest extends TestCase\r\n{\r\n public function testUpdate(): void\r\n {\r\n /** @var Authenticatable|User $user */\r\n $user = User::factory()\r\n ->create();\r\n\r\n $customer = Customer::factory()->create([\r\n 'customer_name' => 'Test Customer',\r\n ]);\r\n\r\n // this is required because the customer has just been created\r\n $this->travelTo(now()->addMinute());\r\n $response = $this\r\n ->actingAs($user)\r\n ->put(\r\n route('customers.update', $customer),\r\n [\r\n 'customer_name' => 'Updated Customer',\r\n ]\r\n );\r\n $response->assertSessionHasNoErrors();\r\n $response->assertRedirect(route('customers.index'));\r\n\r\n $customer->refresh();\r\n $this->assertSame('Updated Customer', $customer->customer_name);\r\n }\r\n}\r\n```",
"comments": [
{
"body": "Thanks. The `freshTimestampString` indeed seems problematic. Would appreciate a PR to remedy this.",
"created_at": "2023-07-26T09:27:21Z"
},
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-07-26T09:27:38Z"
},
{
"body": "@driesvints thanks for confirming, would you be able to nominate what you think the correct solution is?\r\n\r\n> I am unsure as to whether the resolution is for the builder to cast the value before appending it or for any dirty attributes check to always include the updated_at value if any other changed values are present.\r\n\r\nI feel like the latter probably makes more sense, if there are dirty attributes present then include the updated_at which already seems to have been through the casts, but happy to look at the other option if that makes more sense to you.",
"created_at": "2023-07-26T09:31:22Z"
},
{
"body": "I'm not sure myself, sorry. I'd say the former because the latter could have side effects that people don't want.",
"created_at": "2023-07-26T11:52:09Z"
},
{
"body": "what do you think about this?\r\n\r\n@taylorotwell ",
"created_at": "2023-07-29T18:23:59Z"
},
{
"body": "@willpower232 \r\nHow do you implement the controller for `customers.update`?\r\nMake sure you are not using query builder's `update` or similar methods instead of Eloquent's `update` method.",
"created_at": "2023-07-30T18:25:52Z"
},
{
"body": "@amir9480 unfortunately its definitely eloquent related\r\n\r\n\r\n",
"created_at": "2023-07-31T09:00:11Z"
},
{
"body": "Hey folks, I dived into this one and have a potential fix, but I'm not 100% if it is suitable or how I feel about it - so I wanted to float it with those experiencing the issue.\r\n\r\nThe first fix would require a new property on the model indicating the format of the \"updated_at\" timestamp AND the cast in place.\r\n\r\n<img width=\"908\" alt=\"Screen Shot 2023-08-03 at 11 14 22 am\" src=\"https://github.com/laravel/framework/assets/24803032/d6937a24-c193-4902-b481-49cd95f100f4\">\r\n\r\n<img width=\"659\" alt=\"Screen Shot 2023-08-03 at 11 17 00 am\" src=\"https://github.com/laravel/framework/assets/24803032/de1fc4f1-9524-45c7-8d84-c46220ac1190\">\r\n\r\nI don't love this.\r\n\r\nAnother solution, which I prefer at this point, but is a bit more expensive, is to run the new value that the builder generates via the model's cast again. Introducing the `if` here means that the new model instance will only be created if the `updated_at` is not dirty, which is probably pretty rare in a real-world scenario - but certainly could happen, and does happen in unit tests.\r\n\r\nThis approach means that there is no changes in the user model, i.e. there isn't a new \"updatedAtFormat\" property.\r\n\r\n<img width=\"1123\" alt=\"Screen Shot 2023-08-03 at 11 33 36 am\" src=\"https://github.com/laravel/framework/assets/24803032/670b6b43-3488-4119-aae9-a3f4c44e2f79\">\r\n\r\nWould love your input on these approaches.",
"created_at": "2023-08-03T01:35:47Z"
},
{
"body": "We can follow along with this fix I have just created: #47942",
"created_at": "2023-08-03T03:22:00Z"
}
],
"number": 47769,
"title": "Cast on Updated At column not applied for rapid saves (i.e. unit tests) "
} | {
"body": "fixes #47769\r\n\r\nIf a model is using a cast on the `updated_at` column, it is not respected when the **eloquent builder** creates the `updated_at` value.\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App\\Models;\r\n\r\nuse App\\Casts\\UnixTimeStampToCarbon;\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Customer extends Model\r\n{\r\n use HasFactory;\r\n\r\n protected $casts = [\r\n 'created_at' => UnixTimeStampToCarbon::class,\r\n 'updated_at' => UnixTimeStampToCarbon::class,\r\n ];\r\n}\r\n```\r\n\r\n\r\nWhen updating a model, in most cases the `updated_at` value is created in the **eloquent model**, where the cast is respected as expected.\r\n\r\nWhen the model creates the value the builder receives the `updated_at` value in the array it is asked to put into the database. When this happens, everything is good.\r\n\r\nWhen the value of `updated_at` has not changed, i.e. the time is the same as last time it was updated - which you might find happens in a unit test - the `updated_at` is not marked as \"dirty\" and the model does not pass the `updated_at` column through to the builder.\r\n\r\nIn this case, the builder manually creates and adds the `updated_at` value to the array it is putting into the database.\r\n\r\nWhen the builder creates the `updated_at` value it does not use any casts that are in place on the model for the `updated_at` column.\r\n\r\nFor timestamp only values, if you are storing the `updated_at` as an integer, as per #47769, and not other dates, the value attempted to be insert into the database will be `2020-01-01 00:00:00` formatted and MySQL will throw an exception as it is expecting an integer.\r\n\r\n## Performance implications\r\n\r\nI ran some benchmarks using 10,000 iterations.\r\n\r\n## Updated at set by the builder, i.e. time has not progressed\r\n\r\nIf you do not have a cast in place for the `updated_at` column: there is no change ☑️\r\n\r\nIf you do have a cast in place for the `updated_at` column: `0.006ms` > `0.02ms` ⬇️\r\n\r\n## Updated at set by the model, i.e. time has progressed\r\n\r\n`0.006ms` > `0.0ms` (micro optimisation) ⬆️\r\n\r\nSo the implications are only for the cases where you have a cast in place and time has not progressed, which I would guess is 99.999999999999% of the time in a unit test and not going to impact an actual user.",
"number": 47942,
"review_comments": [
{
"body": "The outer `array_key_exists` check is a micro optimisation here, as per the performance section of the description. It can be safely removed if we don't want it.",
"created_at": "2023-08-04T04:20:17Z"
}
],
"title": "[10.x] Use model cast when builder created updated at value"
} | {
"commits": [
{
"message": "Use model cast when builder created updated at value"
},
{
"message": "lint"
},
{
"message": "Support mutators and attributes"
},
{
"message": "Force fill column"
}
],
"files": [
{
"diff": "@@ -1139,10 +1139,21 @@ protected function addUpdatedAtColumn(array $values)\n \n $column = $this->model->getUpdatedAtColumn();\n \n- $values = array_merge(\n- [$column => $this->model->freshTimestampString()],\n- $values\n- );\n+ if (! array_key_exists($column, $values)) {\n+ $timestamp = $this->model->freshTimestampString();\n+\n+ if (\n+ $this->model->hasSetMutator($column)\n+ || $this->model->hasAttributeSetMutator($column)\n+ || $this->model->hasCast($column)\n+ ) {\n+ $timestamp = $this->model->newInstance()\n+ ->forceFill([$column => $timestamp])\n+ ->getAttributes()[$column];\n+ }\n+\n+ $values = array_merge([$column => $timestamp], $values);\n+ }\n \n $segments = preg_split('/\\s+as\\s+/i', $this->query->from);\n ",
"filename": "src/Illuminate/Database/Eloquent/Builder.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,193 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\MySql;\n+\n+use Illuminate\\Contracts\\Database\\Eloquent\\CastsAttributes;\n+use Illuminate\\Database\\Eloquent\\Casts\\Attribute;\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Support\\Carbon;\n+use Illuminate\\Support\\Facades\\Schema;\n+\n+class EloquentCastTest extends MySqlTestCase\n+{\n+ protected $driver = 'mysql';\n+\n+ protected function defineDatabaseMigrationsAfterDatabaseRefreshed()\n+ {\n+ Schema::create('users', function ($table) {\n+ $table->increments('id');\n+ $table->string('email')->unique();\n+ $table->integer('created_at');\n+ $table->integer('updated_at');\n+ });\n+ }\n+\n+ protected function destroyDatabaseMigrations()\n+ {\n+ Schema::drop('users');\n+ }\n+\n+ public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasNotPassed()\n+ {\n+ Carbon::setTestNow(now());\n+ $createdAt = now()->timestamp;\n+\n+ $castUser = UserWithIntTimestampsViaCasts::create([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $attributeUser = UserWithIntTimestampsViaAttribute::create([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $mutatorUser = UserWithIntTimestampsViaMutator::create([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+\n+ $this->assertSame($createdAt, $castUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $castUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);\n+\n+ $castUser->update([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $attributeUser->update([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $mutatorUser->update([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+\n+ $this->assertSame($createdAt, $castUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $castUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $castUser->fresh()->updated_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->fresh()->updated_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->fresh()->updated_at->timestamp);\n+ }\n+\n+ public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasPassed()\n+ {\n+ Carbon::setTestNow(now());\n+ $createdAt = now()->timestamp;\n+\n+ $castUser = UserWithIntTimestampsViaCasts::create([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $attributeUser = UserWithIntTimestampsViaAttribute::create([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $mutatorUser = UserWithIntTimestampsViaMutator::create([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+\n+ $this->assertSame($createdAt, $castUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $castUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->updated_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->created_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);\n+\n+ Carbon::setTestNow(now()->addSecond());\n+ $updatedAt = now()->timestamp;\n+\n+ $castUser->update([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $attributeUser->update([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+ $mutatorUser->update([\n+ 'email' => fake()->unique()->email,\n+ ]);\n+\n+ $this->assertSame($createdAt, $castUser->created_at->timestamp);\n+ $this->assertSame($updatedAt, $castUser->updated_at->timestamp);\n+ $this->assertSame($updatedAt, $castUser->fresh()->updated_at->timestamp);\n+ $this->assertSame($createdAt, $attributeUser->created_at->timestamp);\n+ $this->assertSame($updatedAt, $attributeUser->updated_at->timestamp);\n+ $this->assertSame($updatedAt, $attributeUser->fresh()->updated_at->timestamp);\n+ $this->assertSame($createdAt, $mutatorUser->created_at->timestamp);\n+ $this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);\n+ $this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);\n+ }\n+}\n+\n+class UserWithIntTimestampsViaCasts extends Model\n+{\n+ protected $table = 'users';\n+\n+ protected $fillable = ['email'];\n+\n+ protected $casts = [\n+ 'created_at' => UnixTimeStampToCarbon::class,\n+ 'updated_at' => UnixTimeStampToCarbon::class,\n+ ];\n+}\n+\n+class UnixTimeStampToCarbon implements CastsAttributes\n+{\n+ public function get($model, string $key, $value, array $attributes)\n+ {\n+ return Carbon::parse($value);\n+ }\n+\n+ public function set($model, string $key, $value, array $attributes)\n+ {\n+ return Carbon::parse($value)->timestamp;\n+ }\n+}\n+\n+class UserWithIntTimestampsViaAttribute extends Model\n+{\n+ protected $table = 'users';\n+\n+ protected $fillable = ['email'];\n+\n+ protected function updatedAt(): Attribute\n+ {\n+ return Attribute::make(\n+ get: fn ($value) => Carbon::parse($value),\n+ set: fn ($value) => Carbon::parse($value)->timestamp,\n+ );\n+ }\n+\n+ protected function createdAt(): Attribute\n+ {\n+ return Attribute::make(\n+ get: fn ($value) => Carbon::parse($value),\n+ set: fn ($value) => Carbon::parse($value)->timestamp,\n+ );\n+ }\n+}\n+\n+class UserWithIntTimestampsViaMutator extends Model\n+{\n+ protected $table = 'users';\n+\n+ protected $fillable = ['email'];\n+\n+ protected function getUpdatedAtAttribute($value)\n+ {\n+ return Carbon::parse($value);\n+ }\n+\n+ protected function setUpdatedAtAttribute($value)\n+ {\n+ $this->attributes['updated_at'] = Carbon::parse($value)->timestamp;\n+ }\n+\n+ protected function getCreatedAtAttribute($value)\n+ {\n+ return Carbon::parse($value);\n+ }\n+\n+ protected function setCreatedAtAttribute($value)\n+ {\n+ $this->attributes['created_at'] = Carbon::parse($value)->timestamp;\n+ }\n+}",
"filename": "tests/Integration/Database/MySql/EloquentCastTest.php",
"status": "added"
}
]
} |
{
"body": "### Laravel Version\n\n10.16.0\n\n### PHP Version\n\n8.2.7\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nThe `ofMany` function in `CanBeOneOfMany` trait breaks when only providing the `aggregate` parameter with a closure because it tries to use `strtolower` with the closure, and if the `column` is set to null (wich the DocComment says it can) it breaks again trying to use `array_key_exists` on null.\r\n\r\nBoth problems can be fixed changin lines 79-82 with:\r\n```php\r\n$columns = is_string($columns = $column) ? [\r\n $column => $aggregate,\r\n $keyName => $aggregate,\r\n] : ($column ?? []);\r\n```\r\n\r\nand letting the default values of `column` and `aggregate` to null.\n\n### Steps To Reproduce\n\nCreate a Model with the following relation:\r\n```php\r\npublic function books(): HasMany\r\n{\r\n return $this->hasMany(Book::class);\r\n}\r\n```\r\nAnd any of the next relations:\r\n```php\r\npublic function book(): HasOne\r\n{\r\n return $this->books()->one()->ofMany(aggregate: fn ($query) => $query->where('some_field', true));\r\n}\r\n```\r\n```php\r\npublic function book(): HasOne\r\n{\r\n return $this->books()->one()->ofMany(null, fn ($query) => $query->where('some_field', true));\r\n}\r\n```",
"comments": [
{
"body": "Thanks. Are you willing to send in a PR?",
"created_at": "2023-07-26T08:52:25Z"
},
{
"body": "I don't see this way of using `ofMany` documented anywhere in our documentation. Perhaps the DocBlock should be changed.",
"created_at": "2023-07-28T19:52:56Z"
}
],
"number": 47836,
"title": "ofMany fails when using only aggregate or when column is null"
} | {
"body": "The DocComment of the function `ofMany` in trait `CanBeOneOfMany` states that `columns` and/or `aggregate` can be null, however if any of those are null the function breaks either in function `array_key_exists` or in `strtolower`.\r\n\r\nAlso if only the `aggregate` parameter is passed as a Closure the function will also break in `strtolower`.\r\n\r\nThis PR will prevent those cases, the function will always fallback to `column` 'id' if null given with the MAX aggregate. This will make the api cleaner when the user only wants to use an aggregate closure.\r\n\r\nfixes issue #47836",
"number": 47885,
"review_comments": [],
"title": "Fix ofMany null column or only aggregate"
} | {
"commits": [
{
"message": "fix ofMany null column only aggregate"
},
{
"message": "prevent break on nulls or only aggregate"
},
{
"message": "test can use only aggregate function"
}
],
"files": [
{
"diff": "@@ -76,6 +76,14 @@ public function ofMany($column = 'id', $aggregate = 'MAX', $relation = null)\n \n $keyName = $this->query->getModel()->getKeyName();\n \n+ $column = is_null($column) ? [] : $column;\n+ $aggregate ??= 'MAX';\n+\n+ if ($aggregate instanceof Closure) {\n+ $closure = $aggregate;\n+ $aggregate = 'MAX';\n+ }\n+\n $columns = is_string($columns = $column) ? [\n $column => $aggregate,\n $keyName => $aggregate,\n@@ -85,10 +93,6 @@ public function ofMany($column = 'id', $aggregate = 'MAX', $relation = null)\n $columns[$keyName] = 'MAX';\n }\n \n- if ($aggregate instanceof Closure) {\n- $closure = $aggregate;\n- }\n-\n foreach ($columns as $column => $aggregate) {\n if (! in_array(strtolower($aggregate), ['min', 'max'])) {\n throw new InvalidArgumentException(\"Invalid aggregate [{$aggregate}] used within ofMany relation. Available aggregates: MIN, MAX\");",
"filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php",
"status": "modified"
},
{
"diff": "@@ -486,6 +486,19 @@ public function testWithContraintNotInAggregate()\n $this->assertSame($newFoo->id, $user->last_updated_foo_state->id);\n }\n \n+ public function testCanProvideOnlyAggregateFunction()\n+ {\n+ $user = HasOneOfManyTestUser::create();\n+ $user->prices()->create([\n+ 'published_at' => today(),\n+ ]);\n+ $lastMonthPrice = $user->prices()->create([\n+ 'published_at' => today()->subMonth(),\n+ ]);\n+\n+ $this->assertSame($lastMonthPrice->id, $user->price_last_month->id);\n+ }\n+\n /**\n * Get a database connection instance.\n *\n@@ -612,6 +625,13 @@ public function price_with_shortcut()\n return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->latestOfMany(['published_at', 'id']);\n }\n \n+ public function price_last_month()\n+ {\n+ return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->ofMany(null, function ($q) {\n+ $q->where('published_at', '<', today()->startOfMonth());\n+ });\n+ }\n+\n public function price_without_global_scope()\n {\n return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->withoutGlobalScopes()->ofMany([",
"filename": "tests/Database/DatabaseEloquentHasOneOfManyTest.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.15.0\r\n\r\n### PHP Version\r\n\r\n8.2.7\r\n\r\n### Database Driver & Version\r\n\r\nNot applicable\r\n\r\n### Description\r\n\r\nI have multiple scheduled closures, using `$schedule->call(...)` in the `app/Console/Kernel::schedule()` method. When I run `php artisan schedule:test`, all scheduled closures show up in the task list with the name `Callback`. No matter which closure-based task index number I input, the first scheduled closure task is run.\r\n\r\nIt looks to me like this is because the code which chooses a task based on user input bases its task search on the task name that's generated by the `schedule:test` command, rather than the index number inputted by the user. See here:\r\n\r\nhttps://github.com/laravel/framework/blob/9c44052743b0ee7f3adea36994918b4d8019e8b3/src/Illuminate/Console/Scheduling/ScheduleTestCommand.php#L62-L66\r\n\r\nSince all the closure tasks have the same `$commandName`, `$index` always ends up being the first closure task.\r\n\r\nThere's a second part of the problem that I noticed while reading the code: if you run `php artisan schedule:test --name Callback` with multiple closure-based tasks, you get the message `No matching scheduled command found.`, because there is more than one match found:\r\n\r\nhttps://github.com/laravel/framework/blob/9c44052743b0ee7f3adea36994918b4d8019e8b3/src/Illuminate/Console/Scheduling/ScheduleTestCommand.php#L48-L59\r\n\r\nHappy to make a PR for this if that would be welcome. Repro steps below.\r\n\r\n### Steps To Reproduce\r\n\r\nMy reproduction repo is here: https://github.com/jlevers/laravel-schedule-test-bug-repro\r\n\r\nNote that these two lines are the only thing I added to the base repo produced by `laravel new bug-report --github=\"public\"`:\r\n\r\n```php\r\n$schedule->call(fn () => logger()->debug('first callback'))->everyMinute();\r\n$schedule->call(fn () => logger()->debug('second callback'))->everyMinute();\r\n```\r\n\r\nSteps to reproduce:\r\n```\r\n$ git clone git@github.com:jlevers/laravel-schedule-test-bug-repro.git && cd laravel-schedule-test-bug-repro\r\n$ composer install\r\n$ php artisan schedule:test\r\n\r\n Which command would you like to run?\r\n Callback ....................................................................................................................................... 0 \r\n Callback ....................................................................................................................................... 1\r\n> 1\r\n Running [Callback] ...................................................................................................................... 7ms DONE\r\n```\r\n\r\nIf you check your logs, you should see `local.DEBUG: first callback`, even though we selected the index of the second task.\r\n\r\nTo reproduce the second problem I mentioned:\r\n\r\n```\r\n$ php artisan schedule:test --name Callback\r\n\r\n INFO No matching scheduled command found\r\n```\r\n\r\nThere are in fact two matching commands, so that message is clearly wrong.",
"comments": [
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-07-26T09:03:58Z"
},
{
"body": "Thanks for this detailed issue! Would be cool to get a PR for this with passing tests.",
"created_at": "2023-07-26T09:04:34Z"
},
{
"body": "Looks like we won't be making any changes for this sorry. Please use unique names for commands.",
"created_at": "2023-07-28T14:18:09Z"
},
{
"body": "Hi @driesvints @taylorotwell \r\n\r\nI understand that we can avoid this issue by using unique names for commands like\r\n```\r\nprotected function schedule(Schedule $schedule): void\r\n{\r\n $schedule->call(fn () => logger()->debug('first callback'))->everyMinute()->name('first command');\r\n $schedule->call(fn () => logger()->debug('second callback'))->everyMinute()->name('second command');\r\n}\r\n```\r\nthough here are a few inputs from my end on this if you would like to take this into consideration\r\n\r\nif you add these two lines in this file `\\app\\Console\\Kernel.php`\r\n```\r\nprotected function schedule(Schedule $schedule): void\r\n{\r\n $schedule->call(fn () => logger()->debug('first callback'))->everyMinute();\r\n $schedule->call(fn () => logger()->debug('second callback'))->everyMinute();\r\n}\r\n```\r\nthe command names will be auto-generated as `Callback`\r\n\r\nbecause of the below code inside this file - `laravel\\framework\\src\\Illuminate\\Console\\Scheduling\\CallbackEvent.php`\r\n```\r\npublic function getSummaryForDisplay()\r\n{\r\n if (is_string($this->description)) {\r\n return $this->description;\r\n }\r\n return is_string($this->callback) ? $this->callback : 'Callback';\r\n}\r\n```\r\nthat function will be triggered from here - `laravel\\framework\\src\\Illuminate\\Console\\Scheduling\\ScheduleTestCommand.php`\r\n```\r\nforeach ($commands as $command) {\r\n $commandNames[] = $command->command ?? $command->getSummaryForDisplay();\r\n}\r\n```\r\n\r\nso the PR I provided above had logic to show a prompt to users stating multiple command names found and which one would they like to run?\r\nalso in any case if there are more then one command found with the same name\r\nyou get the message `\"No matching scheduled command found\"` because there is more than one match found. the message itself could be misleading\r\n\r\nwould love to know your thoughts on this please\r\ndo let me know if any changes are needed in the [pull request](https://github.com/laravel/framework/pull/47875) as well\r\n\r\nThanks",
"created_at": "2023-07-28T14:44:01Z"
},
{
"body": "We have no plans to make changes here, sorry. Please use unique names for all commands just like on web routes.",
"created_at": "2023-07-28T15:39:05Z"
}
],
"number": 47783,
"title": "`artisan schedule:test` cannot differentiate between scheduled closures"
} | {
"body": "This pull request addresses two issues related to the `schedule:test` command when dealing with multiple closure-based scheduled commands.\r\n\r\nCloses #47783 \r\n\r\n**Issue:** Incorrect message when using the `--name` option with multiple matching commands\r\n- Previously, when using the command `php artisan schedule:test --name <name>`, if multiple commands found then the returned message was `\"No matching scheduled command found.\"` even if multiple commands with the same name existed. This was misleading.\r\n- Solution:\r\n 1. Updated the logic to display the `\"No matching scheduled command found\"` message only when no command with the given name exists.\r\n 2. Implemented new logic to prompt the user to choose the desired command when multiple commands match the given description.\r\n\r\nApart from the above, another bug was also fixed which was reported in that issue in another PR, so this issue can be closed, description is given below\r\n\r\n**Issue:** Incorrectly selecting scheduled closures by index number\r\n- The `php artisan schedule:test` command allowed users to select a task by its index number, but the task selection logic was based on the task name generated by the `schedule:test` command, causing all closure-based tasks to have the same name.\r\n- Solution: Modified the command to display options with their respective index numbers. Now, when the user selects an option, the correct task associated with that index is executed.\r\nPR for Above issue is already merged - https://github.com/laravel/framework/pull/47862\r\n",
"number": 47875,
"review_comments": [],
"title": "fixed No matching scheduled command found issue"
} | {
"commits": [
{
"message": "fixed No matching scheduled command found issue"
},
{
"message": "fixed formatting"
}
],
"files": [
{
"diff": "@@ -52,13 +52,17 @@ public function handle(Schedule $schedule)\n return trim(str_replace($commandBinary, '', $commandName)) === $name;\n });\n \n- if (count($matches) !== 1) {\n+ if (count($matches) === 0) {\n $this->components->info('No matching scheduled command found.');\n \n return;\n }\n \n $index = key($matches);\n+\n+ if (count($matches) > 1) {\n+ $index = $this->getSelectedCommandByIndex($matches);\n+ }\n } else {\n $index = $this->getSelectedCommandByIndex($commandNames);\n }",
"filename": "src/Illuminate/Console/Scheduling/ScheduleTestCommand.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\n\n10.16.0\n\n### PHP Version\n\n8.2.7\n\n### Database Driver & Version\n\n_No response_\n\n### Description\n\nThe `ofMany` function in `CanBeOneOfMany` trait breaks when only providing the `aggregate` parameter with a closure because it tries to use `strtolower` with the closure, and if the `column` is set to null (wich the DocComment says it can) it breaks again trying to use `array_key_exists` on null.\r\n\r\nBoth problems can be fixed changin lines 79-82 with:\r\n```php\r\n$columns = is_string($columns = $column) ? [\r\n $column => $aggregate,\r\n $keyName => $aggregate,\r\n] : ($column ?? []);\r\n```\r\n\r\nand letting the default values of `column` and `aggregate` to null.\n\n### Steps To Reproduce\n\nCreate a Model with the following relation:\r\n```php\r\npublic function books(): HasMany\r\n{\r\n return $this->hasMany(Book::class);\r\n}\r\n```\r\nAnd any of the next relations:\r\n```php\r\npublic function book(): HasOne\r\n{\r\n return $this->books()->one()->ofMany(aggregate: fn ($query) => $query->where('some_field', true));\r\n}\r\n```\r\n```php\r\npublic function book(): HasOne\r\n{\r\n return $this->books()->one()->ofMany(null, fn ($query) => $query->where('some_field', true));\r\n}\r\n```",
"comments": [
{
"body": "Thanks. Are you willing to send in a PR?",
"created_at": "2023-07-26T08:52:25Z"
},
{
"body": "I don't see this way of using `ofMany` documented anywhere in our documentation. Perhaps the DocBlock should be changed.",
"created_at": "2023-07-28T19:52:56Z"
}
],
"number": 47836,
"title": "ofMany fails when using only aggregate or when column is null"
} | {
"body": "The DocComment of the function `ofMany` in trait `CanBeOneOfMany` states that `columns` and/or `aggregate` can be null, however if any of those are null the function breaks either in function `array_key_exists` or in `strtolower`.\r\n\r\nAlso if only the `aggregate` parameter is passed as a Closure the function will also break in `strtolower`.\r\n\r\nThis PR will prevent those cases, the function will always fallback to `column` 'id' if null given with the MAX aggregate.\r\n\r\nfixes issue #47836",
"number": 47845,
"review_comments": [],
"title": "fix ofMany null column or only aggregate"
} | {
"commits": [
{
"message": "fix ofMany null column only aggregate"
}
],
"files": [
{
"diff": "@@ -66,7 +66,7 @@ abstract public function addOneOfManyJoinSubQueryConstraints(JoinClause $join);\n *\n * @throws \\InvalidArgumentException\n */\n- public function ofMany($column = 'id', $aggregate = 'MAX', $relation = null)\n+ public function ofMany($column = null, $aggregate = null, $relation = null)\n {\n $this->isOneOfMany = true;\n \n@@ -76,6 +76,8 @@ public function ofMany($column = 'id', $aggregate = 'MAX', $relation = null)\n \n $keyName = $this->query->getModel()->getKeyName();\n \n+ $column = is_null($column) ? [] : $column;\n+\n $columns = is_string($columns = $column) ? [\n $column => $aggregate,\n $keyName => $aggregate,",
"filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php",
"status": "modified"
}
]
} |
{
"body": "### Laravel Version\r\n\r\n10.13.5\r\n\r\n### PHP Version\r\n\r\n8.2.7\r\n\r\n### Database Driver & Version\r\n\r\nN/A\r\n\r\n### Description\r\n\r\nCasting a model attribute to an enum _does not_ prevent assigning the attribute to a different enum or a value not defined as a case on the enum.\r\n\r\nFor example, if an attribute is cast to `SomeEnum` you can freely set/update the value of that attribute to `AnotherEnum::WHATEVER` or any primitive value. In this event, if the backed value of `AnotherEnum::WHATEVER` or the primitive value matches a case on `SomeEnum` when we retrieve the model from the DB we will get an instance of `SomeEnum` back (fine, but unexpected). However, if the backed value of `AnotherEnum::WHATEVER` or the primitive value _does not_ match a case on `SomeEnum` we will get a `ValueError` on retrieval of the model since it can't create the `SomeEnum` from the value stored in the DB (i.e. `SomeEnum::from($value)`).\r\n\r\nI believe the intent to allow setting an (uncast) attribute to an enum is at least somewhat intentional. However, **when the attribute is cast to a specific enum and attempting to assigning it to a _different_ enum or a string that is _not_ defined as a case on the enum should result in a error**. This would proactively avoid storing an incorrect value in the DB, prevent the `ValueError` on retrieval and preserve the benefits of using enums in the first place.\r\n\r\nIf this sounds like a reasonable change I can create a PR for this. Let me know what you think.\r\n\r\n**NOTE:** For your reference and mine [here](https://github.com/laravel/framework/blob/ea5172eb59d4ecd87379591c2a2e34c96ca7d068/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L1166-L1191) is the code that sets and gets the value for an attribute cast to an enum.\r\n\r\n### Steps To Reproduce\r\n\r\nCreate some enums.\r\n\r\n```php\r\nnamespace App\\Models\\Enums;\r\n\r\nenum SomeEnum: string\r\n{\r\n case FOO = 'foo';\r\n case BAR = 'bar';\r\n}\r\n``` \r\n\r\n```php\r\nnamespace App\\Models\\Enums;\r\n\r\nenum AnotherEnum: string\r\n{\r\n case BAR = 'bar';\r\n case BAZ = 'baz';\r\n}\r\n```\r\n\r\nCreate a Model with an attribute cast to one of the enums.\r\n\r\n```php\r\nnamespace App\\Models;\r\n\r\nuse App\\Models\\Enums\\SomeEnum;\r\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Example extends Model\r\n{\r\n use HasFactory;\r\n\r\n protected $casts = [\r\n 'some_enum' => SomeEnum::class,\r\n ];\r\n}\r\n```\r\n\r\nSet the attribute to the incorrect enum value.\r\n\r\n\r\n```php\r\n> $example = Example::factory()->makeOne(['some_enum' => SomeEnum::FOO])\r\n= App\\Models\\Example {#6992\r\n some_enum: \"foo\",\r\n }\r\n\r\n> $example->some_enum\r\n= App\\Models\\Enums\\SomeEnum {#6239\r\n +name: \"FOO\",\r\n +value: \"foo\",\r\n }\r\n\r\n> $example->some_enum = AnotherEnum::BAR\r\n= App\\Models\\Enums\\AnotherEnum {#6243\r\n +name: \"BAR\",\r\n +value: \"bar\",\r\n }\r\n\r\n> $example->some_enum\r\n= App\\Models\\Enums\\SomeEnum {#6238\r\n +name: \"BAR\",\r\n +value: \"bar\",\r\n }\r\n\r\n> $example->some_enum = AnotherEnum::BAZ\r\n= App\\Models\\Enums\\AnotherEnum {#6211\r\n +name: \"BAZ\",\r\n +value: \"baz\",\r\n }\r\n\r\n> $example->some_enum\r\n\r\n ValueError \"baz\" is not a valid backing value for enum App\\Models\\Enums\\SomeEnum.\r\n```",
"comments": [
{
"body": "Thank you for reporting this issue!\n\nAs Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.\n\nIf possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.\n\nThank you!",
"created_at": "2023-06-16T16:28:19Z"
},
{
"body": "Hi @PHLAK. Thanks for the detailed report. This indeed seems problematic to me. I think we should also throw a ValueError when you try to assign an incorrect enum. Could you send in a PR? Thanks!",
"created_at": "2023-06-16T16:28:46Z"
},
{
"body": "Thanks @driesvints, I will work on a PR for this.",
"created_at": "2023-06-16T16:29:53Z"
}
],
"number": 47454,
"title": "Casting a model attribute to an enum does not prevent assigning the attribute to a different enum"
} | {
"body": "Prevent an attribute that is cast to an enum from being set to another enum value or a value not defined as a case on a `BackedEnum`. This will throw a `ValueError` like the following when attempting to do so.\r\n\r\n```\r\nValue [\\App\\SomeEnum::CASE] is not of the expected enum type [\\App\\AnotherEnum]\r\n``` \r\n\r\n**NOTE:** This is technically a _breaking change_ but I'd consider it more of a bug fix so handle that as you will.\r\n\r\nResolves #47454",
"number": 47465,
"review_comments": [
{
"body": "This is a breaking change unfortunately. We can't change a method signature in a patch release.",
"created_at": "2023-06-16T18:24:16Z"
},
{
"body": "Even though this is a `protected` method? Can we think of an alternative way of accomplishing this that wont be a breaking change?",
"created_at": "2023-06-16T18:25:45Z"
},
{
"body": "The only alternative I can see would be to add the `instanceof` check before calling `getStorableEnumValue()` (i.e. in `addCastAttributesToArray()` and `setEnumCastableAttribute()`).\r\n\r\nThe downside of this is duplicate code and if `getStorableEnumValue()` were to be added anywhere else in the future we'd need to remember to add the `instanceof` check there as well.\r\n\r\nThis doesn't seem like a good idea to me.\r\n\r\nShould I update the PR to target `master` (`11.x`) instead?",
"created_at": "2023-06-16T18:47:01Z"
},
{
"body": "If we can't do it differently then yeah master might be the only option",
"created_at": "2023-06-16T18:56:17Z"
}
],
"title": "[11.x] Prevent attributes cast to an enum from being set to another enum"
} | {
"commits": [
{
"message": "Prevent attributes cast to an enum from being set to another enum"
},
{
"message": "formatting"
}
],
"files": [
{
"diff": "@@ -39,6 +39,7 @@\n use ReflectionClass;\n use ReflectionMethod;\n use ReflectionNamedType;\n+use ValueError;\n \n trait HasAttributes\n {\n@@ -309,7 +310,7 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt\n }\n \n if ($this->isEnumCastable($key) && (! ($attributes[$key] ?? null) instanceof Arrayable)) {\n- $attributes[$key] = isset($attributes[$key]) ? $this->getStorableEnumValue($attributes[$key]) : null;\n+ $attributes[$key] = isset($attributes[$key]) ? $this->getStorableEnumValue($this->getCasts()[$key], $attributes[$key]) : null;\n }\n \n if ($attributes[$key] instanceof Arrayable) {\n@@ -1155,10 +1156,10 @@ protected function setEnumCastableAttribute($key, $value)\n if (! isset($value)) {\n $this->attributes[$key] = null;\n } elseif (is_object($value)) {\n- $this->attributes[$key] = $this->getStorableEnumValue($value);\n+ $this->attributes[$key] = $this->getStorableEnumValue($enumClass, $value);\n } else {\n $this->attributes[$key] = $this->getStorableEnumValue(\n- $this->getEnumCaseFromValue($enumClass, $value)\n+ $enumClass, $this->getEnumCaseFromValue($enumClass, $value)\n );\n }\n }\n@@ -1180,11 +1181,16 @@ protected function getEnumCaseFromValue($enumClass, $value)\n /**\n * Get the storable value from the given enum.\n *\n+ * @param string $expectedEnum\n * @param \\UnitEnum|\\BackedEnum $value\n * @return string|int\n */\n- protected function getStorableEnumValue($value)\n+ protected function getStorableEnumValue($expectedEnum, $value)\n {\n+ if (! $value instanceof $expectedEnum) {\n+ throw new ValueError(sprintf('Value [%s] is not of the expected enum type [%s].', var_export($value, true), $expectedEnum));\n+ }\n+\n return $value instanceof BackedEnum\n ? $value->value\n : $value->name;",
"filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
"status": "modified"
},
{
"diff": "@@ -8,6 +8,7 @@\n use Illuminate\\Database\\Schema\\Blueprint;\n use Illuminate\\Support\\Facades\\DB;\n use Illuminate\\Support\\Facades\\Schema;\n+use ValueError;\n \n include 'Enums.php';\n \n@@ -264,6 +265,39 @@ public function testFirstOrCreate()\n $this->assertEquals(StringStatus::pending, $model->string_status);\n $this->assertEquals(StringStatus::done, $model2->string_status);\n }\n+\n+ public function testAttributeCastToAnEnumCanNotBeSetToAnotherEnum(): void\n+ {\n+ $model = new EloquentModelEnumCastingTestModel;\n+\n+ $this->expectException(ValueError::class);\n+ $this->expectExceptionMessage(\n+ sprintf('Value [%s] is not of the expected enum type [%s].', var_export(ArrayableStatus::pending, true), StringStatus::class)\n+ );\n+\n+ $model->string_status = ArrayableStatus::pending;\n+ }\n+\n+ public function testAttributeCastToAnEnumCanNotBeSetToAValueNotDefinedOnTheEnum(): void\n+ {\n+ $model = new EloquentModelEnumCastingTestModel;\n+\n+ $this->expectException(ValueError::class);\n+ $this->expectExceptionMessage(\n+ sprintf('\"unexpected_value\" is not a valid backing value for enum %s', StringStatus::class)\n+ );\n+\n+ $model->string_status = 'unexpected_value';\n+ }\n+\n+ public function testAnAttributeWithoutACastCanBeSetToAnEnum(): void\n+ {\n+ $model = new EloquentModelEnumCastingTestModel;\n+\n+ $model->non_enum_status = StringStatus::pending;\n+\n+ $this->assertEquals(StringStatus::pending, $model->non_enum_status);\n+ }\n }\n \n class EloquentModelEnumCastingTestModel extends Model",
"filename": "tests/Integration/Database/EloquentModelEnumCastingTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.50.1\r\n- PHP Version: 8.2.1\r\n- Database Driver & Version: (irrelevant)\r\n\r\n### Description:\r\n[Escaping Blade directives](https://laravel.com/docs/9.x/blade#blade-and-javascript-frameworks) with `@` symbol is broken in some cases.\r\n\r\n### Steps To Reproduce:\r\n\r\nConsider this valid blade:\r\n```\r\n@php\r\n $columns = [];\r\n $locales = [];\r\n@endphp\r\n\r\n@foreach($columns as $col)\r\n @if($col == 'foo')\r\n <div></div>\r\n @elseif($col == 'bar')\r\n @@foreach($locales as $locale)\r\n <div></div>\r\n @@endforeach\r\n @else\r\n <div></div>\r\n @endif\r\n@endforeach\r\n```\r\n\r\nExpected behaviour:\r\nBlade will complile. Double `@@` should just produce one `@`, just like written in the documentation (and how it worked few weeks ago, something must have break just lately).\r\n\r\nI'm getting:\r\n```\r\nsyntax error, unexpected token \"endforeach\", expecting \"elseif\" or \"else\" or \"endif\"\r\n```\r\n\r\nOne solution is to instead of using `@@` to use `{{'@'}}`. If you prefer this solution, then please update the documentation so this is the recommended way.\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Seems to be caused by https://github.com/laravel/framework/pull/45490 in v9.47",
"created_at": "2023-02-02T16:33:52Z"
},
{
"body": "@imanghafoori1 this (https://github.com/laravel/framework/pull/45490) is still broken. I think we need to revert everything back to its original state?",
"created_at": "2023-02-02T16:35:14Z"
},
{
"body": "I take a look into that right now, I need a few hours to investigate the problem.",
"created_at": "2023-02-02T17:57:27Z"
}
],
"number": 45915,
"title": "Escaping Blade directives with @@ is broken"
} | {
"body": "This fixes #45915\r\n\r\nIn the added test there are 4 matches, in the second replacement `@@endforeach` with `@endforeach` in the second replacement.\r\n\r\nThen the final replacement searches for `@endforeach` to replace it with the compiled version, but it finds what was produced by the previously escaped tag because it starts the search from the beginning of the string.\r\n\r\n### Solution:\r\nLogically when replacing the matches found by REGEX one after the other using `Str::replaceFirst`, we have to continue from where we last left off.",
"number": 45928,
"review_comments": [],
"title": "[9.x] Fixes blade escaped tags issue"
} | {
"commits": [
{
"message": "Fixes blade escaped tags issue"
},
{
"message": "formatting"
}
],
"files": [
{
"diff": "@@ -507,6 +507,8 @@ protected function compileStatements($template)\n {\n preg_match_all('/\\B@(@?\\w+(?:::\\w+)?)([ \\t]*)(\\( ( [\\S\\s]*? ) \\))?/x', $template, $matches);\n \n+ $offset = 0;\n+\n for ($i = 0; isset($matches[0][$i]); $i++) {\n $match = [\n $matches[0][$i],\n@@ -538,12 +540,46 @@ protected function compileStatements($template)\n $match[4] = $match[4].$rest;\n }\n \n- $template = Str::replaceFirst($match[0], $this->compileStatement($match), $template);\n+ [$template, $offset] = $this->replaceFirstStatement(\n+ $match[0],\n+ $this->compileStatement($match),\n+ $template,\n+ $offset\n+ );\n }\n \n return $template;\n }\n \n+ /**\n+ * Replace the first match for a statement compilation operation.\n+ *\n+ * @param string $search\n+ * @param string $replace\n+ * @param string $subject\n+ * @param int $offset\n+ * @return array\n+ */\n+ protected function replaceFirstStatement($search, $replace, $subject, $offset)\n+ {\n+ $search = (string) $search;\n+\n+ if ($search === '') {\n+ return $subject;\n+ }\n+\n+ $position = strpos($subject, $search, $offset);\n+\n+ if ($position !== false) {\n+ return [\n+ substr_replace($subject, $replace, $position, strlen($search)),\n+ $position + strlen($replace)\n+ ];\n+ }\n+\n+ return [$subject, 0];\n+ }\n+\n /**\n * Determine if the given expression has the same number of opening and closing parentheses.\n *",
"filename": "src/Illuminate/View/Compilers/BladeCompiler.php",
"status": "modified"
},
{
"diff": "@@ -16,4 +16,19 @@ public function testEscapedWithAtDirectivesAreCompiled()\n $i as $x\n )'));\n }\n+\n+ public function testNestedEscapes()\n+ {\n+ $template = '\n+@foreach($cols as $col)\n+ @@foreach($issues as $issue_45915)\n+ @@endforeach\n+@endforeach';\n+ $compiled = '\n+<?php $__currentLoopData = $cols; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $col): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>\n+ @foreach($issues as $issue_45915)\n+ @endforeach\n+<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>';\n+ $this->assertSame($compiled, $this->compiler->compileString($template));\n+ }\n }",
"filename": "tests/View/Blade/BladeEscapedTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: v9.46.0\r\n- PHP Version: 8.1\r\n- Database Driver & Version: MySql 5.7\r\n\r\n### Description:\r\nhttps://github.com/laravel/framework/pull/45453 On this pr and in the release of 9.46 the behaviour of findMany changed.\r\nConsider the following query Category::query()->findMany($categoryIds) where the categoryIds has the following format:\r\narray:2 [ \r\n 0 => array:1 [\r\n \"category_id\" => 34234234\r\n ],\r\n 1 => array:1 [\r\n \"category_id\" => 6756767567\r\n ]\r\n];\r\n\r\nAnd because it would use the regular whereIn method it would basically flatten the array resulting in the query \r\n\"where id IN (34234234,6756767567)\".\r\n\r\nAfter that change we are using the IntegerInRaw which casts the array to int resulting in the query of where id IN (1,1).\r\n\r\n\r\nDon't know if that was intentional or not but it does change the previous behaviour.\r\n\r\n### Steps To Reproduce:\r\nBasically pass an array of arrays in the findMany in latest version of the framework\r\n",
"comments": [
{
"body": "Thanks for your report. We're reverting this.",
"created_at": "2023-01-10T10:02:44Z"
},
{
"body": "@Boorinio Thanks for mentioning it. I proposed a fix here: #45584 ",
"created_at": "2023-01-10T11:12:31Z"
},
{
"body": "> @Boorinio Thanks for mentioning it. I proposed a fix here: #45584\r\n\r\nYeah seems fine! ",
"created_at": "2023-01-10T11:58:28Z"
}
],
"number": 45582,
"title": "findMany breaking change"
} | {
"body": "This fixes #45582 \r\nSince the `Builder\\Query` flattens the binding array before applying it a method like `whereIn` can accept an associative array as its second argument (as demonstrated in the added tests).\r\nSo to make `whereIntegerInRaw` compatible with `whereIn` we need to flatten the values before casting it to int.\r\n@staudenmeir \r\n\r\n- Missing tests are added.\r\n\r\n\r\n\r\n- The `whereIn` method tries to avoid accepting nested arrays as `$values` with the check below, but it is not enough and can be bypassed with an input like this:\r\n```\r\n ->whereIn('id', [\r\n ['id' => 1 ], \r\n ['id' => 2 ]\r\n ]) \r\n``` \r\n\r\nand due to the above flattening, it will continue to work as if it was called like this:\r\n```\r\n->whereIn('id', [1, 2])\r\n ```\r\n\r\n\r\n\r\n",
"number": 45584,
"review_comments": [],
"title": "[9.x] Fixes 45582 issue 🔧"
} | {
"commits": [
{
"message": "Fixes 45582 issue"
},
{
"message": "Update Builder.php"
}
],
"files": [
{
"diff": "@@ -1094,6 +1094,8 @@ public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = fal\n $values = $values->toArray();\n }\n \n+ $values = Arr::flatten($values);\n+\n foreach ($values as &$value) {\n $value = (int) $value;\n }",
"filename": "src/Illuminate/Database/Query/Builder.php",
"status": "modified"
},
{
"diff": "@@ -936,12 +936,46 @@ public function testBasicWhereIns()\n $this->assertSame('select * from \"users\" where \"id\" in (?, ?, ?)', $builder->toSql());\n $this->assertEquals([0 => 1, 1 => 2, 2 => 3], $builder->getBindings());\n \n+ // associative arrays as values:\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->whereIn('id', [\n+ 'issue' => 45582,\n+ 'id' => 2,\n+ 3,\n+ ]);\n+ $this->assertSame('select * from \"users\" where \"id\" in (?, ?, ?)', $builder->toSql());\n+ $this->assertEquals([0 => 45582, 1 => 2, 2 => 3], $builder->getBindings());\n+\n+ // can accept some nested arrays as values.\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->whereIn('id', [\n+ ['issue' => 45582],\n+ ['id' => 2],\n+ [3],\n+ ]);\n+ $this->assertSame('select * from \"users\" where \"id\" in (?, ?, ?)', $builder->toSql());\n+ $this->assertEquals([0 => 45582, 1 => 2, 2 => 3], $builder->getBindings());\n+\n $builder = $this->getBuilder();\n $builder->select('*')->from('users')->where('id', '=', 1)->orWhereIn('id', [1, 2, 3]);\n $this->assertSame('select * from \"users\" where \"id\" = ? or \"id\" in (?, ?, ?)', $builder->toSql());\n $this->assertEquals([0 => 1, 1 => 1, 2 => 2, 3 => 3], $builder->getBindings());\n }\n \n+ public function testBasicWhereInsException()\n+ {\n+ $this->expectException(InvalidArgumentException::class);\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->whereIn('id', [\n+ [\n+ 'a' => 1,\n+ 'b' => 1,\n+ ],\n+ ['c' => 2],\n+ [3],\n+ ]);\n+ }\n+\n public function testBasicWhereNotIns()\n {\n $builder = $this->getBuilder();\n@@ -999,6 +1033,15 @@ public function testWhereIntegerInRaw()\n $builder->select('*')->from('users')->whereIntegerInRaw('id', ['1a', 2]);\n $this->assertSame('select * from \"users\" where \"id\" in (1, 2)', $builder->toSql());\n $this->assertEquals([], $builder->getBindings());\n+\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->whereIntegerInRaw('id', [\n+ ['id' => '1a'],\n+ ['id' => 2],\n+ ['any' => '3'],\n+ ]);\n+ $this->assertSame('select * from \"users\" where \"id\" in (1, 2, 3)', $builder->toSql());\n+ $this->assertEquals([], $builder->getBindings());\n }\n \n public function testOrWhereIntegerInRaw()",
"filename": "tests/Database/DatabaseQueryBuilderTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.45.1\r\n- PHP Version: 8.1.13\r\n- Database Driver & Version:\r\n\r\n### Description:\r\n\r\nMethod explodeExplicitRule works wrong with this rule `regex:/^[\\d\\-]*$/|max:20`.\r\n\r\nIt can not explodes this rule to two patterns like \r\n```\r\n[\r\n 0 => 'regex:/^[\\d\\-]*$/',\r\n 1 => 'max:20'\r\n]\r\n```\r\n\r\nI have verified it in Laravel 8 and It has worked perfectly.\r\nI saw Laravel 9 had changed explodeExplicitRule which made it wrong.\r\nIn another rule like `required|regex:/^[\\d\\-]*$/|max:20` or just rotate it like `max:20|regex:/^[\\d\\-]*$/`,\r\nIt works perfectly.\r\n\r\nhttps://github.com/laravel/framework/blob/9.x/src/Illuminate/Validation/ValidationRuleParser.php#L86-L103\r\n\r\nhttps://github.com/laravel/framework/blob/8.x/src/Illuminate/Validation/ValidationRuleParser.php#L84-L93\r\n\r\n### Steps To Reproduce:\r\n\r\nuse Laravel validator with rule `regex:/^[\\d\\-]*$/|max:20`\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Ping @stevebauman. Seems to be because of the changes made here? https://github.com/laravel/framework/pull/40941\r\n\r\n@du-nong-028 can you confirm that reverting that PR fixes your issue?",
"created_at": "2023-01-05T12:38:11Z"
},
{
"body": "Thanks for the ping @driesvints! Looking into this now.",
"created_at": "2023-01-05T14:25:28Z"
},
{
"body": "@driesvints Thank you, I confirm that It's working when I revert that PR https://github.com/laravel/framework/pull/40941\r\n@stevebauman FYI\r\nCurrent\r\n````\r\narray:1 [▼\r\n \"tel\" => array:1 [▶\r\n 0 => \"regex:/^[\\d\\-]*$/|max:20\"\r\n ]\r\n]\r\n````\r\nWhen reverting that PR\r\n```\r\narray:1 [▼\r\n \"tel\" => array:2 [▶\r\n 0 => \"regex:/^[\\d\\-]*$/\"\r\n 1 => \"max:20\"\r\n ]\r\n]\r\n```\r\n",
"created_at": "2023-01-06T00:52:42Z"
},
{
"body": "Thanks @du-nong-028, I appreciate the detail in your report 🙏 . I've submitted a PR that reverts the changes and restores documented behaviour.",
"created_at": "2023-01-07T17:30:34Z"
}
],
"number": 45520,
"title": "Method explodeExplicitRule working wrong with regex rule"
} | {
"body": "Closes #45520 \r\n\r\nThis PR reverts a change that I made in PR #40941 ([specifically this change](https://github.com/laravel/framework/pull/40941/files#diff-88815c1c8302eb7f025ae9ba1f232036adbfae6a415d3d84d199ad2f3af15c31L88)), which attempted to handle regex rules containing pipes, if they were the only rule in the string. This didn't work as intended when a string rule contains a regex with subsequent rules (as displayed in PR #45520).\r\n\r\nThis revert returns the validator to its default and documented behaviour of requiring regex rules containing pipes be split into an array of rule strings.\r\n\r\nI have also adjusted the tests to ensure this default behaviour is kept, and that we will be notified of such a change due to test failure.\r\n\r\nLet me know if you would like anything adjusted, thanks for your time!",
"number": 45555,
"review_comments": [],
"title": "[9.x] Method explodeExplicitRule working wrong with regex rule - Issue 45520"
} | {
"commits": [
{
"message": "Revert #40941 changes"
},
{
"message": "Fix test"
},
{
"message": "Update test ensuring default behaviour"
},
{
"message": "Add issue test case"
}
],
"files": [
{
"diff": "@@ -86,9 +86,7 @@ protected function explodeRules($rules)\n protected function explodeExplicitRule($rule, $attribute)\n {\n if (is_string($rule)) {\n- [$name] = static::parseStringRule($rule);\n-\n- return static::ruleIsRegex($name) ? [$rule] : explode('|', $rule);\n+ return explode('|', $rule);\n }\n \n if (is_object($rule)) {",
"filename": "src/Illuminate/Validation/ValidationRuleParser.php",
"status": "modified"
},
{
"diff": "@@ -211,7 +211,7 @@ public function testForEachCallbacksDoNotBreakRegexRules()\n \n $rules = [\n 'items.*' => Rule::forEach(function () {\n- return ['users.*.type' => 'regex:/^(super|admin)$/i'];\n+ return ['users.*.type' => 'regex:/^(super)$/i'];\n }),\n ];\n ",
"filename": "tests/Validation/ValidationForEachTest.php",
"status": "modified"
},
{
"diff": "@@ -96,15 +96,28 @@ public function testEmptyConditionalRulesArePreserved()\n ], $rules);\n }\n \n- public function testExplodeProperlyParsesSingleRegexRule()\n+ public function testExplodeFailsParsingSingleRegexRuleContainingPipe()\n {\n $data = ['items' => [['type' => 'foo']]];\n \n $exploded = (new ValidationRuleParser($data))->explode(\n ['items.*.type' => 'regex:/^(foo|bar)$/i']\n );\n \n- $this->assertSame('regex:/^(foo|bar)$/i', $exploded->rules['items.0.type'][0]);\n+ $this->assertSame('regex:/^(foo', $exploded->rules['items.0.type'][0]);\n+ $this->assertSame('bar)$/i', $exploded->rules['items.0.type'][1]);\n+ }\n+\n+ public function testExplodeProperlyParsesSingleRegexRuleNotContainingPipe()\n+ {\n+ $data = ['items' => [['type' => 'foo']]];\n+\n+ $exploded = (new ValidationRuleParser($data))->explode(\n+ ['items.*.type' => 'regex:/^[\\d\\-]*$/|max:20']\n+ );\n+\n+ $this->assertSame('regex:/^[\\d\\-]*$/', $exploded->rules['items.0.type'][0]);\n+ $this->assertSame('max:20', $exploded->rules['items.0.type'][1]);\n }\n \n public function testExplodeProperlyParsesRegexWithArrayOfRules()",
"filename": "tests/Validation/ValidationRuleParserTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.32.0\r\n- PHP Version: 8.1.10\r\n- Database Driver & Version: mysqlnd\r\n\r\n### Description:\r\nWhen executing the `php artisan db` console command while having read and write hosts setup in `config/database.php` it returns this error: \r\n```\r\n╰─ff php artisan db\r\n\r\n ErrorException\r\n\r\n Undefined array key \"host\"\r\n\r\n at vendor/laravel/framework/src/Illuminate/Database/Console/DbCommand.php:141\r\n 137▕ */\r\n 138▕ protected function getMysqlArguments(array $connection)\r\n 139▕ {\r\n 140▕ return array_merge([\r\n ➜ 141▕ '--host='.$connection['host'],\r\n 142▕ '--port='.$connection['port'],\r\n 143▕ '--user='.$connection['username'],\r\n 144▕ ], $this->getOptionalArguments([\r\n 145▕ 'password' => '--password='.$connection['password'],\r\n\r\n +16 vendor frames\r\n 17 artisan:37\r\n Illuminate\\Foundation\\Console\\Kernel::handle()\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Setup mysql to use read and write hosts\r\n2. execute `php artisan db`\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "I understand that i can select --read or --write but it should throw a warning or a better error in my opinion if there's no default host and only using read/write as exampled here: https://laravel.com/docs/9.x/database#read-and-write-connections",
"created_at": "2022-09-29T19:14:58Z"
},
{
"body": "Or select read by default",
"created_at": "2022-09-29T19:15:12Z"
},
{
"body": "Thanks. We added a more descriptive message for this.",
"created_at": "2022-09-30T13:10:53Z"
}
],
"number": 44383,
"title": "Artisan db command fails when using read/write hosts"
} | {
"body": "This PR resolves #44383 by checking for a host key on the connection configuration before attempting to connect.\r\n\r\n<img width=\"652\" alt=\"Screenshot 2022-09-30 at 11 47 56\" src=\"https://user-images.githubusercontent.com/3438564/193254420-62300616-8d90-487b-ae82-8d8c35d85fbb.png\">\r\n\r\n",
"number": 44394,
"review_comments": [],
"title": "[9.x] Adds error output to `db` command when missing host"
} | {
"commits": [
{
"message": "Check for host"
},
{
"message": "Formatting"
}
],
"files": [
{
"diff": "@@ -34,6 +34,14 @@ public function handle()\n {\n $connection = $this->getConnection();\n \n+ if (! isset($connection['host'])) {\n+ $this->components->error('No host specified for this database connection.');\n+ $this->line(' Use the <options=bold>[--read]</> and <options=bold>[--write]</> options to specify a read or write connection.');\n+ $this->newLine();\n+\n+ return Command::FAILURE;\n+ }\n+\n (new Process(\n array_merge([$this->getCommand($connection)], $this->commandArguments($connection)),\n null,",
"filename": "src/Illuminate/Database/Console/DbCommand.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.30.1\r\n- PHP Version: 8.1.9\r\n- Database Driver & Version: PgSQL 14.5\r\n\r\n### Description:\r\n`db:show` throws the following exception:\r\n\r\n```php\r\n Doctrine\\DBAL\\Exception\r\n\r\n Unknown database type ltree requested, Doctrine\\DBAL\\Platforms\\PostgreSQL100Platform may not support it.\r\n\r\n at vendor/doctrine/dbal/src/Platforms/AbstractPlatform.php:418\r\n 414▕\r\n 415▕ $dbType = strtolower($dbType);\r\n 416▕\r\n 417▕ if (! isset($this->doctrineTypeMapping[$dbType])) {\r\n ➜ 418▕ throw new Exception(\r\n 419▕ 'Unknown database type ' . $dbType . ' requested, ' . static::class . ' may not support it.',\r\n 420▕ );\r\n 421▕ }\r\n 422▕\r\n\r\n +19 vendor frames\r\n 20 artisan:37\r\n Illuminate\\Foundation\\Console\\Kernel::handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n```\r\n\r\nLooks to be related to #43635.\r\n\r\n### Steps To Reproduce:\r\nExecute `artisan db:show`\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [],
"number": 44213,
"title": "`db:show` throws unknown database type exception for PostgreSQL"
} | {
"body": "This PR resolves #44213 \r\n\r\nDBAL does not have support for the ltree column type, so this PR maps it to a string as has been done with other unsupported types.",
"number": 44220,
"review_comments": [],
"title": "[9.x] Adds support for ltree when inspecting Postrges databases"
} | {
"commits": [
{
"message": "Add support for ltree"
}
],
"files": [
{
"diff": "@@ -28,6 +28,7 @@ abstract class DatabaseInspectionCommand extends Command\n 'geometry' => 'string',\n 'geomcollection' => 'string',\n 'linestring' => 'string',\n+ 'ltree' => 'string',\n 'multilinestring' => 'string',\n 'multipoint' => 'string',\n 'multipolygon' => 'string',",
"filename": "src/Illuminate/Database/Console/DatabaseInspectionCommand.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.27.0\r\n- PHP Version: 8.1.9\r\n- Database Driver & Version: X\r\n\r\nThis is a follow up issue to my old one, where i miss understood the problem.\r\n## Description:\r\nRoute prefix is returned with slash at the start when parent RouteGroup prefix is empty.\r\nFor exmaple:\r\n```php\r\nRoute::middleware(\"auth\")->group(function () { // parent RouteGroup prefix is empty\r\n Route::view(\"/\", \"page.test\");\r\n\r\n Route::prefix(\"dashboard\")->group(function () { // we add another group with its own prefix\r\n Route::view(\"/settings\", \"page.test\");\r\n });\r\n});\r\n```\r\n### Expected behavior:\r\nWhen user visits `*/dashboard/settings` the `Route->current()->getPrefix()` should return `dashboard`\r\n### Actual behavior:\r\nThe route prefix is returned with slash at the start -> `/dashboard`\r\n\r\nThis only happens when parent RouteGroup prefix is empty\r\nFor example this code would work as expected:\r\n```php\r\nRoute::prefix(\"admin\")->group(function () { // parent RouteGroup prefix is set to admin\r\n Route::view(\"/\", \"page.test\");\r\n\r\n Route::prefix(\"dashboard\")->group(function () { // we add another group with its own prefix\r\n Route::view(\"/\", \"page.test\");\r\n });\r\n});\r\n```\r\nWhen user visits `*/admin/dashboard` the `Route->current()->getPrefix()` returns `admin/dashboard` as expected.\r\n\r\n**The main problem is that route like this wouldn't work too.**\r\n```php\r\nRoute::group([\"prefix\" => \"dashboard\"], function () {\r\n Route::view('/', \"page.test\");\r\n});\r\n```\r\nWhen user visits `*/dashboard` the `Route->current()->getPrefix()` returns `/dashboard`\r\n\r\nThis is because all routes inside `web.php` are loaded using group with empty prefix in `RouteServiceProvider` boot method.\r\n```php\r\nRoute::middleware('web')\r\n ->group(base_path('routes/web.php')); // RouteGroup prefix is empty\r\n```\r\n\r\n## Source of the problem\r\nIf i understood the problem correctly i think the issue is in the `RouteGroup::formatPrefix` method.\r\nhttps://github.com/laravel/framework/blob/7fa4beb386a139cabb730a7e3b9571ba8ea2a181/src/Illuminate/Routing/RouteGroup.php#L64-L73\r\nHere the `$old` variable is set to empty string, when the parent RouteGroup prefix is empty / not set.\r\nAnd now when the old prefix is empty and new prefix is set. \r\nThis is what happens in the code on line 69 -> `\"\" . \"/\" . \"newPrefix\"`\r\nThere is **slash** added to the start of the new prefix.\r\n\r\nI also managed to write a failing test for this issue.\r\n```php\r\n$old = []; // leave array empty, this is what happens when loading routes in RouteServiceProvider\r\n$this->assertEquals(['prefix' => 'foo', 'namespace' => null, 'where' => []], RouteGroup::merge(['prefix' => 'foo'], $old)); // add prefix to route group\r\n```\r\n### Test output\r\n```\r\nFailed asserting that two arrays are equal.\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n Array (\r\n- 'prefix' => 'foo'\r\n+ 'prefix' => '/foo'\r\n 'namespace' => null\r\n 'where' => Array ()\r\n )\r\n```\r\n\r\n## My solution\r\nI managed to fix this issue by wrapping the return from `formatPrefix` in trim.\r\nReference:\r\nhttps://github.com/laravel/framework/blob/7fa4beb386a139cabb730a7e3b9571ba8ea2a181/src/Illuminate/Routing/RouteGroup.php#L64-L73\r\nMy fix:\r\n```php\r\nreturn trim(isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old, '/');\r\n```\r\nThis should guarantee the prefix is always returned without slash at the start as expected.\r\nI also tried running all the tests in the Routing folder after this fix and all of them have passed.\r\n\r\n\r\nIf my understanding of the problem is correct i would be open to submit a PR with fix and some additional test.\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Feel free to send in a PR but keep in mind that none of the existing behavior for non-cached routes can change.",
"created_at": "2022-09-05T07:48:36Z"
},
{
"body": "I just wanna leave this comment in case others have the same issue as I:\r\nthis change introduced a breaking change. before, the function $request->route()->getPrefix() returned the prefix with \"/\" at the beginning. Now this slash is removed.\r\nWhile the new behavior is cleaner and better, it broke my application and required some refactoring.",
"created_at": "2022-09-09T16:16:01Z"
},
{
"body": "@ruedigerm-playster did this break something for you in non-cached route behavior or with cached routes?",
"created_at": "2022-09-09T16:47:44Z"
},
{
"body": "I think non-cached behavior. (at least I'm not using any caching explicitly)\r\n\r\nI use prefix like \r\n`Route::prefix('my-api')->group(function () {`\r\n\r\nOld behavior: `$request->route()->getPrefix()` returned the prefix as \"/my-api\"\r\nNew behavior: `$request->route()->getPrefix()` returned the prefix as \"my-api\"",
"created_at": "2022-09-09T16:54:51Z"
},
{
"body": "@JirakLu we're going to roll back your PR. Seems it did break something while routes aren't cached. We cannot change the behavior for non-cached routes on patch releases.",
"created_at": "2022-09-09T17:11:38Z"
}
],
"number": 43997,
"title": "`RouteGroup::merge` adds slash to the route prefix, when parent RouteGroup prefix is empty / not set."
} | {
"body": "\r\nThis PR fixes issue described in #43997 \r\n## Problem this PR fixes\r\nIf route has parent RouteGroup with its prefix not set. FormatPrefix adds slash to either start or end of the actual prefix depending on the situtation.\r\nThis problem affects the whole `web.php` file, because the routes inside are loaded using group with empty $attributes array (so its prefix is empty).\r\n```php\r\nRoute::middleware('web')\r\n ->group(base_path('routes/web.php'));\r\n```\r\n\r\n## Examples of the problem\r\n**Appending prefix**\r\n```php\r\nRoute::middleware(\"auth\")->group(function () { // parent RouteGroup prefix is empty\r\n Route::view(\"/\", \"page.test\");\r\n\r\n Route::prefix(\"dashboard\")->group(function () { // we add another group with its own prefix\r\n Route::view(\"/settings\", \"page.test\");\r\n });\r\n});\r\n```\r\n### Expected behavior:\r\nWhen user visits */dashboard/settings the `Route->current()->getPrefix()` should return `dashboard`\r\n\r\n### Actual behavior:\r\nThe route prefix is returned with slash at the start -> `/dashboard`\r\n\r\n**Prepending prefix**\r\n```php\r\nRoute::middleware(\"web\")->group(function () { // parent RouteGroup prefix is empty\r\n Route::prefix(\"dashboard\")->get(\"/settings\", TestController::class); // add route with its own prefix\r\n});\r\n```\r\n### Expected behavior:\r\nWhen user visits */dashboard/settings the `Route->current()->getPrefix()` should return `dashboard`\r\n\r\n### Actual behavior:\r\nThe route prefix is returned with slash at the end -> `dashboard/`\r\n\r\n**Quick side note:** I don't even know if this syntax is allowed. I didn't found any mentions about prepending route prefixes in the routing documentation, yet there is a test for this exact behavior.\r\nhttps://github.com/laravel/framework/blob/7fa4beb386a139cabb730a7e3b9571ba8ea2a181/tests/Routing/RoutingRouteTest.php#L1159-L1170\r\nHere the `bar` prefix is before the group `foo` prefix. Event tho its defined inside the group.\r\n\r\n## Source of the problem\r\nIf i understood the problem correctly i think the issue is in the `RouteGroup::formatPrefix` method.\r\nhttps://github.com/laravel/framework/blob/7fa4beb386a139cabb730a7e3b9571ba8ea2a181/src/Illuminate/Routing/RouteGroup.php#L64-L73\r\nHere the `$old` variable is set to empty string, when the parent RouteGroup prefix is empty / not set.\r\nAnd now when the old prefix is empty and new prefix is set. \r\n**Appending prefix**\r\nThis is what happens in the code on line 69 -> `\"\" . \"/\" . \"newPrefix\"`\r\nThere is **slash** added to the start of the new prefix.\r\n**Prepending prefix**\r\nThis is what happens in the code on line 71 -> `\"newPrefix\" . \"/\" . \"\"`\r\nThere is **slash** added to the end of the new prefix.\r\n\r\n## My solution\r\nI managed to fix this issue by wrapping the return from `formatPrefix` in trim.\r\nReference:\r\nhttps://github.com/laravel/framework/blob/7fa4beb386a139cabb730a7e3b9571ba8ea2a181/src/Illuminate/Routing/RouteGroup.php#L64-L73\r\nMy fix:\r\n```php\r\nif ($prependExistingPrefix) {\r\n return trim(isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old, '/');\r\n} else {\r\n return trim(isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old, '/');\r\n}\r\n```\r\nThis should guarantee the prefix is always returned without slash at the start or end as expected.\r\nI also tried running all the tests in the Routing folder after this fix and all of them have passed.\r\n\r\nI hope my understanding of the problem is correct and the explanation was clear enough. :)\r\n\r\n",
"number": 44011,
"review_comments": [],
"title": "[9.x] Fixed `RoueGroup::merge` to format merged prefixes correctly"
} | {
"commits": [
{
"message": "Fixed route prefix formatting in RouteGroup::formatPrefix(). Added tests for this issue."
},
{
"message": "formatting fix"
}
],
"files": [
{
"diff": "@@ -66,9 +66,9 @@ protected static function formatPrefix($new, $old, $prependExistingPrefix = true\n $old = $old['prefix'] ?? '';\n \n if ($prependExistingPrefix) {\n- return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n+ return trim(isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old, '/');\n } else {\n- return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;\n+ return trim(isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old, '/');\n }\n }\n ",
"filename": "src/Illuminate/Routing/RouteGroup.php",
"status": "modified"
},
{
"diff": "@@ -1040,6 +1040,9 @@ public function testGroupMerging()\n $this->assertEquals(['prefix' => null, 'namespace' => null, 'where' => [\n 'var1' => 'foo', 'var2' => 'bar',\n ]], RouteGroup::merge(['where' => ['var1' => 'foo', 'var2' => 'bar']], $old));\n+\n+ $old = [];\n+ $this->assertEquals(['prefix' => 'foo', 'namespace' => null, 'where' => []], RouteGroup::merge(['prefix' => 'foo'], $old));\n }\n \n public function testRouteGrouping()\n@@ -1168,6 +1171,34 @@ public function testNestedRouteGroupingPrefixing()\n $routes = $router->getRoutes();\n $route = $routes->getByName('Foo::baz');\n $this->assertSame('bar/foo', $route->getAction('prefix'));\n+\n+ /*\n+ * nested with first layer skipped (prefix prepended)\n+ */\n+ $router = $this->getRouter();\n+ $router->group(['as' => 'Foo::'], function () use ($router) {\n+ $router->prefix('bar')->get('baz', ['as' => 'baz', function () {\n+ return 'hello';\n+ }]);\n+ });\n+ $routes = $router->getRoutes();\n+ $route = $routes->getByName('Foo::baz');\n+ $this->assertSame('bar', $route->getAction('prefix'));\n+\n+ /*\n+ * nested with first layer skipped (prefix appended)\n+ */\n+ $router = $this->getRouter();\n+ $router->group(['as' => 'Foo::'], function () use ($router) {\n+ $router->group(['prefix' => 'bar'], function () use ($router) {\n+ $router->get('baz', ['as' => 'baz', function () {\n+ return 'hello';\n+ }]);\n+ });\n+ });\n+ $routes = $router->getRoutes();\n+ $route = $routes->getByName('Foo::baz');\n+ $this->assertSame('bar', $route->getAction('prefix'));\n }\n \n public function testRouteMiddlewareMergeWithMiddlewareAttributesAsStrings()",
"filename": "tests/Routing/RoutingRouteTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.23.0\r\n- PHP Version: 8.1.9\r\n- Database Driver & Version: X\r\n\r\n### Description:\r\nAfter `route:cache`, `Route::current()->getPrefix()` returns the current route prefix without slash at the start.\r\nI think it would be better to unify this and always return prefix without slash at the start.\r\n\r\n## Not Cached\r\n`Route::current()->getPrefix()` returns \"/testPrefix\";\r\n\r\n## Cached\r\n`Route::current()->getPrefix()` returns \"testPrefix\";\r\n\r\nThis only happens for grouped routes:\r\n```php\r\n// Broken, getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::prefix(\"/test\")->group(function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// Broken, getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::group([\"prefix\" => \"/test\"], function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// Broken, getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::controller(TestController::class)->prefix(\"/test\")->group(function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// Working as expected, getPrefix() returns -> NOT CACHED: \"test\" | CACHED: \"test\"\r\nRoute::view(\"/\", \"pages.test\")->prefix(\"/test\")->name(\"test\");\r\n```\r\nI think the problem is in the `RouteGroup::formatPrefix()` method.\r\n\r\nhttps://github.com/laravel/framework/blob/2a1a55caf3c65a74f173f47be594587cb931f22c/src/Illuminate/Routing/RouteGroup.php#L64-L73\r\n\r\nHere if the old prefix isnt set it basically does this - `\"\" . \"/\" . \"newPrefix\"` -> adds slash at the start because the old prefix is an empty string.\r\n\r\nI managed to fixed the problem by adding ltrim to the return.\r\n```php\r\n$old = $old['prefix'] ?? '';\r\n\r\nif ($prependExistingPrefix) {\r\n return ltrim(isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old, '/');\r\n} else {\r\n return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;\r\n}\r\n```\r\nIf my understanding of the problem is correct, I would be happy to submit a PR to fix this.\r\n\r\n#43376 # Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "We should indeed fix this but the cached behavior should adopt to the non-cached behavior, not the other way around. ",
"created_at": "2022-08-29T08:26:37Z"
},
{
"body": "The problem is that the behavior differs even for not cached routes as i described here.\r\nIt depends if you use route group or not.\r\n\r\n```php\r\n// Broken, getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::group([\"prefix\" => \"/test\"], function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// Broken, getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::controller(TestController::class)->prefix(\"/test\")->group(function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// Working as expected, getPrefix() returns -> NOT CACHED: \"test\" | CACHED: \"test\"\r\nRoute::view(\"/\", \"pages.test\")->prefix(\"/test\")->name(\"test\");\r\n```",
"created_at": "2022-08-29T09:08:13Z"
},
{
"body": "> `Route::view(\"/\", \"pages.test\")->prefix(\"/test\")->name(\"test\");`\r\n\r\nThis isn't valid code. I don't think we document using prefixes like that on single routes anywhere.",
"created_at": "2022-08-29T09:15:11Z"
},
{
"body": "Oh, my bad.\r\nThen i guess the problem would be somewhere here.\r\nhttps://github.com/laravel/framework/blob/45cd804928f4c1a42fafd2b78c7fa023a59c542a/src/Illuminate/Routing/Route.php#L804-L809\r\nYou are basically trimming the slash at the start from the `$newPrefix`.\r\nI managed to fix it by replacing `trim` by `rtrim`.\r\n```php\r\nprotected function updatePrefixOnAction($prefix)\r\n{\r\n if (! empty($newPrefix = rtrim(rtrim($prefix, '/').'/'.ltrim($this->action['prefix'] ?? '', '/'), '/'))) {\r\n $this->action['prefix'] = $newPrefix;\r\n }\r\n}\r\n```\r\nThis works for me and the prefix is always returned with slash at the start. Cached or not cached.\r\n ",
"created_at": "2022-08-29T15:36:02Z"
},
{
"body": "Can you try to send in a PR?",
"created_at": "2022-08-30T07:50:03Z"
},
{
"body": "Done. Here is the PR: https://github.com/laravel/framework/pull/43932.",
"created_at": "2022-08-30T12:36:42Z"
},
{
"body": "Ima close this issue for now. I will create a new one with proper explanation of the problem soon.",
"created_at": "2022-09-02T13:26:57Z"
}
],
"number": 43882,
"title": "After `route:cache`, `Route::current()->getPrefix()` returns route prefix without slash at the start."
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n### This PR solves issue #43882 \r\nThe main problem was that the behavior of `Route::current->getPrefix()` was different for cached / not cached routes.\r\nNot Cached\r\n`Route::current()->getPrefix()` returns `\"/testPrefix\"`;\r\n\r\nCached\r\n`Route::current()->getPrefix()` returns `\"testPrefix\"`;\r\n```php\r\n// getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::prefix(\"/test\")->group(function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::group([\"prefix\" => \"/test\"], function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n\r\n// getPrefix() returns -> NOT CACHED: \"/test\" | CACHED: \"test\"\r\nRoute::controller(TestController::class)->prefix(\"/test\")->group(function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\");\r\n});\r\n```\r\n\r\n### Solution\r\nI unified how the route prefix names are returned. Either cached or not cached.\r\nRoute prefix is now always returned with slash at the start -> `/test`, `/test/test`.\r\n\r\nIt was tested for all these routes.\r\n```php\r\nRoute::group([\"prefix\" => \"test\"], function() {\r\n Route::view(\"/\", \"page.test\"); // getPrefix() returns -> /test\r\n});\r\n\r\nRoute::group([\"prefix\" => \"/testSlash\"], function() {\r\n Route::view(\"/\", \"page.test\"); // getPrefix() returns -> /testSlash\r\n});\r\n\r\nRoute::prefix(\"noSlash\")->group(function() {\r\n Route::view(\"/\", \"page.test\"); // getPrefix() returns -> /noSlash\r\n});\r\n\r\nRoute::prefix(\"/slash\")->group(function() {\r\n Route::view(\"/\", \"page.test\"); // getPrefix() returns -> /slash\r\n});\r\n\r\nRoute::group([\"prefix\" => \"test\"], function() {\r\n Route::group([\"prefix\" => \"test\"], function() {\r\n Route::view(\"/\", \"page.test\"); // getPrefix() returns -> /test/test\r\n });\r\n});\r\n\r\nRoute::group([\"prefix\" => \"testSlash\"], function() {\r\n Route::group([\"prefix\" => \"testSlash\"], function() {\r\n Route::view(\"/\", \"page.test\"); // getPrefix() returns -> /testSlash/testSlash\r\n });\r\n});\r\n\r\nRoute::controller(TestController::class)->prefix(\"/testController\")->group(function () {\r\n Route::view(\"/\", \"pages.test\")->name(\"test\"); // getPrefix() returns -> /testController\r\n});\r\n```\r\n",
"number": 43932,
"review_comments": [],
"title": "[9.x] Always return slash at the start of route prefix name."
} | {
"commits": [
{
"message": "Always return slash at the start of route prefix name."
}
],
"files": [
{
"diff": "@@ -803,7 +803,7 @@ public function prefix($prefix)\n */\n protected function updatePrefixOnAction($prefix)\n {\n- if (! empty($newPrefix = trim(rtrim($prefix, '/').'/'.ltrim($this->action['prefix'] ?? '', '/'), '/'))) {\n+ if (! empty($newPrefix = rtrim(rtrim($prefix, '/').'/'.ltrim($this->action['prefix'] ?? '', '/'), '/'))) {\n $this->action['prefix'] = $newPrefix;\n }\n }",
"filename": "src/Illuminate/Routing/Route.php",
"status": "modified"
},
{
"diff": "@@ -66,9 +66,9 @@ protected static function formatPrefix($new, $old, $prependExistingPrefix = true\n $old = $old['prefix'] ?? '';\n \n if ($prependExistingPrefix) {\n- return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n+ return isset($new['prefix']) ? rtrim($old, '/').'/'.trim($new['prefix'], '/') : $old;\n } else {\n- return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old;\n+ return isset($new['prefix']) ? rtrim($new['prefix'], '/').'/'.trim($old, '/') : $old;\n }\n }\n ",
"filename": "src/Illuminate/Routing/RouteGroup.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.0.1\r\n- PHP Version: 8.1.2\r\n- Database Driver & Version: irrelevant\r\n\r\n### Description:\r\nUsing an or sign (`|`) within a regex validation rule for an array item breaks on Laravel 9.x. This works fine on Laravel 8.x.\r\n\r\nIt seems somewhere the rules are parsed and the `|` is interpreted as start of another validation rule instead of as being part of the regex rule, causing the parsed regex rule to be `regex:/^(typeA|`. \r\n\r\nMost probably related to https://github.com/laravel/framework/pull/40498.\r\n\r\n### Steps To Reproduce:\r\n\r\nSee https://github.com/jnoordsij/laravel/tree/regex-validation-bug-8.x for the (working) 8.x version and https://github.com/jnoordsij/laravel/tree/regex-validation-bug-9.x for the test breaking on 9.x.\r\n\r\n1. clone repo\r\n2. `composer install`\r\n3. `cp .env.example .env.testing`\r\n4. `php artisan key:generate --env=testing`\r\n5. `php artisan test tests/Feature/SimpleRequestTest.php`\r\n\r\nResulting exception:\r\n`ErrorException: preg_match(): No ending delimiter '/' found in ...`\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "You should wrap your `regex` rule in an array. For example, this will fail:\r\n\r\n```php\r\n$v = new Validator($trans, ['x' => 'foo'], ['x' => 'Regex:/^(taylor|james)$/i']);\r\n$this->assertTrue($v->passes());\r\n```\r\n\r\nBut this will pass:\r\n\r\n```diff\r\n-$v = new Validator($trans, ['x' => 'foo'], ['x' => 'Regex:/^(taylor|james)$/i']);\r\n+$v = new Validator($trans, ['x' => 'foo'], ['x' => ['Regex:/^(taylor|james)$/i']]);\r\n$this->assertTrue($v->passes());\r\n```",
"created_at": "2022-02-10T11:42:55Z"
},
{
"body": "Note that this is what the documentation instructs you to do, when your regex contains a `|`. https://laravel.com/docs/9.x/validation#rule-regex",
"created_at": "2022-02-10T11:44:41Z"
},
{
"body": "Sorry, I see this is more nuanced as it's affecting nested rules only. I'll re-open whilst I investigate.",
"created_at": "2022-02-10T11:46:48Z"
},
{
"body": "The regex rule is actually in array form; I could understand that using something like `'contact.phonenumbers.*.type' => 'regex:/^(typeA|typeB|typeC)$/|required|string'` would be too ambiguous to parse, but the example I provided seems to comply with what the documentation instructs.",
"created_at": "2022-02-10T11:59:57Z"
},
{
"body": "Right, this passes in 8.x but fails in 9.x.\r\n\r\n```php\r\n$v = new Validator($trans,\r\n ['x' => ['y' => ['z' => 'james']]],\r\n ['x.*.z' => [\r\n 'required',\r\n 'string',\r\n 'Regex:/^(taylor|james)$/i'\r\n ]]\r\n);\r\n$this->assertTrue($v->passes());\r\n```\r\n\r\n```\r\n1) Illuminate\\Tests\\Validation\\ValidationValidatorTest::testValidateRegex\r\npreg_match(): No ending delimiter '/' found\r\n```",
"created_at": "2022-02-10T12:00:04Z"
},
{
"body": "@stevebauman any idea how to solve this? Otherwise, we need to revert Rule::forEach",
"created_at": "2022-02-10T15:07:12Z"
},
{
"body": "Give me a moment -- investigating now 👍 ",
"created_at": "2022-02-10T15:08:36Z"
},
{
"body": "@stevebauman from my investigation so far the error is around here:\r\n\r\nhttps://github.com/laravel/framework/blob/4c7cd8c4e95d161c0c6ada6efa0a5af4d0d487c9/src/Illuminate/Validation/ValidationRuleParser.php#L145-L161\r\n\r\nIf I replace the lines above by their 8.x counterpart...\r\n\r\nhttps://github.com/laravel/framework/blob/29bc8779103909ebc428478b339ee6fa8703e193/src/Illuminate/Validation/ValidationRuleParser.php#L133-L137\r\n\r\n...it works (tested `->passes()`, `->fails()` and `->validated()`)\r\n\r\nI am still digging into it, but I thought it would be nice to share",
"created_at": "2022-02-10T15:17:28Z"
},
{
"body": "@stevebauman in 8.x when `$rule` was a regex and reached here:\r\n\r\nhttps://github.com/laravel/framework/blob/4c7cd8c4e95d161c0c6ada6efa0a5af4d0d487c9/src/Illuminate/Validation/ValidationRuleParser.php#L85-L98\r\n\r\nIt was wrapped into an array, now it reaches here as a string, thus it gets on the first `if` clause that explodes it.\r\n\r\nOne other thing: if the regex validation rule is a top-level rule it works. It only fails when it is nested.",
"created_at": "2022-02-10T15:37:12Z"
},
{
"body": "@stevebauman if we change this line:\r\n\r\nhttps://github.com/laravel/framework/blob/4c7cd8c4e95d161c0c6ada6efa0a5af4d0d487c9/src/Illuminate/Validation/ValidationRuleParser.php#L145\r\n\r\nback to as it was in 8.x\r\n\r\n~~~php\r\nforeach ((array) $rules as $rule) {\r\n~~~\r\n\r\nIt works. From the blame this line was changed by you on PR #40498\r\n\r\nI will run the tests with this change and report back.\r\n\r\nEDIT: it works with the test case provided by OP",
"created_at": "2022-02-10T15:44:09Z"
},
{
"body": "@stevebauman Changing it back as of my last comment makes these two tests fail:\r\n\r\n~~~\r\nThere were 2 failures:\r\n\r\n1) Illuminate\\Tests\\Validation\\ValidationRuleParserTest::testExplodeHandlesArraysOfNestedRules\r\nFailed asserting that two arrays are equal.\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n Array (\r\n 'users.0.name' => Array (\r\n- 0 => 'required'\r\n- 1 => 'in:\"taylor\"'\r\n+ 0 => Array (...)\r\n+ 1 => Array (...)\r\n )\r\n 'users.1.name' => Array (\r\n- 0 => 'required'\r\n- 1 => 'in:\"abigail\"'\r\n+ 0 => Array (...)\r\n+ 1 => Array (...)\r\n )\r\n )\r\n\r\n/home/rodrigo/code/open-source/framework/tests/Validation/ValidationRuleParserTest.php:171\r\n\r\n2) Illuminate\\Tests\\Validation\\ValidationRuleParserTest::testExplodeHandlesRecursivelyNestedRules\r\nFailed asserting that null matches expected 'Taylor Otwell'.\r\n\r\n/home/rodrigo/code/open-source/framework/tests/Validation/ValidationRuleParserTest.php:192\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/NestedRules.php:37\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:122\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:96\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:71\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:201\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:187\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:159\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:67\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:49\r\n/home/rodrigo/code/open-source/framework/tests/Validation/ValidationRuleParserTest.php:209\r\n~~~\r\n\r\nI have an appointment in 10 minutes, so I will only be able to look into it further later. Hope it helps you out :)",
"created_at": "2022-02-10T15:52:10Z"
}
],
"number": 40924,
"title": "[9.x] Regex validation rules for array items containing 'or' seperators cause ErrorException on input validation"
} | {
"body": "Closes #43779\r\nCloses #43751\r\nRelated #43192\r\nRelated #40924\r\n\r\n> **Important**: Please look at the first PR above for full context.\r\n\r\nThis PR resolves a regression bug that I introduced in `9.x` in the `Rule::forEach()` validation feature, where nested array validation rules can no longer be used, due to flattening them via an `Arr::flatten($rules)`.\r\n\r\nFor example, this can no longer be done, whereas it used to work in prior versions of Laravel:\r\n\r\n```php\r\n$data = [\r\n 'items' => [\r\n ['|name' => 'foo'],\r\n ]\r\n];\r\n\r\n$rules = [\r\n 'items.*' => ['array', ['required_array_keys', '|name']] // <-- Nested array rule with an argument.\r\n];\r\n\r\n// BadMethodCallException: Method Illuminate\\Validation\\Validator::validateName does not exist\r\nValidator::make($data, $rules)->passes();\r\n```\r\n\r\n`Arr::flatten()` was used to be able to determine if a ruleset contains a `NestedRules` instance, and allowed validation rules to be infinitely nested, as they would be flattened before being parsed:\r\n\r\nhttps://github.com/laravel/framework/blob/2a1a55caf3c65a74f173f47be594587cb931f22c/src/Illuminate/Validation/ValidationRuleParser.php#L154-L155\r\n\r\nThis PR will break the below (however unlikely) implementation for developers -- but will resolve the regression bug, while keeping the `Rule::forEach` feature:\r\n\r\n```php\r\n$rules = [\r\n 'users.*.name' => [\r\n Rule::forEach(function ($value, $attribute, $data) {\r\n // ...\r\n }),\r\n Rule::forEach(function ($value, $attribute, $data) {\r\n // ...\r\n }),\r\n ],\r\n];\r\n```\r\n\r\nDevelopers will have instead have to use a single `Rule::forEach()` (non-nested), as this will no longer be supported:\r\n\r\n```php\r\n$rules = [\r\n 'users.*.name' => Rule::forEach(function ($value, $attribute, $data) {\r\n // ...\r\n }),\r\n];\r\n```\r\n\r\nI've added test to ensure we have some coverage over the nested array rule feature so regression will not occur again in the future.\r\n\r\nThanks so much for your time, and I apologize for this issue that has caused grief for devs upgrading to 9.x ❤️ ",
"number": 43897,
"review_comments": [],
"title": "[9.x] Patch nested array validation rule regression bug"
} | {
"commits": [
{
"message": "Remove Arr::flatten"
},
{
"message": "Update tests and remove no-longer relevant tests"
},
{
"message": "Add test for nested validation rules"
},
{
"message": "Rename and move test"
},
{
"message": "Add failing validation run"
},
{
"message": "CS fix"
}
],
"files": [
{
"diff": "@@ -151,7 +151,7 @@ protected function explodeWildcardRules($results, $attribute, $rules)\n \n foreach ($data as $key => $value) {\n if (Str::startsWith($key, $attribute) || (bool) preg_match('/^'.$pattern.'\\z/', $key)) {\n- foreach (Arr::flatten((array) $rules) as $rule) {\n+ foreach ((array) $rules as $rule) {\n if ($rule instanceof NestedRules) {\n $compiled = $rule->compile($key, $value, $data);\n ",
"filename": "src/Illuminate/Validation/ValidationRuleParser.php",
"status": "modified"
},
{
"diff": "@@ -144,18 +144,6 @@ public function testExplodeFailsParsingRegexWithOtherRulesInSingleString()\n $this->assertSame('bar)$/i', $exploded->rules['items.0.type'][2]);\n }\n \n- public function testExplodeProperlyFlattensRuleArraysOfArrays()\n- {\n- $data = ['items' => [['type' => 'foo']]];\n-\n- $exploded = (new ValidationRuleParser($data))->explode(\n- ['items.*.type' => ['in:foo', [[['regex:/^(foo|bar)$/i']]]]]\n- );\n-\n- $this->assertSame('in:foo', $exploded->rules['items.0.type'][0]);\n- $this->assertSame('regex:/^(foo|bar)$/i', $exploded->rules['items.0.type'][1]);\n- }\n-\n public function testExplodeGeneratesNestedRules()\n {\n $parser = (new ValidationRuleParser([\n@@ -208,28 +196,19 @@ public function testExplodeHandlesArraysOfNestedRules()\n ]));\n \n $results = $parser->explode([\n- 'users.*.name' => [\n- Rule::forEach(function ($value, $attribute, $data) {\n- $this->assertEquals([\n- 'users.0.name' => 'Taylor Otwell',\n- 'users.1.name' => 'Abigail Otwell',\n- ], $data);\n-\n- return [Rule::requiredIf(true)];\n- }),\n- Rule::forEach(function ($value, $attribute, $data) {\n+ 'users.*.name' => Rule::forEach(function ($value, $attribute, $data) {\n $this->assertEquals([\n 'users.0.name' => 'Taylor Otwell',\n 'users.1.name' => 'Abigail Otwell',\n ], $data);\n \n return [\n+ Rule::requiredIf(true),\n $value === 'Taylor Otwell'\n ? Rule::in('taylor')\n : Rule::in('abigail'),\n ];\n }),\n- ],\n ]);\n \n $this->assertEquals([\n@@ -240,8 +219,6 @@ public function testExplodeHandlesArraysOfNestedRules()\n $this->assertEquals([\n 'users.*.name' => [\n 'users.0.name',\n- 'users.0.name',\n- 'users.1.name',\n 'users.1.name',\n ],\n ], $results->implicitAttributes);\n@@ -254,9 +231,13 @@ public function testExplodeHandlesRecursivelyNestedRules()\n ]));\n \n $results = $parser->explode([\n- 'users.*.name' => [\n- Rule::forEach(function ($value, $attribute, $data) {\n- $this->assertSame('Taylor Otwell', $value);\n+ 'users.*.name' => Rule::forEach(function ($value, $attribute, $data) {\n+ $this->assertSame('Taylor Otwell', $value);\n+ $this->assertSame('users.0.name', $attribute);\n+ $this->assertEquals(['users.0.name' => 'Taylor Otwell'], $data);\n+\n+ return Rule::forEach(function ($value, $attribute, $data) {\n+ $this->assertNull($value);\n $this->assertSame('users.0.name', $attribute);\n $this->assertEquals(['users.0.name' => 'Taylor Otwell'], $data);\n \n@@ -265,16 +246,10 @@ public function testExplodeHandlesRecursivelyNestedRules()\n $this->assertSame('users.0.name', $attribute);\n $this->assertEquals(['users.0.name' => 'Taylor Otwell'], $data);\n \n- return Rule::forEach(function ($value, $attribute, $data) {\n- $this->assertNull($value);\n- $this->assertSame('users.0.name', $attribute);\n- $this->assertEquals(['users.0.name' => 'Taylor Otwell'], $data);\n-\n- return [Rule::requiredIf(true)];\n- });\n+ return [Rule::requiredIf(true)];\n });\n- }),\n- ],\n+ });\n+ }),\n ]);\n \n $this->assertEquals(['users.0.name' => ['required']], $results->rules);",
"filename": "tests/Validation/ValidationRuleParserTest.php",
"status": "modified"
},
{
"diff": "@@ -173,6 +173,37 @@ public function testInValidatableRulesReturnsValid()\n $this->assertTrue($v->passes());\n }\n \n+ public function testValidateUsingNestedValidationRulesPasses()\n+ {\n+ $rules = [\n+ 'items' => ['array'],\n+ 'items.*' => ['array', ['required_array_keys', '|name']],\n+ 'items.*.|name' => [['in', '|ABC123']],\n+ ];\n+\n+ $data = [\n+ 'items' => [\n+ ['|name' => '|ABC123'],\n+ ],\n+ ];\n+\n+ $trans = $this->getIlluminateArrayTranslator();\n+ $v = new Validator($trans, $data, $rules);\n+\n+ $this->assertTrue($v->passes());\n+\n+ $data = [\n+ 'items' => [\n+ ['|name' => '|1234'],\n+ ],\n+ ];\n+\n+ $trans = $this->getIlluminateArrayTranslator();\n+ $v = new Validator($trans, $data, $rules);\n+\n+ $this->assertSame('validation.in', $v->messages()->get('items.0.|name')[0]);\n+ }\n+\n public function testValidateEmptyStringsAlwaysPasses()\n {\n $trans = $this->getIlluminateArrayTranslator();",
"filename": "tests/Validation/ValidationValidatorTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 9.25.1\r\n- PHP Version: 8.1.6\r\n- Database Driver & Version: MySQL 8.0.27\r\n\r\n### Description:\r\n\r\nWhen queueing a job that has a **custom** Eloquent Collection as a typed property, and it holds an empty collection, (un)serializing fails with a Type Error, since it tries to assign the base Eloquent Collection to the property:\r\n\r\n```php\r\nclass SomeJob implements ShouldQueue\r\n{\r\n use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;\r\n\r\n public OrderCollection $orders;\r\n\r\n public function __construct(OrderCollection $orders)\r\n {\r\n $this->orders = $orders;\r\n }\r\n\r\n public function handle()\r\n {\r\n //\r\n }\r\n}\r\n\r\n$job = new SomeJob(new OrderCollection());\r\n\r\n$serialized = serialize($job)\r\n\r\nunserialize($serialized)\r\n\r\n```\r\n\r\nResult:\r\n\r\n`TypeError : Cannot assign Illuminate\\Database\\Eloquent\\Collection to property SomeJob::$orders of type App\\Eloquent\\OrderCollection`\r\n\r\n### Steps To Reproduce:\r\n\r\nI've added a failing test to prove the bug is there:\r\nhttps://github.com/hxnk/framework/commit/ac6ed8ba058ae007c73e352c332fd4fb1070c1df",
"comments": [
{
"body": "Thanks, I confirmed this and sent in a fix.",
"created_at": "2022-08-18T12:40:51Z"
}
],
"number": 43732,
"title": "Serialization fails for typed custom Eloquent Collections that are empty"
} | {
"body": "This fixes an issue where restoring a custom Eloquent collection wouldn't be of the same type. We should save the class type in the ModelIdentifier class to achieve this.\n\nFixes #43732\n",
"number": 43758,
"review_comments": [
{
"body": "The `?? null` part here is a BC measure to make sure we don't break already serialized model identifiers instances that don't have this property.",
"created_at": "2022-08-18T12:53:55Z"
}
],
"title": "[9.x] Fix empty collection class serialization"
} | {
"commits": [
{
"message": "Fix empty collection class serialization"
},
{
"message": "Apply fixes from StyleCI"
},
{
"message": "wip"
},
{
"message": "move to method"
}
],
"files": [
{
"diff": "@@ -34,6 +34,13 @@ class ModelIdentifier\n */\n public $connection;\n \n+ /**\n+ * The class name of the model collection.\n+ *\n+ * @var string|null\n+ */\n+ public $collectionClass;\n+\n /**\n * Create a new model identifier.\n *\n@@ -50,4 +57,17 @@ public function __construct($class, $id, array $relations, $connection)\n $this->relations = $relations;\n $this->connection = $connection;\n }\n+\n+ /**\n+ * Specify the collection class that should be used when serializing / restoring collections.\n+ *\n+ * @param string|null $collectionClass\n+ * @return $this\n+ */\n+ public function useCollectionClass(?string $collectionClass)\n+ {\n+ $this->collectionClass = $collectionClass;\n+\n+ return $this;\n+ }\n }",
"filename": "src/Illuminate/Contracts/Database/ModelIdentifier.php",
"status": "modified"
},
{
"diff": "@@ -20,11 +20,15 @@ trait SerializesAndRestoresModelIdentifiers\n protected function getSerializedPropertyValue($value)\n {\n if ($value instanceof QueueableCollection) {\n- return new ModelIdentifier(\n+ return (new ModelIdentifier(\n $value->getQueueableClass(),\n $value->getQueueableIds(),\n $value->getQueueableRelations(),\n $value->getQueueableConnection()\n+ ))->useCollectionClass(\n+ ($collectionClass = get_class($value)) !== EloquentCollection::class\n+ ? $collectionClass\n+ : null\n );\n }\n \n@@ -66,7 +70,9 @@ protected function getRestoredPropertyValue($value)\n protected function restoreCollection($value)\n {\n if (! $value->class || count($value->id) === 0) {\n- return new EloquentCollection;\n+ return ! is_null($value->collectionClass ?? null)\n+ ? new $value->collectionClass\n+ : new EloquentCollection;\n }\n \n $collection = $this->getQueryForModelRestoration(",
"filename": "src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php",
"status": "modified"
},
{
"diff": "@@ -314,9 +314,21 @@ public function test_model_serialization_structure()\n $serialized = serialize(new ModelSerializationParentAccessibleTestClass($user, $user, $user));\n \n $this->assertSame(\n- 'O:78:\"Illuminate\\\\Tests\\\\Integration\\\\Queue\\\\ModelSerializationParentAccessibleTestClass\":2:{s:4:\"user\";O:45:\"Illuminate\\\\Contracts\\\\Database\\\\ModelIdentifier\":4:{s:5:\"class\";s:61:\"Illuminate\\\\Tests\\\\Integration\\\\Queue\\\\ModelSerializationTestUser\";s:2:\"id\";i:1;s:9:\"relations\";a:0:{}s:10:\"connection\";s:7:\"testing\";}s:8:\"'.\"\\0\".'*'.\"\\0\".'user2\";O:45:\"Illuminate\\\\Contracts\\\\Database\\\\ModelIdentifier\":4:{s:5:\"class\";s:61:\"Illuminate\\\\Tests\\\\Integration\\\\Queue\\\\ModelSerializationTestUser\";s:2:\"id\";i:1;s:9:\"relations\";a:0:{}s:10:\"connection\";s:7:\"testing\";}}', $serialized\n+ 'O:78:\"Illuminate\\\\Tests\\\\Integration\\\\Queue\\\\ModelSerializationParentAccessibleTestClass\":2:{s:4:\"user\";O:45:\"Illuminate\\\\Contracts\\\\Database\\\\ModelIdentifier\":5:{s:5:\"class\";s:61:\"Illuminate\\\\Tests\\\\Integration\\\\Queue\\\\ModelSerializationTestUser\";s:2:\"id\";i:1;s:9:\"relations\";a:0:{}s:10:\"connection\";s:7:\"testing\";s:15:\"collectionClass\";N;}s:8:\"'.\"\\0\".'*'.\"\\0\".'user2\";O:45:\"Illuminate\\\\Contracts\\\\Database\\\\ModelIdentifier\":5:{s:5:\"class\";s:61:\"Illuminate\\\\Tests\\\\Integration\\\\Queue\\\\ModelSerializationTestUser\";s:2:\"id\";i:1;s:9:\"relations\";a:0:{}s:10:\"connection\";s:7:\"testing\";s:15:\"collectionClass\";N;}}', $serialized\n );\n }\n+\n+ public function test_serialization_types_empty_custom_eloquent_collection()\n+ {\n+ $class = new ModelSerializationTypedCustomCollectionTestClass(\n+ new ModelSerializationTestCustomUserCollection());\n+\n+ $serialized = serialize($class);\n+\n+ unserialize($serialized);\n+\n+ $this->assertTrue(true);\n+ }\n }\n \n trait TraitBootsAndInitializersTest\n@@ -352,6 +364,18 @@ class ModelSerializationTestCustomUserCollection extends Collection\n //\n }\n \n+class ModelSerializationTypedCustomCollectionTestClass\n+{\n+ use SerializesModels;\n+\n+ public ModelSerializationTestCustomUserCollection $collection;\n+\n+ public function __construct(ModelSerializationTestCustomUserCollection $collection)\n+ {\n+ $this->collection = $collection;\n+ }\n+}\n+\n class ModelSerializationTestCustomUser extends Model\n {\n public $table = 'users';",
"filename": "tests/Integration/Queue/ModelSerializationTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.24.0\r\n- PHP Version: 8.1.0\r\n- Database Driver & Version:\r\nMySql 8\r\nDescription:\r\nWhen we use a cast of type 'object', 'collection' and we have the original value null, we get an error when trying to decode json.\r\nThis change appeared in the [PR](https://github.com/laravel/framework/pull/42793/files#diff-59d24f1a8f0dd1e51ee7dffc8778133711634e928ecef4a91b63fc3851cb1579) and is still relevant even for version 9.\r\nPR\r\nWe get the warning\r\n\r\n> PHP Deprecated: json_decode(): Passing null to parameter https://github.com/laravel/framework/issues/1 ($json) of type string is deprecated\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "@tpetry since you originally created https://github.com/laravel/framework/issues/37961 which sparked https://github.com/laravel/framework/pull/41337: do you know of a way to do a fix so both issues are resolved?\r\n\r\nAlso want to ping you @JBtje since you're the author of https://github.com/laravel/framework/pull/41337.\r\n\r\n@jc-skurman this change has been in the framework now for several months. Did you only update Laravel now recently?",
"created_at": "2022-08-15T10:16:18Z"
},
{
"body": "I just now caught this bug on the old version and after indicating that you no longer support it, I checked it on the latest version",
"created_at": "2022-08-15T10:23:52Z"
},
{
"body": "@driesvints \r\n\r\nI've checked issues can be reproduced if you have `null` original value for `object` or/and `collection` cast. This can be fixed replacing `fromJson` call to `castAttribute`\r\n \r\n\r\n ```php\r\n } elseif ($this->hasCast($key, ['object', 'collection'])) {\r\n return $this->fromJson($attribute) ===\r\n $this->fromJson($original);\r\n ```\r\nchange to \r\n ```php\r\n } elseif ($this->hasCast($key, ['object', 'collection'])) {\r\n return $this->castAttribute($key, $attribute) ===\r\n $this->castAttribute($key, $original); \r\n ```\r\n\r\n ",
"created_at": "2022-08-15T10:30:19Z"
},
{
"body": "I replaced the dirty check with my custom implementation because in my projects I found a lot more edge cases, e.g. different order of object keys.\r\n\r\nBut based on the implementation of the PR the null value has to be handled too. `null != json, null = null`.\r\n\r\n",
"created_at": "2022-08-15T10:31:43Z"
},
{
"body": "First and foremost, `null` (object) is not valid `json`, so the warning is correct If you seed your empty JSON fields with a valid JSON value (e.g. empty string), the warning is solved.\r\nI have come across this warning a few times, just to realize i did something wrong (i.e. not seeding JSON field properly).\r\n\r\nBut if you think `null` should be a valid value for a JSON field, then this could easily be solved:\r\nhttps://github.com/laravel/framework/blob/9.x/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L1203\r\n```\r\n return json_decode($value ?? '', ! $asObject);\r\n```\r\nsolves the warning.",
"created_at": "2022-08-15T10:51:22Z"
},
{
"body": "@JBtje that's not true actually. `null` is definitely valid JSON: https://stackoverflow.com/questions/8526995/is-null-valid-json-4-bytes-nothing-else",
"created_at": "2022-08-15T10:54:17Z"
},
{
"body": "Would appreciate a PR to fix this.",
"created_at": "2022-08-15T10:54:32Z"
},
{
"body": "Edit: PHP was right...\r\n\r\n@driesvints `'null'` as a string is valid JSON. `null` as an object isn't valid JSON.\r\n\r\nAfter reading up some more on the topic; the json-text must be a **string**.\r\nThe json-**value** however can also be a null (object), true/false (bool), array, object\r\nhttps://datatracker.ietf.org/doc/rfc8259/\r\nvisualisation: https://www.json.org/json-en.html\r\n\r\n```\r\njson_decode( 'null' ) -> null\r\njson_decode( 'false' ) -> false\r\njson_decode( 'true' ) -> true\r\n\r\njson_decode( null ) -> invalid json, throws depricated warning\r\njson_decode( false ) -> invalid json, returns int(1) (don't ask why)\r\njson_decode( true ) -> invalid josn, returns null (don't ask why)\r\n```\r\n\r\nJavascript however accepts null (object), true/false (bool) as input. This is allowed under RFC8259 but not mandatory.\r\n\r\nCause of this problem:\r\nhttps://wiki.php.net/rfc/deprecate_null_to_scalar_internal_arg\r\nChanged in https://github.com/php/php-src/commit/b10416a652d26577a22fe0b183b2258b20c8bb86#diff-a39ce231303cec12a6d347165931a7f2209ee7dce5989f2e06f8c04143ec7032\r\n\r\nSolution to support `null` (object) in Laravel:\r\nPR: https://github.com/laravel/framework/pull/43706",
"created_at": "2022-08-15T12:05:05Z"
},
{
"body": "We merged a fix for this. Thanks",
"created_at": "2022-08-15T13:58:54Z"
}
],
"number": 43705,
"title": "Null compatibility broken"
} | {
"body": "Problem:\r\n- PHP 8.1 no longer supports null for json_decode, and throws a deprication warning\r\nhttps://wiki.php.net/rfc/deprecate_null_to_scalar_internal_arg\r\nChanged in https://github.com/php/php-src/commit/b10416a652d26577a22fe0b183b2258b20c8bb86#diff-a39ce231303cec12a6d347165931a7f2209ee7dce5989f2e06f8c04143ec7032\r\n\r\nHowever, thr RFC says that `null` is a valid JSON value:\r\nhttps://datatracker.ietf.org/doc/rfc8259/\r\n```\r\nA JSON value MUST be an object, array, number, or string, or one of\r\nthe following three literal names:\r\n\r\n false null true\r\n\r\n The literal names MUST be lowercase. No other literal names are\r\n allowed.\r\n```\r\nThus, auto cast should accept `null` as a valid JSON and not result in a deprecation warning..\r\n\r\nalso see issue #43705",
"number": 43706,
"review_comments": [],
"title": "[9.x] Null value for auto-cast field caused deprication warning in php 8.1"
} | {
"commits": [
{
"message": "Null value for auto-cast field caused deprication warning in php 8.1\n\nSee issue !43705"
}
],
"files": [
{
"diff": "@@ -1200,7 +1200,7 @@ protected function asJson($value)\n */\n public function fromJson($value, $asObject = false)\n {\n- return json_decode($value, ! $asObject);\n+ return json_decode($value ?? '', ! $asObject);\n }\n \n /**",
"filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "When trying to pass an integer value to whereMonth() or whereDay(), e.g. \r\n```php\r\nUser::whereMonth('updated_at', '=', 4)->get();\r\n```\r\nPHPstan will report `Parameter #3 $value of method Illuminate\\Database\\Eloquent\\Builder<App\\Models\\User>::whereMonth() expects DateTimeInterface|string|null, int given.` \r\n\r\nAt the same time,\r\n```php\r\nUser::whereYear('updated_at', '=', 2022)->get();\r\n```\r\nwill accept integer values.\r\n\r\nThis PR suggests to make the type definitions for `whereYear()`, `whereMonth()` and `whereDay()` more consistent by adding the int type to the @param docblock for `$value`.\r\n\r\nI am swapping out the usage of `str_pad()` with `sprintf()` because the latter will accept mixed arguments, whereas for `str_pad()`, we would have to convert int values to strings first (and it's more compact, too).",
"number": 43668,
"review_comments": [],
"title": "[9.x] Allow for int value parameters to whereMonth() and whereDay()"
} | {
"commits": [
{
"message": "allow for int value parameters for whereMonth() and whereDay()"
}
],
"files": [
{
"diff": "@@ -1386,7 +1386,7 @@ public function orWhereTime($column, $operator, $value = null)\n *\n * @param string $column\n * @param string $operator\n- * @param \\DateTimeInterface|string|null $value\n+ * @param \\DateTimeInterface|string|int|null $value\n * @param string $boolean\n * @return $this\n */\n@@ -1403,7 +1403,7 @@ public function whereDay($column, $operator, $value = null, $boolean = 'and')\n }\n \n if (! $value instanceof Expression) {\n- $value = str_pad($value, 2, '0', STR_PAD_LEFT);\n+ $value = sprintf('%02d', $value);\n }\n \n return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean);\n@@ -1414,7 +1414,7 @@ public function whereDay($column, $operator, $value = null, $boolean = 'and')\n *\n * @param string $column\n * @param string $operator\n- * @param \\DateTimeInterface|string|null $value\n+ * @param \\DateTimeInterface|string|int|null $value\n * @return $this\n */\n public function orWhereDay($column, $operator, $value = null)\n@@ -1431,7 +1431,7 @@ public function orWhereDay($column, $operator, $value = null)\n *\n * @param string $column\n * @param string $operator\n- * @param \\DateTimeInterface|string|null $value\n+ * @param \\DateTimeInterface|string|int|null $value\n * @param string $boolean\n * @return $this\n */\n@@ -1448,7 +1448,7 @@ public function whereMonth($column, $operator, $value = null, $boolean = 'and')\n }\n \n if (! $value instanceof Expression) {\n- $value = str_pad($value, 2, '0', STR_PAD_LEFT);\n+ $value = sprintf('%02d', $value);\n }\n \n return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean);\n@@ -1459,7 +1459,7 @@ public function whereMonth($column, $operator, $value = null, $boolean = 'and')\n *\n * @param string $column\n * @param string $operator\n- * @param \\DateTimeInterface|string|null $value\n+ * @param \\DateTimeInterface|string|int|null $value\n * @return $this\n */\n public function orWhereMonth($column, $operator, $value = null)",
"filename": "src/Illuminate/Database/Query/Builder.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.21.0\r\n- PHP Version: 8.1\r\n- Database Driver & Version: MySQL / N/A\r\n\r\n### Description:\r\nWe are using the intl PHP extension to localize dates in our views. Since the [pull request #42080](https://github.com/laravel/framework/pull/42080) was merged, the selected locale is always overriden by the framework when we use a custom `FormRequest` in the controller. The problem is not present if we use the default `Request` instead of a custom one.\r\n\r\nWe are setting the locale of the extension in the `app/Providers/AppServiceProvider.php`, in the `boot` method like this:\r\n\r\n```php\r\n public function boot(): void\r\n {\r\n \\Locale::setDefault(\\App::getLocale());\r\n }\r\n```\r\n\r\nWhen the custom request is created from the base request, the default language is set in the file `src/Illuminate/Http/Request.php`, line 426:\r\n```php\r\n $request->setDefaultLocale($from->getDefaultLocale());\r\n```\r\nand because the locale is null, the default Locale is also modified (line 1335):\r\n```php\r\n /**\r\n * Sets the default locale.\r\n */\r\n public function setDefaultLocale(string $locale)\r\n {\r\n $this->defaultLocale = $locale;\r\n\r\n if (null === $this->locale) {\r\n $this->setPhpDefaultLocale($locale);\r\n }\r\n }\r\n```\r\nline 1869 of the Symfony vendor file `symfony/http-foundation/Request.php`:\r\n```php\r\n private function setPhpDefaultLocale(string $locale): void\r\n {\r\n // if either the class Locale doesn't exist, or an exception is thrown when\r\n // setting the default locale, the intl module is not installed, and\r\n // the call can be ignored:\r\n try {\r\n if (class_exists(\\Locale::class, false)) {\r\n \\Locale::setDefault($locale);\r\n }\r\n } catch (\\Exception) {\r\n }\r\n }\r\n```\r\n\r\n### Steps To Reproduce:\r\nAs requested, here is a repo that replicate the issue: https://github.com/faeby/laravel-issue-43371\r\n\r\n1. create a new laravel project\r\n2. set the default language in french in app.php\r\n```php\r\n /*\r\n |--------------------------------------------------------------------------\r\n | Application Locale Configuration\r\n |--------------------------------------------------------------------------\r\n |\r\n | The application locale determines the default locale that will be used\r\n | by the translation service provider. You are free to set this value\r\n | to any of the locales which will be supported by the application.\r\n |\r\n */\r\n\r\n 'locale' => 'fr',\r\n```\r\n4. set the intl locale in the default locale of the app in the app service provider (shown above) \r\n```php\r\n public function boot(): void\r\n {\r\n \\Locale::setDefault(\\App::getLocale());\r\n }\r\n```\r\n5. create a custom request with the command `php artisan make:request ShouldBeInFrench` and authorize every to access it\r\n6. add the followings routes in `routes/web.php`\r\n```php\r\nRoute::get('/requests/custom', function (\\App\\Http\\Requests\\ShouldBeInFrench $request) {\r\n dump(\"INTL locale: \" . \\Locale::getDefault());\r\n return \"I'm the custom request. <a href='/requests/base'>Go to base request</a>\";\r\n});\r\n\r\nRoute::get('/requests/base', function (\\Illuminate\\Http\\Request $request) {\r\n dump(\"INTL locale: \" . \\Locale::getDefault());\r\n return \"I'm the original request. <a href='/requests/custom'>Go to custom request</a>\";\r\n});\r\n```\r\n7. serve the app and navigate to the given URLs, and the intl locale shown is different\r\n\r\n\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n\r\n### Workaround:\r\nAs a workaround, we are manually setting the request default locale in the `AppServiceprovider` boot method. This is not perfect but we did not found a way to configure the request locale in a better way.\r\n```php\r\n public function boot()\r\n {\r\n // Functional workaround.\r\n $this->app->afterResolving(FormRequest::class, function ($request, $app) {\r\n $app['request']->setDefaultLocale(App::getLocale());\r\n });\r\n\r\n \\Locale::setDefault(App::getLocale());\r\n }\r\n```",
"comments": [
{
"body": "Please recreate the repo with the following command and commit any custom changes into a single commit:\r\n\r\n```bash\r\nlaravel new bug-report --github=\"--public\"\r\n```\r\n\r\nThanks!",
"created_at": "2022-07-25T10:20:43Z"
},
{
"body": "Here is the new repository, created as requested: https://github.com/faeby/laravel-issue-43371\r\nThis is my first time submitting a bug report, so I hope this is correct this time.",
"created_at": "2022-07-25T12:36:35Z"
},
{
"body": "Thanks. I've sent in a PR for this: https://github.com/laravel/framework/pull/43426",
"created_at": "2022-07-26T09:39:29Z"
}
],
"number": 43371,
"title": "Using a custom FormRequest always modify the language of \\Locale class from intl PHP extension"
} | {
"body": "This PR fixes a bug where the global Locale value would be overwritten by calling setLocale. Underneath this method, Symfony sets the global Locale. Since we're not initializing the original request of the application but \r\nrather copying an existing request, we need to prevent from overwriting the default PHP locale. We can achieve this by just setting the plain locale and plain default locale without modifying the PHP locale. I've added new methods to achieve this so there's no side effects.\r\n\r\nFixes #43371\r\n",
"number": 43426,
"review_comments": [],
"title": "[9.x] Fix overriding global locale"
} | {
"commits": [
{
"message": "Fix overriding global locale"
},
{
"message": "wip"
},
{
"message": "formatting"
},
{
"message": "Update Request.php"
}
],
"files": [
{
"diff": "@@ -451,9 +451,9 @@ public static function createFrom(self $from, $to = null)\n \n $request->headers->replace($from->headers->all());\n \n- $request->setLocale($from->getLocale());\n+ $request->setRequestLocale($from->getLocale());\n \n- $request->setDefaultLocale($from->getDefaultLocale());\n+ $request->setDefaultRequestLocale($from->getDefaultLocale());\n \n $request->setJson($from->json());\n \n@@ -572,6 +572,28 @@ public function setLaravelSession($session)\n $this->session = $session;\n }\n \n+ /**\n+ * Set the locale for the request instance.\n+ *\n+ * @param string $locale\n+ * @return void\n+ */\n+ public function setRequestLocale(string $locale)\n+ {\n+ $this->locale = $locale;\n+ }\n+\n+ /**\n+ * Set the default locale for the request instance.\n+ *\n+ * @param string $locale\n+ * @return void\n+ */\n+ public function setDefaultRequestLocale(string $locale)\n+ {\n+ $this->defaultLocale = $locale;\n+ }\n+\n /**\n * Get the user making the request.\n *",
"filename": "src/Illuminate/Http/Request.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: v9.19.0\r\n- PHP Version: 8.1.6\r\n\r\n### Description:\r\n\r\nAccording to [documentation](https://laravel.com/docs/9.x/queues#unique-jobs), implementing ShouldBeUnique on job class is enough to ensure only one instance of given job is present in the queue. However, using `dynamodb` cache driver without setting `$uniqueFor` explicitly makes the lock item expire after 1 second, because `expires_at` is set to current timestamp when `$uniqueFor` is 0 (default value).\r\n\r\nThis is the change event in DynamoDB table after `putItem` request when trying to acquire job lock:\r\n\r\n```\r\n{\r\n \"awsRegion\": \"eu-central-1\",\r\n \"eventID\": \"4cb2d5b3-4954-451e-8332-01671dd2bf3e\",\r\n \"eventName\": \"INSERT\",\r\n \"userIdentity\": null,\r\n \"recordFormat\": \"application/json\",\r\n \"tableName\": \"vapor_cache\",\r\n \"dynamodb\": {\r\n \"ApproximateCreationDateTime\": 1658222276198,\r\n \"Keys\": {\r\n \"key\": {\r\n \"S\": \"cloud-api-production:cloud-api-production:laravel_unique_job:App\\\\Jobs\\\\<job-name>\"\r\n }\r\n },\r\n \"NewImage\": {\r\n \"value\": {\r\n \"S\": \"s:16:\\\"D7X1915ojxbQW6sU\\\";\"\r\n },\r\n \"key\": {\r\n \"S\": \"cloud-api-production:cloud-api-production:laravel_unique_job:App\\\\Jobs\\\\<job-name>\"\r\n },\r\n \"expires_at\": {\r\n \"N\": \"1658222276\"\r\n }\r\n },\r\n \"SizeBytes\": 237\r\n },\r\n \"eventSource\": \"aws:dynamodb\"\r\n}\r\n```\r\n\r\n`expires_at` is equal to current timestamp (see `ApproximateCreationDateTime`), so trying to acquire the lock in the following second will work because of used condition:\r\n\r\nhttps://github.com/laravel/framework/blob/d425952e8cc664b01de8bd654336c1be8dcf7444/src/Illuminate/Cache/DynamoDbStore.php#L273\r\n\r\nIt seems like the behavior is not consistent across other cache providers, e.g. `database` cache provider uses lock expiration time of 1 day if no time was provided:\r\n\r\nhttps://github.com/laravel/framework/blob/d425952e8cc664b01de8bd654336c1be8dcf7444/src/Illuminate/Cache/DatabaseLock.php#L92-L95\r\n\r\n`redis` provider creates non-expiring item:\r\n\r\nhttps://github.com/laravel/framework/blob/d425952e8cc664b01de8bd654336c1be8dcf7444/src/Illuminate/Cache/RedisLock.php#L35-L42\r\n\r\n`memcached` items doesn't expire with expiration time set to 0.\r\n\r\nWhile `dynamodb` items expire in the next second after the lock is acquired.\r\n\r\nPossible solution would be to use 1 day as default expiration value, as in `database` cache provider case.\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Use `dynamodb` cache provider\r\n2. Create a job implementing `ShouldBeUnique` that takes longer than a few seconds to complete\r\n3. Try to dispatch the job two times, more than 1 second apart\r\n4. The job will be executed concurrently despite implementing `ShouldBeUnique`\r\n\r\nRepository demonstrating the issue: https://github.com/Wowu/laravel-dynamodb-bug-report\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Can you make a PR to fix the issue?",
"created_at": "2022-07-21T15:26:23Z"
},
{
"body": "We merged a fix. Thanks!",
"created_at": "2022-07-22T14:58:55Z"
}
],
"number": 43280,
"title": "ShouldBeUnique with DynamoDB provider doesn't work as expected with default configuration"
} | {
"body": "I've added a default lock duration of 1 day for DynamoDB locks.\r\n\r\nThis makes the behavior consistent with `DatabaseLock`:\r\nhttps://github.com/laravel/framework/blob/d425952e8cc664b01de8bd654336c1be8dcf7444/src/Illuminate/Cache/DatabaseLock.php#L92-L95\r\n\r\n\r\nFix #43280",
"number": 43365,
"review_comments": [],
"title": "[8.x] Fix DynamoDB locks with 0 seconds duration"
} | {
"commits": [
{
"message": "Fix DynamoDB locks with 0 seconds duration"
},
{
"message": "Update DynamoDbLock.php"
}
],
"files": [
{
"diff": "@@ -34,9 +34,11 @@ public function __construct(DynamoDbStore $dynamo, $name, $seconds, $owner = nul\n */\n public function acquire()\n {\n- return $this->dynamo->add(\n- $this->name, $this->owner, $this->seconds\n- );\n+ if ($this->seconds > 0) {\n+ return $this->dynamo->add($this->name, $this->owner, $this->seconds);\n+ } else {\n+ return $this->dynamo->add($this->name, $this->owner, 86400);\n+ }\n }\n \n /**",
"filename": "src/Illuminate/Cache/DynamoDbLock.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "#43065 using `resolve()` causes Lumen app broken.\r\n\r\n```\r\n[2022-07-20 20:11:01] production.ERROR: Call to undefined function Illuminate\\Console\\View\\Components\\resolve() {\"exception\":\"[object] (Error(code: 0): Call to undefined function Illuminate\\\\Console\\\\View\\\\Components\\\r\nesolve() at /data/wwww/vendor/illuminate/console/View/Components/Component.php:89)\r\n[stacktrace]\r\n#0 /data/wwww/vendor/illuminate/console/View/Components/Task.php(22): Illuminate\\\\Console\\\\View\\\\Components\\\\Component->mutate()\r\n#1 /data/wwww/vendor/illuminate/console/View/Components/Factory.php(56): Illuminate\\\\Console\\\\View\\\\Components\\\\Task->render()\r\n#2 /data/wwww/vendor/illuminate/console/Scheduling/ScheduleRunCommand.php(199): Illuminate\\\\Console\\\\View\\\\Components\\\\Factory->__call()\r\n#3 /data/wwww/vendor/illuminate/console/Scheduling/ScheduleRunCommand.php(127): Illuminate\\\\Console\\\\Scheduling\\\\ScheduleRunCommand->runEvent()\r\n#4 /data/wwww/vendor/illuminate/container/BoundMethod.php(36): Illuminate\\\\Console\\\\Scheduling\\\\ScheduleRunCommand->handle()\r\n#5 /data/wwww/vendor/illuminate/container/Util.php(41): Illuminate\\\\Container\\\\BoundMethod::Illuminate\\\\Container\\\\{closure}()\r\n#6 /data/wwww/vendor/illuminate/container/BoundMethod.php(93): Illuminate\\\\Container\\\\Util::unwrapIfClosure()\r\n#7 /data/wwww/vendor/illuminate/container/BoundMethod.php(37): Illuminate\\\\Container\\\\BoundMethod::callBoundMethod()\r\n#8 /data/wwww/vendor/illuminate/container/Container.php(651): Illuminate\\\\Container\\\\BoundMethod::call()\r\n#9 /data/wwww/vendor/illuminate/console/Command.php(139): Illuminate\\\\Container\\\\Container->call()\r\n#10 /data/wwww/vendor/symfony/console/Command/Command.php(308): Illuminate\\\\Console\\\\Command->execute()\r\n#11 /data/wwww/vendor/illuminate/console/Command.php(124): Symfony\\\\Component\\\\Console\\\\Command\\\\Command->run()\r\n#12 /data/wwww/vendor/symfony/console/Application.php(998): Illuminate\\\\Console\\\\Command->run()\r\n#13 /data/wwww/vendor/symfony/console/Application.php(299): Symfony\\\\Component\\\\Console\\\\Application->doRunCommand()\r\n#14 /data/wwww/vendor/symfony/console/Application.php(171): Symfony\\\\Component\\\\Console\\\\Application->doRun()\r\n#15 /data/wwww/vendor/illuminate/console/Application.php(102): Symfony\\\\Component\\\\Console\\\\Application->run()\r\n#16 /data/wwww/vendor/laravel/lumen-framework/src/Console/Kernel.php(116): Illuminate\\\\Console\\\\Application->run()\r\n#17 /data/wwww/artisan(35): Laravel\\\\Lumen\\\\Console\\\\Kernel->handle()\r\n#18 {main}\r\n\"} \r\n```",
"number": 43312,
"review_comments": [],
"title": "Replace resolve() with app() for Lumen compatible"
} | {
"commits": [
{
"message": "Replace resolve() with app() for Lumen compatible"
}
],
"files": [
{
"diff": "@@ -83,10 +83,10 @@ protected function mutate($data, $mutators)\n foreach ($mutators as $mutator) {\n if (is_iterable($data)) {\n foreach ($data as $key => $value) {\n- $data[$key] = resolve($mutator)->__invoke($value);\n+ $data[$key] = app($mutator)->__invoke($value);\n }\n } else {\n- $data = resolve($mutator)->__invoke($data);\n+ $data = app($mutator)->__invoke($data);\n }\n }\n ",
"filename": "src/Illuminate/Console/View/Components/Component.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.18.0\r\n- PHP Version: 8.1.2\r\n- Database Driver & Version: MariaDB 10.4.22\r\n\r\n### Description:\r\nWhen trying to follow a cursor returned by `cursorPaginate()`, if records have been deleted, a server error response (500) is returned.\r\n\r\nAn exception with the message \"only arrays and objects are supported when cursor paginating items\" is being thrown by Laravel.\r\n\r\nThis does not appear to be the expected behavior.\r\n\r\n### Steps To Reproduce:\r\nSimply use cursor pagination (with `cursorPaginate()`) in a query, retrieve part of the records, delete all records and try to follow the cursor.\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "@claudiofabiao It is difficult to understand in this way, can you explain all the methods and processes you use in order to understand.",
"created_at": "2022-06-26T20:07:52Z"
},
{
"body": "Hi, @selcukcukur.\r\n\r\nI created a repository to demonstrate: [https://github.com/claudiofabiao/bug-report](https://github.com/claudiofabiao/bug-report).\r\n\r\nSteps to reproduce:\r\n\r\n- clone the repository\r\n- run `php artisan migrate --seed`\r\n- load the first 25 tasks into _/tasks_ and store `next_cursor` for later use\r\n- delete all DB tasks\r\n- now try following the stored `next_cursor` via /tasks?cursor=CURSOR_HERE\r\n\r\nAn exception will be thrown.",
"created_at": "2022-06-26T20:31:35Z"
},
{
"body": "`return Task::query()->cursorPaginate(25);`\r\n\r\nI didn't have any problems with a clean install this way.",
"created_at": "2022-06-26T20:49:22Z"
},
{
"body": "@claudiofabiao It looks like everything is fine. Something you did or an external action you did is causing the problem. Everything seems fine in my tests. I also followed the steps you did.",
"created_at": "2022-06-26T20:50:30Z"
},
{
"body": " @php\r\n $users = \\App\\Models\\User::query()->cursorPaginate(1);\r\n @endphp\r\n\r\n <div class=\"container\">\r\n @foreach ($users as $user)\r\n {{ $user->name }}\r\n @endforeach\r\n </div>\r\n {{ $users->links() }}\r\n\r\nI haven't fully studied your usage, though. This is the shape you should use.",
"created_at": "2022-06-26T20:54:58Z"
},
{
"body": "Hi, @selcukcukur.\r\n\r\nSorry, but I do not understand.\r\n\r\nDid you delete the records and then try to follow `next_cursor`?\r\n\r\nWhat was the response received?\r\n\r\nI've attached the response I get.\r\n\r\nThis is a clean install.\r\n\r\n",
"created_at": "2022-06-26T20:58:29Z"
},
{
"body": "@claudiofabiao I misunderstood what you said. Now I fully understand.",
"created_at": "2022-06-26T21:24:56Z"
},
{
"body": "Sent PR #42963 to address this issue",
"created_at": "2022-06-26T22:44:04Z"
},
{
"body": "Hi, @selcukcukur and @rodrigopedra.\r\n\r\nI thank you very much for your attention.\r\n\r\nI will follow the PR #42963.\r\n\r\nI am available to help, if needed.",
"created_at": "2022-06-26T23:51:42Z"
}
],
"number": 42962,
"title": "Cursor pagination fails if records have been deleted"
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nCloses #42962 \r\n\r\nAs noted by issue #42962, if the user has a link to a next, or previous page from a pagination using cursor pagination, accessing this URL throws an exception when no items are found.\r\n\r\nThis PR:\r\n\r\n- Modifies `AbstractCursorPaginator@previousCursor` and `AbstractCursorPaginator@nextCursor` methods to check if the `$items` collection is empty, and if so early returning `null` before trying to build their respective `Cursor` instances\r\n- Add a test case that would fail without the this PR's proposed changes\r\n\r\n",
"number": 42963,
"review_comments": [],
"title": "[8.x] Handle cursor paginator when no items are found"
} | {
"commits": [
{
"message": "handle cursor paginator when no items are found"
},
{
"message": "StyleCI suugested fix"
}
],
"files": [
{
"diff": "@@ -155,6 +155,10 @@ public function previousCursor()\n return null;\n }\n \n+ if ($this->items->isEmpty()) {\n+ return null;\n+ }\n+\n return $this->getCursorForItem($this->items->first(), false);\n }\n \n@@ -170,6 +174,10 @@ public function nextCursor()\n return null;\n }\n \n+ if ($this->items->isEmpty()) {\n+ return null;\n+ }\n+\n return $this->getCursorForItem($this->items->last(), true);\n }\n ",
"filename": "src/Illuminate/Pagination/AbstractCursorPaginator.php",
"status": "modified"
},
{
"diff": "@@ -4,6 +4,7 @@\n \n use Illuminate\\Pagination\\Cursor;\n use Illuminate\\Pagination\\CursorPaginator;\n+use Illuminate\\Support\\Collection;\n use PHPUnit\\Framework\\TestCase;\n \n class CursorPaginatorTest extends TestCase\n@@ -76,6 +77,26 @@ public function testCanTransformPaginatorItems()\n $this->assertSame([['id' => 6], ['id' => 7]], $p->items());\n }\n \n+ public function testReturnEmptyCursorWhenItemsAreEmpty()\n+ {\n+ $cursor = new Cursor(['id' => 25], true);\n+\n+ $p = new CursorPaginator(Collection::make(), 25, $cursor, [\n+ 'path' => 'http://website.com/test',\n+ 'cursorName' => 'cursor',\n+ 'parameters' => ['id'],\n+ ]);\n+\n+ $this->assertInstanceOf(CursorPaginator::class, $p);\n+ $this->assertSame([\n+ 'data' => [],\n+ 'path' => 'http://website.com/test',\n+ 'per_page' => 25,\n+ 'next_page_url' => null,\n+ 'prev_page_url' => null,\n+ ], $p->toArray());\n+ }\n+\n protected function getCursor($params, $isNext = true)\n {\n return (new Cursor($params, $isNext))->encode();",
"filename": "tests/Pagination/CursorPaginatorTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version:9.17.0\r\n- PHP Version: 8.1.7\r\n\r\n### Description:\r\n\r\nThe `catch` callback attached to a chain of jobs is called more than once when using the `sync` connection. I expected the catch callback to only be called once. It's only called once for the redis and sqs queue connection. This is best illustrated as an example.\r\n \r\n```\r\n Bus::chain([\r\n new TestJob(1),\r\n new TestJob(2),\r\n new TestJob(3),\r\n new TestJob(4, exception: true),\r\n new TestJob(5),\r\n new TestJob(6),\r\n new TestJob(7),\r\n ])->catch(function (Throwable $e): void {\r\n dump('A job within the chain has failed...');\r\n })->onConnection('sync')->dispatch();\r\n```\r\n\r\nThe above chain will call catch 4 times.\r\n\r\n```\r\n\"A job within the chain has failed...\"\r\n\"A job within the chain has failed...\"\r\n\"A job within the chain has failed...\"\r\n\"A job within the chain has failed...\"\r\n\r\n Exception\r\n\r\n foobar 4\r\n\r\n```\r\n\r\nThe further down the exception the more times catch will be called for example if the exception at index 4 catch will be called 5 times, if it's at index 5 it will be called 6 times, etc.\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\nHere is an isolated console command to test it:\r\n\r\n```\r\n<?php\r\n\r\ndeclare(strict_types=1);\r\n\r\nnamespace App\\Console\\Commands;\r\n\r\nuse Illuminate\\Bus\\Queueable;\r\nuse Illuminate\\Console\\Command;\r\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\r\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\r\nuse Illuminate\\Queue\\InteractsWithQueue;\r\nuse Illuminate\\Support\\Facades\\Bus;\r\n\r\nfinal class TestJob implements ShouldQueue\r\n{\r\n use Dispatchable;\r\n use InteractsWithQueue;\r\n use Queueable;\r\n\r\n public function __construct(protected int $id, protected bool $exception = false)\r\n {\r\n }\r\n\r\n public function handle(): void\r\n {\r\n dump(__METHOD__.\" {$this->id}\");\r\n\r\n if ($this->exception) {\r\n throw new \\Exception(\"foobar {$this->id}\");\r\n }\r\n }\r\n}\r\n\r\nfinal class TestChainCommand extends Command\r\n{\r\n /**\r\n * The name and signature of the console command.\r\n *\r\n * @var string\r\n */\r\n protected $signature = 'sandbox:chain';\r\n\r\n /**\r\n * The console command description.\r\n *\r\n * @var string\r\n */\r\n protected $description = 'Test chained job exceptions';\r\n\r\n /**\r\n * Execute the console command.\r\n */\r\n public function handle(): int\r\n {\r\n Bus::chain([\r\n new TestJob(1),\r\n new TestJob(2),\r\n new TestJob(3),\r\n new TestJob(4, exception: true),\r\n new TestJob(5),\r\n new TestJob(6),\r\n new TestJob(7),\r\n ])->catch(function (\\Throwable $e): void {\r\n dump('A job within the chain has failed...');\r\n })->onConnection('sync')->dispatch();\r\n\r\n return 0;\r\n }\r\n}\r\n```\r\n\r\n",
"comments": [
{
"body": "This indeed sounds like a bug. Would appreciate any help with figuring this one out.",
"created_at": "2022-06-23T14:16:07Z"
},
{
"body": "My understanding is that the sync queue handles exceptions directly rather than inserting them into the failed_jobs database table: \r\n\r\n> After an asynchronous job has exceeded this number of attempts, it will be inserted into the failed_jobs database table. [Synchronously dispatched jobs](https://laravel.com/docs/9.x/queues#synchronous-dispatching) that fail are not stored in this table and their exceptions are immediately handled by the application. -- https://laravel.com/docs/9.x/queues#dealing-with-failed-jobs\r\n\r\nSo one issue is that I only expect the catch callback to be executed once, but also I don't really expect the exception to bubble up if a catch callback is defined, I expect the exception to caught by the callback and maybe only bubble up if the catch callback rethrows it.\r\n\r\nThe same issue applies to batched jobs and I've noticed that the `finally` callback is not called if an exception is thrown either:\r\n\r\n```\r\n Bus::batch($jobs)\r\n ->catch(static fn (...$args) => self::onCatch(...$args))\r\n ->finally(static fn (...$args) => self::onFinally(...$args))\r\n ->dispatch();\r\n```\r\n\r\nIn the above the catch callback will be called for each job and the finally callback won't be called. Again I expect the catch to only be called once, the finally callback to be called, and like the chained jobs I really expect the catch callback to prevent the exception from bubbling up.\r\n\r\nToggling `allowFailures` makes no difference:\r\n\r\n```\r\n Bus::batch($jobs)\r\n ->allowFailures(true)\r\n ->catch(static fn (...$args) => self::onCatch(...$args))\r\n ->finally(static fn (...$args) => self::onFinally(...$args))\r\n ->dispatch();\r\n ```\r\n",
"created_at": "2022-06-23T14:59:02Z"
},
{
"body": "Sent PR #42950 to address this issue",
"created_at": "2022-06-25T13:37:58Z"
},
{
"body": "One of my tests failed with the recent release. \r\n\r\nI've narrowed the issue down to the `finally` method on a batch of jobs is not being called if there is an exception in one of the jobs **and** the exception occurs before the last job.\r\n\r\nFor example in the following the `finally` method will not be invoked. However, if you comment out job 5 and 6 the `finally` **will** be called. Should we open up a separate issue for this?\r\n\r\n```\r\n\r\n $jobs = [\r\n new TestBatchJob(1),\r\n new TestBatchJob(2),\r\n new TestBatchJob(3),\r\n new TestBatchJob(4, exception: true),\r\n new TestBatchJob(5),\r\n new TestBatchJob(6),\r\n ];\r\n\r\n Bus::batch($jobs)\r\n ->allowFailures(true)\r\n ->catch(function (): void {\r\n dump('A job within the chain has failed...');\r\n })\r\n ->finally(function (): void {\r\n dump('Batch finally called...');\r\n })\r\n ->onConnection('sync')->dispatch();\r\n```\r\n\r\nHere is the `TestBatchJob`:\r\n\r\n```\r\nfinal class TestBatchJob implements ShouldQueue\r\n{\r\n use Batchable;\r\n use Dispatchable;\r\n use InteractsWithQueue;\r\n use Queueable;\r\n\r\n public function __construct(protected int $id, protected bool $exception = false)\r\n {\r\n }\r\n\r\n public function handle(): void\r\n {\r\n dump(__METHOD__.\" {$this->id}\");\r\n\r\n if ($this->exception) {\r\n dump(__METHOD__.\" {$this->id} throwing exception\");\r\n throw new \\Exception(\"foobar {$this->id}\");\r\n }\r\n }\r\n}\r\n```\r\n\r\nI've tested the new fixes on more complicated dispatches. The new fix seems to resolve all the other issues. There are no longer duplicate calls to the catch callbacks and the exceptions no longer bubble up. :sparkles: :rocket: \r\n\r\n```\r\n\r\n Bus::chain([\r\n new TestJob(1),\r\n new TestJob(2),\r\n new TestJob(3),\r\n // new TestJob(4, exception: true),\r\n function (): void {\r\n Bus::batch([\r\n new TestBatchJob(1),\r\n new TestBatchJob(2),\r\n new TestBatchJob(3),\r\n new TestBatchJob(4, exception: true),\r\n // new TestBatchJob(5),\r\n // new TestBatchJob(6),\r\n ])\r\n ->allowFailures(true)\r\n ->catch(function (): void {\r\n dump('A job within the BATCH has failed...');\r\n })\r\n ->finally(function (): void {\r\n dump('The batch FINALLY called...');\r\n })\r\n ->onConnection('sync')->dispatch();\r\n },\r\n ])->catch(function (\\Throwable $e): void {\r\n dump('A job within the CHAIN has failed...');\r\n })->onConnection('sync')->dispatch();\r\n```\r\n\r\n\r\n",
"created_at": "2022-07-13T17:07:22Z"
},
{
"body": "I just noticed something else, if there is an exception in a batch job, is it rolling back the DB after the finally callback? ",
"created_at": "2022-07-13T17:37:39Z"
},
{
"body": "I've tested the first snippet you sent here ( https://github.com/laravel/framework/issues/42883#issuecomment-1183473224 ) without the changes from #42950 and the finally callback is not called when using the sync connection **AND** allowing failures.\r\n\r\nWhen not allowing failures it works as expected\r\n\r\nAfter first inspection it seems to be a different issue, specific to the command bus, but my feeling is the fix might be similar, but I won't have time to further until the weekend.\r\n",
"created_at": "2022-07-13T21:44:56Z"
},
{
"body": "Cool. Note that changing `allowFailures` doesn't make any difference in my testing. The finally method is called fine if no exceptions are throw. It's also called if the exception occurs in the last job in the batch. It's not called if the exception occurs before the last job.\r\n\r\n\r\nThere may be one other separate issue too: it looks like the finally call is wrapped in a db transaction so when an exception occurs any changes to db in the finally callback are rolled back. This doesn't happen in other connections like redis. ",
"created_at": "2022-07-14T14:20:40Z"
},
{
"body": "Let's create separate issues for the other bugs. Thanks all!",
"created_at": "2022-07-19T12:25:48Z"
},
{
"body": "Does anyone have any ideas on how to resend in https://github.com/laravel/framework/pull/42950 without the breaking change?",
"created_at": "2022-08-02T12:00:54Z"
},
{
"body": "Hi all, it looks like this cannot be solved without introducing a breaking change. Feel free to PR master with the above PR.\r\n\r\n@bramdevries feel free to provide a comment on that PR if you want to advocate against a breaking change.",
"created_at": "2022-08-08T14:41:50Z"
}
],
"number": 42883,
"title": "The catch callback attached to a chain of jobs is called more than once"
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nCloses #42883\r\n\r\nAs noted by issue #42883, when a chain of jobs is dispatched and a closure is provided to the chain's `catch` method, if an exception occur, the callback is called multiple times.\r\n\r\nFor example, consider this code:\r\n\r\n~~~php\r\nBus::chain([\r\n new TestJob(1),\r\n new TestJob(2),\r\n new TestJob(3),\r\n new TestJob(4, exception: true),\r\n new TestJob(5),\r\n new TestJob(6),\r\n new TestJob(7),\r\n])->catch(function (Throwable $e): void {\r\n dump('A job within the chain has failed...');\r\n})->onConnection('sync')->dispatch();\r\n~~~\r\n\r\nWhen `new TestJob(4, exception: true)` throws an exception, the call back will be called 4 times, one for each of these job instances:\r\n\r\n- `new TestJob(4, exception: true)`\r\n- `new TestJob(3)`\r\n- `new TestJob(2)`\r\n- `new TestJob(1)`\r\n\r\nIf `new TestJob(4, exception: true)` was defined further down on the chain, the callback would be called more times, and vice-versa.\r\n\r\nThis happens as each job in the `sync` queue is executed in the same PHP process, so when the next job is dispatched it is actually \"called\" within the same execution call stack. \r\n\r\nThus when an exception is thrown the exception triggers the `SyncQueue` exception handler multiple times, one for each job awaiting the execution call stack to complete.\r\n\r\nThis PR\r\n\r\n- Adds an instance property to `SyncQueue` to track how many jobs were already pushed within its execution call stack\r\n- Adds a guard to `SyncQueue@handleException` method, to ensure the handler is called only once for that execution call stack\r\n- Adds a test case which fails without this PR's code \r\n\r\n",
"number": 42950,
"review_comments": [],
"title": "[8.x] Prevent double throwing chained exception on sync queue"
} | {
"commits": [
{
"message": "prevent double throwing chained exception on sync queue"
},
{
"message": "decrease job count after processing"
}
],
"files": [
{
"diff": "@@ -12,6 +12,8 @@\n \n class SyncQueue extends Queue implements QueueContract\n {\n+ protected $jobsCount = 0;\n+\n /**\n * Get the size of the queue.\n *\n@@ -37,6 +39,8 @@ public function push($job, $data = '', $queue = null)\n {\n $queueJob = $this->resolveJob($this->createPayload($job, $queue, $data), $queue);\n \n+ $this->jobsCount++;\n+\n try {\n $this->raiseBeforeJobEvent($queueJob);\n \n@@ -45,6 +49,8 @@ public function push($job, $data = '', $queue = null)\n $this->raiseAfterJobEvent($queueJob);\n } catch (Throwable $e) {\n $this->handleException($queueJob, $e);\n+ } finally {\n+ $this->jobsCount--;\n }\n \n return 0;\n@@ -113,11 +119,19 @@ protected function raiseExceptionOccurredJobEvent(Job $job, Throwable $e)\n */\n protected function handleException(Job $queueJob, Throwable $e)\n {\n- $this->raiseExceptionOccurredJobEvent($queueJob, $e);\n+ static $isGuarded = false;\n+\n+ if ($isGuarded) {\n+ $isGuarded = false;\n+ } else {\n+ $isGuarded = $this->jobsCount > 1;\n \n- $queueJob->fail($e);\n+ $this->raiseExceptionOccurredJobEvent($queueJob, $e);\n \n- throw $e;\n+ $queueJob->fail($e);\n+\n+ throw $e;\n+ }\n }\n \n /**",
"filename": "src/Illuminate/Queue/SyncQueue.php",
"status": "modified"
},
{
"diff": "@@ -12,7 +12,7 @@\n \n class JobChainingTest extends TestCase\n {\n- public static $catchCallbackRan = false;\n+ public static $catchCallbackCount = 0;\n \n protected function getEnvironmentSetUp($app)\n {\n@@ -30,7 +30,6 @@ protected function tearDown(): void\n JobChainingTestFirstJob::$ran = false;\n JobChainingTestSecondJob::$ran = false;\n JobChainingTestThirdJob::$ran = false;\n- static::$catchCallbackRan = false;\n }\n \n public function testJobsCanBeChainedOnSuccess()\n@@ -148,19 +147,56 @@ public function testThirdJobIsNotFiredIfSecondFails()\n \n public function testCatchCallbackIsCalledOnFailure()\n {\n+ self::$catchCallbackCount = 0;\n+\n Bus::chain([\n new JobChainingTestFirstJob,\n new JobChainingTestFailingJob,\n new JobChainingTestSecondJob,\n ])->catch(static function () {\n- self::$catchCallbackRan = true;\n+ self::$catchCallbackCount++;\n })->dispatch();\n \n $this->assertTrue(JobChainingTestFirstJob::$ran);\n- $this->assertTrue(static::$catchCallbackRan);\n+ $this->assertSame(1, static::$catchCallbackCount);\n $this->assertFalse(JobChainingTestSecondJob::$ran);\n }\n \n+ public function testCatchCallbackIsCalledOnceOnSyncQueue()\n+ {\n+ self::$catchCallbackCount = 0;\n+\n+ try {\n+ Bus::chain([\n+ new JobChainingTestFirstJob(),\n+ new JobChainingTestThrowJob(),\n+ new JobChainingTestSecondJob(),\n+ ])->catch(function () {\n+ self::$catchCallbackCount++;\n+ })->onConnection('sync')->dispatch();\n+ } finally {\n+ $this->assertTrue(JobChainingTestFirstJob::$ran);\n+ $this->assertSame(1, static::$catchCallbackCount);\n+ $this->assertFalse(JobChainingTestSecondJob::$ran);\n+ }\n+\n+ self::$catchCallbackCount = 0;\n+\n+ try {\n+ Bus::chain([\n+ new JobChainingTestFirstJob(),\n+ new JobChainingTestThrowJob(),\n+ new JobChainingTestSecondJob(),\n+ ])->catch(function () {\n+ self::$catchCallbackCount++;\n+ })->onConnection('sync')->dispatch();\n+ } finally {\n+ $this->assertTrue(JobChainingTestFirstJob::$ran);\n+ $this->assertSame(1, static::$catchCallbackCount);\n+ $this->assertFalse(JobChainingTestSecondJob::$ran);\n+ }\n+ }\n+\n public function testChainJobsUseSameConfig()\n {\n JobChainingTestFirstJob::dispatch()->allOnQueue('some_queue')->allOnConnection('sync1')->chain([\n@@ -293,3 +329,13 @@ public function handle()\n $this->fail();\n }\n }\n+\n+class JobChainingTestThrowJob implements ShouldQueue\n+{\n+ use Dispatchable, InteractsWithQueue, Queueable;\n+\n+ public function handle()\n+ {\n+ throw new \\Exception();\n+ }\n+}",
"filename": "tests/Integration/Queue/JobChainingTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.17\r\n- PHP Version: 8.0.23\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n\r\nWhen using `forceCreate()` on a morph relation (`morphOne|morphMany`), the morph type column is not added.\r\n\r\n```\r\n$post->comments()->forceCreate(['body' => 'Cool article']);\r\n```\r\n\r\nThis behavior is realated to #42281.\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\nclass Post extends Model\r\n{\r\n public $fillable = ['*'];\r\n public function comments() { return $this->morphMany(Comment::class, 'commentable'); }\r\n}\r\n\r\nclass Comment extends Model\r\n{\r\n public function commentable() { return $this->morphTo(); }\r\n}\r\n\r\n$post = Post::create(['body' => 'Hello world!']);\r\n\r\n$post->comments()->forceCreate(['body' => 'Cool article']);\r\n\r\n// Illuminate\\Database\\QueryException : \r\n// SQLSTATE[23000]: \r\n// Integrity constraint violation: \r\n// 19 NOT NULL constraint failed: comments.commentable_type\r\n// ...\r\n```",
"comments": [
{
"body": "As I understand `make` doesn't create a new row in the database it just creates a new instance of the class you request, I tried to test your code with `create` instead of `make`, and it's worked well, because `create` persists to the database, the code will be like this \r\n\r\n\r\n\r\n```\r\n$post = Post::create(['body' => 'Hello world!']);\r\n\r\n$post->comments()->forceCreate(['body' => 'Cool article']);\r\n```\r\nI'm not sure if it should also work well with `make` or not because `make` will not return a new `id`, so even if he knows the `commentable_type`, he'll give another error because it didn't know the `commentable_id` in your case, correct me if I'm wrong?\r\n",
"created_at": "2022-06-25T18:34:18Z"
},
{
"body": "> As I understand `make` doesn't create a new row in the database it just creates a new instance of the class you request, I tried to test your code with `create` instead of `make`, and it's worked well, because `create` persists to the database, the code will be like this\r\n> \r\n> ```\r\n> $post = Post::create(['body' => 'Hello world!']);\r\n> \r\n> $post->comments()->forceCreate(['body' => 'Cool article']);\r\n> ```\r\n> \r\n> I'm not sure if it should also work well with `make` or not because `make` will not return a new `id`, so even if he knows the `commentable_type`, he'll give another error because it didn't know the `commentable_id` in your case, correct me if I'm wrong?\r\n\r\nYou're correct, my example was bad. I used `create`, so I fixed the example.",
"created_at": "2022-06-25T20:03:31Z"
},
{
"body": "Looks like a fix was accepted: https://github.com/laravel/framework/pull/42929",
"created_at": "2022-06-26T12:53:00Z"
}
],
"number": 42796,
"title": "Calling `forceCreate()` on a MorphMany relation doesn't includes morph type"
} | {
"body": "Fixes #42796\r\n\r\n`forceCreate` was not including the morph type on the attributes sent to create the related model. The forceCreate method has been overrided to include the morph type on the attributes before passing the call to its parent.\r\n\r\nThis should solve the #42796 issue.\r\n",
"number": 42929,
"review_comments": [],
"title": "[8.x] Fixed bug on forceCreate on a MorphMay relationship not including morph type"
} | {
"commits": [
{
"message": "Fixed bug on forceCreate on a MorphMay relationship not including morph type"
},
{
"message": "Added test for morph many not including type bug"
},
{
"message": "Style fixes on MorphMany.php"
}
],
"files": [
{
"diff": "@@ -46,4 +46,16 @@ public function match(array $models, Collection $results, $relation)\n {\n return $this->matchMany($models, $results, $relation);\n }\n+\n+ /**\n+ * Create a new instance of the related model. Allow mass-assignment.\n+ *\n+ * @param array $attributes\n+ * @return \\Illuminate\\Database\\Eloquent\\Model\n+ */\n+ public function forceCreate(array $attributes = []) \n+ {\n+ $attributes[$this->getMorphType()] = $this->morphClass;\n+ parent::forceCreate($attributes);\n+ }\n }",
"filename": "src/Illuminate/Database/Eloquent/Relations/MorphMany.php",
"status": "modified"
},
{
"diff": "@@ -94,6 +94,15 @@ public function testMorphType()\n $this->assertSame('active', $product->current_state->state);\n }\n \n+ public function testForceCreateMorphType()\n+ {\n+ $product = MorphOneOfManyTestProduct::create();\n+ $product->states()->forceCreate([\n+ 'state' => 'active',\n+ ]);\n+ $this->assertSame(MorphOneOfManyTestProduct::class, $product->current_state->stateful_type);\n+ }\n+\n public function testExists()\n {\n $product = MorphOneOfManyTestProduct::create();",
"filename": "tests/Database/DatabaseEloquentMorphOneOfManyTest.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nActually: \r\n- Model::toArray() cannot be called if the current model is trying to cast a property of type Enum\r\n```\r\nError: Cannot instantiate enum App\\Enums\\UserGender in file /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 1585\r\n\r\n#0 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(773): Illuminate\\Database\\Eloquent\\Model->resolveCasterClass('gender')\r\n#1 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(662): Illuminate\\Database\\Eloquent\\Model->getClassCastableAttributeValue('gender', NULL)\r\n#2 /var/www/app/Helpers/HasForeignAttributes.php(62): Illuminate\\Database\\Eloquent\\Model->mutateAttributeForArray('gender', NULL)\r\n#3 [internal function]: App\\Models\\User->__call('nickname', Array)\r\n#4 /var/www/app/Helpers/HasForeignAttributes.php(56): call_user_func(Array)\r\n#5 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(621): App\\Models\\User->__call('getNicknameAttr...', Array)\r\n#6 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(671): Illuminate\\Database\\Eloquent\\Model->mutateAttribute('nickname', NULL)\r\n#7 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(202): Illuminate\\Database\\Eloquent\\Model->mutateAttributeForArray('nickname', NULL)\r\n#8 /var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1517): Illuminate\\Database\\Eloquent\\Model->attributesToArray()\r\n#9 /var/www/routes/api.php(28): Illuminate\\Database\\Eloquent\\Model->toArray()\r\n```\r\n\r\n\r\nExpected:\r\n - Can call Model::toArray(), get enum value and no error\r\n\r\nTest:\r\n - [ ] I added 1 test case for this case\r\n\r\n",
"number": 42829,
"review_comments": [],
"title": "HasAttributes::mutateAttributeForArray - Fix support enum cast"
} | {
"commits": [
{
"message": "HasAttributes::mutateAttributeForArray - Fix support enum cast"
}
],
"files": [
{
"diff": "@@ -658,7 +658,9 @@ protected function mutateAttributeMarkedAttribute($key, $value)\n */\n protected function mutateAttributeForArray($key, $value)\n {\n- if ($this->isClassCastable($key)) {\n+ if ($this->isEnumCastable($key)) {\n+ $value = $this->getEnumCastableAttributeValue($key, $value);\n+ } elseif ($this->isClassCastable($key)) {\n $value = $this->getClassCastableAttributeValue($key, $value);\n } elseif (isset(static::$getAttributeMutatorCache[get_class($this)][$key]) &&\n static::$getAttributeMutatorCache[get_class($this)][$key] === true) {",
"filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "Let's say you have a closure based route like this:\r\n\r\n```php\r\nuse Illuminate\\Support\\Facades\\Route;\r\n \r\nRoute::get('/', function () {\r\n return 'Hello World';\r\n});\r\n```\r\n\r\nAfter you run the `route:list` command, you'll see a deprecation warning in Laravel Telescope (under PHP 8.1), because there is no `action` defined for this route:\r\n\r\n```\r\nstr_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in /var/www/[...]/RouteListCommand.php on line 403\r\n```\r\n\r\n- https://php.watch/versions/8.1/internal-func-non-nullable-null-deprecation",
"number": 42704,
"review_comments": [],
"title": "[9.x] Fix deprecation error in the `route:list` command"
} | {
"commits": [
{
"message": "Fix deprecation error in the `route:list` command"
}
],
"files": [
{
"diff": "@@ -400,7 +400,7 @@ protected function forCli($routes)\n $spaces,\n preg_replace('#({[^}]+})#', '<fg=yellow>$1</>', $uri),\n $dots,\n- str_replace(' ', ' › ', $action),\n+ str_replace(' ', ' › ', $action ?? ''),\n ), $this->output->isVerbose() && ! empty($middleware) ? \"<fg=#6C7280>$middleware</>\" : null];\n })\n ->flatten()",
"filename": "src/Illuminate/Foundation/Console/RouteListCommand.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.14.1\r\n- PHP Version: 8.1.2\r\n- Database Driver & Version:\r\n\r\n### Description:\r\n\r\nI've recently updated Laravel from 9.13.0 to 9.14.1 and I have a series of nested apiResource routes defined like so:\r\n`$router->apiResource('/product/{product}/image', ImageController::class)->scoped();`\r\n\r\nI've found that when I request an image that doesn't belong to the product id specified in the URL, I get a 404 like I'd expect in v9.13.0, but in v9.14.1 the request falls through to the controller incorrectly... I may be doing something wrong but it has been working until today.\r\n\r\n### Steps To Reproduce:\r\n\r\nDefine a scoped API resource like the one above.\r\nRequest a URL where the child model is not owned by the parent model.\r\n\r\nExpected: The app throws a 404\r\nActual: The app calls the controller\r\n\r\nI've made a new laravel project to demonstrate: https://github.com/joe-pritchard/scoped-resource-bug\r\n\r\nThere's a test in there at `Tests\\Feature\\Models\\ChildTest` which shows the issue. The test fails, but it will pass if you downgrade the `laravel/framework` dependency to 9.13.0\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "i have exactly the same problem,\r\nthe problem appeared when I updated the laravel/framework version from `9.4.1` to `9.14.1`",
"created_at": "2022-05-29T14:22:04Z"
},
{
"body": "@ksassnowski ping! Can you watch it? I think the problem is because of this [PR](https://github.com/laravel/framework/pull/42517)",
"created_at": "2022-05-30T10:47:12Z"
},
{
"body": "I’ll have a look at this. Seems like that change had quite a few unforeseen knock-on effects. Sorry about that!",
"created_at": "2022-05-30T10:54:02Z"
},
{
"body": "OK so the fix itself could get a little tricky, but there's at least a temporary workaround for now. If you explicitly define the binding field when calling `scoped` on an api resource, it works as expected.\r\n\r\nSo instead of \r\n\r\n```php\r\nRoute::apiResource('/product/{product}/image', ImageController::class)->scoped();\r\n```\r\n\r\ndo this\r\n\r\n```php\r\nRoute::apiResource('/product/{product}/image', ImageController::class)->scoped([\r\n // Or whatever the route key for `Image` should be\r\n 'image' => 'id',\r\n]);\r\n```",
"created_at": "2022-05-30T11:23:59Z"
},
{
"body": "@ksassnowski if there's no way we can fix this except through a workaround we probably best revert the PR for now and re-add the changes in Laravel 10.",
"created_at": "2022-05-30T12:46:16Z"
},
{
"body": "I actually have a solution and am finishing up the PR right now",
"created_at": "2022-05-30T12:47:38Z"
},
{
"body": "Here's the PR #42571 ",
"created_at": "2022-05-30T13:35:19Z"
}
],
"number": 42541,
"title": "Scoped route binding in apiResource routes no longer working"
} | {
"body": "Fixes #42541\r\n\r\nFirst of all, I'm really sorry about all the issues the initial PR has caused 😞\r\n\r\n## Summary\r\n\r\nThis PR reverts most of the changes of the original PR (#42425) while still fixing the bug described in the PR. The only method that was changed was the `bindingFieldFor` method of the `Route` class. All changes to `ImplicitRouteBinding` and `RouteUri` were reverted.\r\n\r\nTo fix the bug described in the original PR, we now resolve the parameter index to the parameter name by looking it up in the route's `parameterNames` array. \r\n\r\n```php\r\npublic function bindingFieldFor($parameter)\r\n{\r\n if (is_int($parameter)) {\r\n $parameter = $this->parameterNames()[$parameter];\r\n }\r\n\r\n return $this->bindingFields[$parameter] ?? null;\r\n}\r\n```\r\n\r\nThis means that we no longer have to change the structure of the `bindingFields` array itself like in the original PR. The bug described in the related issue (#42541) was due to the fact that the `ResourceRouteRegistrar` _also_ filled the route's binding fields with `null` values, just like my change in the original PR. The problem with that is that both of these implementations used `null` to signal the exact opposite of each other. My PR used `null` to mean \"don't scope this parameter\", whereas the `ResourceRouteRegistrar` used it to mean \"scope this parameter but default to the model's route key name\".\r\n\r\nI left in all the additional tests I added since all the problems that got reported due to my original PR were not covered by any existing tests.",
"number": 42571,
"review_comments": [],
"title": "[9.x] Map integer parameter to parameter name when resolving binding field"
} | {
"commits": [
{
"message": "Map integer parameter to parameter name when resolving binding field"
}
],
"files": [
{
"diff": "@@ -46,7 +46,7 @@ public static function resolveForRoute($container, $route)\n ? 'resolveSoftDeletableRouteBinding'\n : 'resolveRouteBinding';\n \n- if ($parent instanceof UrlRoutable && ($route->enforcesScopedBindings() || $route->bindingFieldFor($parameterName) !== null)) {\n+ if ($parent instanceof UrlRoutable && ($route->enforcesScopedBindings() || array_key_exists($parameterName, $route->bindingFields()))) {\n $childRouteBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance))\n ? 'resolveSoftDeletableChildRouteBinding'\n : 'resolveChildRouteBinding';",
"filename": "src/Illuminate/Routing/ImplicitRouteBinding.php",
"status": "modified"
},
{
"diff": "@@ -535,9 +535,11 @@ public function signatureParameters($conditions = [])\n */\n public function bindingFieldFor($parameter)\n {\n- $fields = is_int($parameter) ? array_values($this->bindingFields) : $this->bindingFields;\n+ if (is_int($parameter)) {\n+ $parameter = $this->parameterNames()[$parameter];\n+ }\n \n- return $fields[$parameter] ?? null;\n+ return $this->bindingFields[$parameter] ?? null;\n }\n \n /**",
"filename": "src/Illuminate/Routing/Route.php",
"status": "modified"
},
{
"diff": "@@ -44,27 +44,19 @@ public static function parse($uri)\n $bindingFields = [];\n \n foreach ($matches[0] as $match) {\n- $parameter = trim($match, '{}?');\n-\n- if (! str_contains($parameter, ':')) {\n- $bindingFields[$parameter] = null;\n-\n+ if (! str_contains($match, ':')) {\n continue;\n }\n \n- $segments = explode(':', $parameter);\n+ $segments = explode(':', trim($match, '{}?'));\n \n $bindingFields[$segments[0]] = $segments[1];\n \n $uri = str_contains($match, '?')\n- ? str_replace($match, '{'.$segments[0].'?}', $uri)\n- : str_replace($match, '{'.$segments[0].'}', $uri);\n+ ? str_replace($match, '{'.$segments[0].'?}', $uri)\n+ : str_replace($match, '{'.$segments[0].'}', $uri);\n }\n \n- $bindingFields = ! empty(array_filter($bindingFields))\n- ? $bindingFields\n- : [];\n-\n return new static($uri, $bindingFields);\n }\n }",
"filename": "src/Illuminate/Routing/RouteUri.php",
"status": "modified"
},
{
"diff": "@@ -51,27 +51,22 @@ public function uriProvider()\n [\n '/foo/{bar}/baz/{qux:slug}',\n '/foo/{bar}/baz/{qux}',\n- ['bar' => null, 'qux' => 'slug'],\n+ ['qux' => 'slug'],\n ],\n [\n '/foo/{bar}/baz/{qux:slug}',\n '/foo/{bar}/baz/{qux}',\n- ['bar' => null, 'qux' => 'slug'],\n- ],\n- [\n- '/foo/{bar:slug}/baz/{qux}',\n- '/foo/{bar}/baz/{qux}',\n- ['bar' => 'slug', 'qux' => null],\n+ ['qux' => 'slug'],\n ],\n [\n '/foo/{bar}/baz/{qux:slug?}',\n '/foo/{bar}/baz/{qux?}',\n- ['bar' => null, 'qux' => 'slug'],\n+ ['qux' => 'slug'],\n ],\n [\n '/foo/{bar}/baz/{qux:slug?}/{test:id?}',\n '/foo/{bar}/baz/{qux?}/{test?}',\n- ['bar' => null, 'qux' => 'slug', 'test' => 'id'],\n+ ['qux' => 'slug', 'test' => 'id'],\n ],\n ];\n }",
"filename": "tests/Routing/RouteUriTest.php",
"status": "modified"
},
{
"diff": "@@ -1706,6 +1706,23 @@ public function testParentChildImplicitBindingsWhereOnlySomeParametersAreScoped(\n $this->assertSame('2|another-test-slug|3', $router->dispatch(Request::create('foo/2/another-test-slug/3', 'GET'))->getContent());\n }\n \n+ public function testApiResourceScopingWhenChildDoesNotBelongToParent()\n+ {\n+ ResourceRegistrar::singularParameters();\n+ $router = $this->getRouter();\n+ $router->apiResource(\n+ 'teams.users',\n+ RouteTestNestedResourceControllerWithMissingUser::class,\n+ ['only' => ['show']],\n+ )\n+ ->middleware(SubstituteBindings::class)\n+ ->scoped();\n+\n+ $this->expectException(ModelNotFoundException::class);\n+\n+ $router->dispatch(Request::create('teams/1/users/2', 'GET'));\n+ }\n+\n public function testParentChildImplicitBindingsProperlyCamelCased()\n {\n $router = $this->getRouter();\n@@ -2109,6 +2126,13 @@ public function show(RoutingTestUserModel $fooBar)\n }\n }\n \n+class RouteTestNestedResourceControllerWithMissingUser extends Controller\n+{\n+ public function show(RoutingTestTeamWithoutUserModel $team, RoutingTestUserModel $user)\n+ {\n+ }\n+}\n+\n class RouteTestClosureMiddlewareController extends Controller\n {\n public function __construct()\n@@ -2366,6 +2390,14 @@ public function firstOrFail()\n }\n }\n \n+class RoutingTestTeamWithoutUserModel extends RoutingTestTeamModel\n+{\n+ public function users()\n+ {\n+ throw new ModelNotFoundException();\n+ }\n+}\n+\n class ActionStub\n {\n public function __invoke()",
"filename": "tests/Routing/RoutingRouteTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.12.2\r\n- PHP Version: PHP 8.1.4 (cli) (built: Mar 16 2022 09:33:31) (ZTS Visual C++ 2019 x64)\r\n- Database Driver & Version: MySql 8.0.16\r\n\r\n### Description:\r\n\r\nI have an api POST route with json contents. Very unexpected this route was giving Allowed memory size of 134217728 bytes exhausted (tried to allocate ... bytes) errors.\r\n\r\nTo debug this issue:\r\n\r\n1) I adjusted public/index.php so the request would run to the end and would not be aborted by memory exhausted errors.\r\n\r\n```php\r\nini_set(\"memory_limit\", \"-1\");\r\n```\r\n\r\n2) I attached XDEBUG in profile mode.\r\n\r\n3) I replayed the request.\r\n\r\n4) I used QCacheGrind to visualize the profile:\r\n\r\n\r\n\r\n\r\nAs the profile shows, ```Illuminate\\Http\\Request::createFromBase``` via ```Request->json()``` calls ```json_decode()``` twice. Which is unwanted, because I don't use the ```Request::json()``` to retrieve the json contents. I do my own ```json_decode((string) Request::getContents())```.\r\n\r\nI did some digging in the Laravel History and found the commit introducing the json_decode behaviour in [9.x]: https://github.com/laravel/framework/commit/13e4a7ff1799ee51698faa10161b2d2af889b713 The commit message states: _... This commit solves the underlying issue without breaking compatibility with the original functionality. ..._\r\n\r\n**This commit is breaking compatibility, because it does not take memory consumption into account. Neither does it take performance into account, decoding the same request body twice is performance degradation.** For large JSON (in my case Content-Length: 6428178) this can easily lead to memory exhausted errors. In Laravel 7.x there was no memory exhausted error.\r\n\r\n\r\n\r\n\r\n",
"comments": [
{
"body": "You can remove your `json_decode` and use the decoded data in the request instead, with `$request->all()` for example, to retrieve the whole decoded data, you can also use `->get('key')` to retrieve a specific field in your json, you can even use `->input('root.sub')` to retrieve nested data, so there is no need to do your own json decode\r\n\r\nIf you have to do that, you should do it in your custom request (or create one with you don't use one), by overriding the `->json()` method to ensure that data is not decoded twice and is consistent, but there is no reason to do it in 99% of the cases, the only exception is json_decode flags that you might need\r\n\r\nAnd for the underlying issue, in my testings, json() is called once by createFromBase :\r\n\r\n\r\n\r\n\r\nclean function does seems to do extra calls to json though\r\n",
"created_at": "2022-05-16T15:45:29Z"
},
{
"body": "@ik77 `Request@json` has an if clause to only decode the JSON payload if it was not yet decoded.\r\n\r\nhttps://github.com/laravel/framework/blob/465dbee04c028457e19ccab0452630582a571e9a/src/Illuminate/Http/Request.php#L374-L376\r\n\r\nSo the subsequent calls doesn't call `json_decode` again.\r\n\r\n@MircoBabin the change introduced in https://github.com/laravel/framework/commit/13e4a7ff1799ee51698faa10161b2d2af889b713\r\n\r\nReplaced this call:\r\n\r\nhttps://github.com/laravel/framework/blob/76b3417d3cb902fa421ea16e402cb018bd5fc173/src/Illuminate/Http/Request.php#L435\r\n\r\nBy this:\r\n\r\nhttps://github.com/laravel/framework/blob/465dbee04c028457e19ccab0452630582a571e9a/src/Illuminate/Http/Request.php#L458-L460\r\n\r\nSo, before it called `Request@getInputSource` to fill the request, which in turn already decoded JSON requests on its own, since 2013, as you can see in this commit: https://github.com/laravel/framework/commit/e7f07b940edbae92015ac9096b7ca0409e03f9ee\r\n\r\nhttps://github.com/laravel/framework/blob/465dbee04c028457e19ccab0452630582a571e9a/src/Illuminate/Http/Request.php#L390-L397\r\n\r\n`Request@createFromBase` has been calling `Request@getInputSource`, and by consequence decoding JSON requests, since 2015, introduced by this commit: https://github.com/laravel/framework/commit/9312bec98aa3ea92c657939163386e06d0200dcc\r\n\r\nBottom line: I think it is very unlikely this behavior will be changed by maintainers after so many years.\r\n\r\nYou could take @ik77 suggestions and either use the already decoded data, or if really want to decode it yourself, maybe to use different parameters on `json_decode`, you can:\r\n\r\n- extend the `Illuminate/Http/Request` class\r\n- override its `createFromBase` method and avoid JSON parsing\r\n- Modify your app's `./public/index.php` to use your `Request` subclass\r\n- Bind your subclass to `Illuminate/Http/Request` on your apps' `AppServiceProvider@register` method, this would look something like this:\r\n\r\n~~~php\r\nclass AppServiceProvider extends ServiceProvider\r\n{\r\n public function register()\r\n {\r\n $this->app->bind(\\Illuminate\\Http\\Request::class, \\App\\Http\\Request::class);\r\n }\r\n\r\n public function boot()\r\n {\r\n }\r\n}\r\n~~~\r\n\r\nNote, while `FormRequest`s will still extend the original `Request` class and not your subclass, they are hydrated from the request resolved from the container, which after binding it to the container, will be an instance of your subclass.\r\n\r\nhttps://github.com/laravel/framework/blob/465dbee04c028457e19ccab0452630582a571e9a/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php#L33-L37\r\n\r\nHope this helps you solve your issue.",
"created_at": "2022-05-17T02:37:14Z"
},
{
"body": "@driesvints after doing research to answer @MircoBabin , I noted PR #37921 , which introduced the check if a request is a JSON request before replacing its `$request` property, apparently didn't change anything as `Request@getInputSource` already did that check internally.\r\n\r\nActually the tests (one changed, and one added) on that PR, both passes if one reverts the change made by it.\r\n\r\nI am not sure it makes any change if reverted, as for non-JSON requests `Request@getInputSource` would return the contents of `$request->request` anyways which are already populated on the `Request@duplicate` call some lines above, but it is curious tests passed without the proposed change.\r\n\r\nI have no idea on how to do so, but maybe there is a way to automate to check if any added tests fail before committing a PR's proposed change?\r\n",
"created_at": "2022-05-17T02:44:36Z"
},
{
"body": "Thanks @rodrigopedra.\r\n\r\n@LukeTowers could you weigh in here?",
"created_at": "2022-05-17T07:20:09Z"
},
{
"body": "I have taken @IK77 advice and do not json_decode() myself anymore. Instead i'm using Request::json() now.\r\n\r\nBut still I'm getting memory exhausted because Laravel is **decoding twice**. Here is new the profile:\r\n\r\n\r\n",
"created_at": "2022-05-17T07:55:56Z"
},
{
"body": "@rodrigopedra thanks for you detailed explanation. So it seems I'm wrong concluding https://github.com/laravel/framework/commit/13e4a7ff1799ee51698faa10161b2d2af889b713 was the commit introducing wrong behaviour.\r\n\r\nYour solution to extend the ```Illuminate/Http/Request```, while being a very creative solution, is not really a viable solution. Upon each Laravel update I still would have to compare the ```Request::createFromBase``` with the extended class. \r\n\r\nWalking this path it would be easier to just directly modify the ```Illuminate/Http/Request.php``` source file, what would break with each Laravel update. I could write a test for this, that would fail after update. But I'm not going to take this path, as it is not maintainable in the long run. (Yep against all best practices, I am committing the ```vendor``` directory. Because on shared webhosting you can't ```composer install```, there is no shell. Using DeployHQ ftp deployment with a committed ```vendor``` directory is the easiest solution.)",
"created_at": "2022-05-17T08:14:20Z"
},
{
"body": "To be fair, isn't the real issue that your JSON payloads are simply too large? What kind of payloads are you handling?",
"created_at": "2022-05-17T11:21:51Z"
},
{
"body": "The payloads are order request payloads for renting a touringcar. In the payload also is the calculated Google Maps route present. That together constitutes a lot of bytes.\r\n\r\nThe http-payload is ~7 MB, which is not that big. Json_decoded() it becomes ~69MB, which still is not beyond default PHP limits.\r\n\r\nBut then comes Laravel, deciding to **decode twice** and keeping 2 copies in memory. So claiming 2 times 69MB which is beyond the default PHP limits.",
"created_at": "2022-05-17T12:43:36Z"
},
{
"body": "If you have a solution to this issue that does not break other use cases please PR it. Thank you.",
"created_at": "2022-05-17T15:05:19Z"
},
{
"body": "> after doing research to answer @MircoBabin , I noted PR #37921 , which introduced the check if a request is a JSON request before replacing its `$request` property, apparently didn't change anything as `Request@getInputSource` already did that check internally.\r\n\r\n> I am not sure it makes any change if reverted, as for non-JSON requests Request@getInputSource would return the contents of $request->request anyways which are already populated on the Request@duplicate call some lines above, but it is curious tests passed without the proposed change.\r\n\r\n@rodrigopedra thanks for your detailed response! My change however is absolutely critical, although it might not appear so at first glance which is why the original behaviour was so dangerous. \r\n\r\nThe problem is that the internal `request` property is intended to only hold POST parameters; while `Request@getInputSource` will return GET parameters (the `query` property) if the request method is GET or HEAD. This means that any calls to Laravel's methods asking for POST data on a GET request would return GET data previously (i.e. `Request::post('somevar');` would return the value of `?somevar=bad` on GET requests). The `Request@duplicate` call above does not have this problem because the `request` and `query` parameters are properly separated during the duplication process.\r\n\r\nUltimately there are two things to keep in mind:\r\n1. The `Request->request` property should ONLY ever hold POST data\r\n2. The `Request@getInputSource()` method returns data from different locations depending on the type of request made.\r\n\r\n",
"created_at": "2022-05-17T16:36:13Z"
},
{
"body": "@MircoBabin where is Laravel calling json_decode twice? I'm not seeing it in the source.",
"created_at": "2022-05-17T16:39:06Z"
},
{
"body": "@LukeTowers gotcha. Thanks for the heads up.\r\n\r\nMy misunderstanding was due to `Request@getInputSource` checking if a request wants JSON as its first thing, but by moving the if clause to `Request@createFromBase` you avoid overwriting `$request->request` for non JSON requests.\r\n\r\nStill, I found weird the added test passed if the change is reverted. Maybe is it worth adding another one that fails without the change?\r\n\r\n",
"created_at": "2022-05-17T21:29:25Z"
},
{
"body": "@MircoBabin , I am not familiar with the call trace visualization tool you are using, but comparing the two screenshots you posted, it is not clear to me, in the last one, that `json_decode()` is called twice.\r\n\r\nI apologize in advance if it is a lack of familiarity with the tool. \r\n\r\nOn the other hand, if you can provide a clearer spot where `json_decode()` is called multiple times, it would be helpful to help you out on this.\r\n",
"created_at": "2022-05-17T21:31:39Z"
},
{
"body": "@rodrigopedra I also find it odd that the test passed without the change applied, when I made the PR the test failed without the change.",
"created_at": "2022-05-18T00:14:33Z"
},
{
"body": "@rodrigopedra @LukeTowers I have adjusted ```\\Illuminate\\Http\\Request.php - function json()``` to write logging:\r\n\r\n```php\r\n/**\r\n * Get the JSON payload for the request.\r\n *\r\n * @param string|null $key\r\n * @param mixed $default\r\n *\r\n * @return \\Symfony\\Component\\HttpFoundation\\ParameterBag|mixed\r\n */\r\n public function json($key = null, $default = null)\r\n {\r\n if (!isset($this->json)) {\r\n static $calledCount = 0;\r\n ++$calledCount;\r\n file_put_contents('c:\\\\incoming\\\\out-of-memory.'.$calledCount.'.log', (strval(new \\Exception('\\Illuminate\\Http\\Request.php function json() is called - executing json_decode()'))));\r\n $this->json = new ParameterBag((array) json_decode($this->getContent(), true));\r\n }\r\n\r\n if (is_null($key)) {\r\n return $this->json;\r\n }\r\n\r\n return data_get($this->json->all(), $key, $default);\r\n }\r\n\r\n```\r\n\r\n2 files are written:\r\n\r\n1)\r\n```\r\nException: \\Illuminate\\Http\\Request.php function json() is called - executing json_decode() in D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php:377\r\nStack trace:\r\n#0 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php(462): Illuminate\\Http\\Request->json()\r\n#1 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php(67): Illuminate\\Http\\Request::createFromBase(Object(Symfony\\Component\\HttpFoundation\\Request))\r\n#2 D:\\Projects\\Webpage\\tripportals\\public\\index.php(83): Illuminate\\Http\\Request::capture()\r\n#3 {main}\r\n```\r\n\r\n2)\r\n```\r\nException: \\Illuminate\\Http\\Request.php function json() is called - executing json_decode() in D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php:377\r\nStack trace:\r\n#0 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php(462): Illuminate\\Http\\Request->json()\r\n#1 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\CompiledRouteCollection.php(155): Illuminate\\Http\\Request::createFromBase(Object(Illuminate\\Http\\Request))\r\n#2 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\CompiledRouteCollection.php(114): Illuminate\\Routing\\CompiledRouteCollection->requestWithoutTrailingSlash(Object(Illuminate\\Http\\Request))\r\n#3 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php(680): Illuminate\\Routing\\CompiledRouteCollection->match(Object(Illuminate\\Http\\Request))\r\n#4 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php(667): Illuminate\\Routing\\Router->findRoute(Object(Illuminate\\Http\\Request))\r\n#5 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php(656): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))\r\n#6 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(167): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))\r\n#7 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(141): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))\r\n#8 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#9 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#10 D:\\Projects\\Webpage\\tripportals\\app\\Http\\Middleware\\CheckDatabaseConnections.php(79): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#11 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(180): App\\Http\\Middleware\\CheckDatabaseConnections->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#12 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance.php(86): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#13 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#14 D:\\Projects\\Webpage\\tripportals\\app\\Http\\Middleware\\Cors.php(32): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#15 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(180): App\\Http\\Middleware\\Cors->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#16 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Middleware\\TrustProxies.php(39): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#17 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(180): Illuminate\\Http\\Middleware\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#18 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Middleware\\TrustHosts.php(48): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#19 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(180): Illuminate\\Http\\Middleware\\TrustHosts->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#20 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#21 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(142): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\r\n#22 D:\\Projects\\Webpage\\tripportals\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(111): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\r\n#23 D:\\Projects\\Webpage\\tripportals\\public\\index.php(83): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\r\n#24 {main}\r\n```",
"created_at": "2022-05-18T05:14:31Z"
},
{
"body": "The problem is in ```Illuminate\\Routing\\CompiledRouteCollection.php - function requestWithoutTrailingSlash()```. \r\n\r\n```php\r\n /**\r\n * Get a cloned instance of the given request without any trailing slash on the URI.\r\n *\r\n * @param \\Illuminate\\Http\\Request $request\r\n * @return \\Illuminate\\Http\\Request\r\n */\r\n protected function requestWithoutTrailingSlash(Request $request)\r\n {\r\n $trimmedRequest = Request::createFromBase($request);\r\n\r\n $parts = explode('?', $request->server->get('REQUEST_URI'), 2);\r\n\r\n $trimmedRequest->server->set(\r\n 'REQUEST_URI', rtrim($parts[0], '/').(isset($parts[1]) ? '?'.$parts[1] : '')\r\n );\r\n\r\n return $trimmedRequest;\r\n }\r\n```\r\n\r\n1) it calls ```Request::createFromBase``` with an ```\\Illuminate\\Http\\Request```, which already did a internal ```json()``` and so already contains 69MB.\r\n2) ```Request::createFromBase``` expects a ```Symfony\\Component\\HttpFoundation\\Request```. Because it is unaware of the already decoded json body, it's decoding again. Claiming again 69MB memory.\r\n\r\nAdjusting ```Request::createFromBase``` prevents the double json_decode(). But because the ParameterBag is not really copied/cloned I'm unsure if this is really a valid solution.\r\n\r\n```php\r\n /**\r\n * Create an Illuminate request from a Symfony instance.\r\n *\r\n * @return static\r\n */\r\n public static function createFromBase(SymfonyRequest $request)\r\n {\r\n $newRequest = (new static())->duplicate(\r\n $request->query->all(), $request->request->all(), $request->attributes->all(),\r\n $request->cookies->all(), $request->files->all(), $request->server->all()\r\n );\r\n\r\n $newRequest->headers->replace($request->headers->all());\r\n\r\n $newRequest->content = $request->content;\r\n\r\n if ($newRequest->isJson()) {\r\n if ($request instanceof self) {\r\n $newRequest->request = $request->json();\r\n $newRequest->json = $request->json; // Unsure if this is allowed, because this is a ParameterBag\r\n } else {\r\n $newRequest->request = $newRequest->json();\r\n }\r\n }\r\n\r\n return $newRequest;\r\n }\r\n```",
"created_at": "2022-05-18T06:23:51Z"
},
{
"body": "@MircoBabin can you test changing the first line of `CompiledRouteCollection@requestWithoutTrailingSlash`\r\n\r\nfrom:\r\n\r\n~~~php\r\n$trimmedRequest = Request::createFromBase($request);\r\n~~~\r\n\r\nto:\r\n\r\n~~~php\r\n$trimmedRequest = $request->duplicate();\r\n~~~\r\n\r\nAnd see if it fixes it?\r\n",
"created_at": "2022-05-18T06:41:58Z"
},
{
"body": "@rodrigopedra I can confirm after changing ```function requestWithoutTrailingSlash()```, there is no double json_decode() anymore.",
"created_at": "2022-05-18T06:47:31Z"
},
{
"body": "@MircoBabin I sent PR #42420 to make this change.\r\n\r\nThanks for tracing the spots so we could find where the double encoding happened =)",
"created_at": "2022-05-18T07:09:02Z"
},
{
"body": "@rodrigopedra The PR targets the [8.x] branch. Can it also target the [9.x] branch ? Because that's the version I'm using.\r\n\r\nOr must the PR first be accepted on the [8.x] branch and will then later be targeted at the [9.x] branch and future [10.x] branch ? Sorry for the question, I don't know how the Laravel project is handling patches on multiple versions.",
"created_at": "2022-05-18T07:22:45Z"
},
{
"body": "@MircoBabin all fixes for 8.x are merged upstream to newer versions.",
"created_at": "2022-05-18T07:35:06Z"
},
{
"body": "@MircoBabin as it is a bugfix it should target the 8.x, as this branch is still in bugfix support. \r\n\r\nComplementing what @driesvints said, changes in 8.x are merged into 9.x before each weekly release.",
"created_at": "2022-05-18T07:38:29Z"
},
{
"body": "Thank you very much !",
"created_at": "2022-05-18T07:44:31Z"
},
{
"body": "@MircoBabin excellent work tracking down the issue and great final solution @rodrigopedra! Glad to see the issue resolved with a general win for Laravel performance :) ",
"created_at": "2022-05-18T20:27:40Z"
},
{
"body": "Will be fixed in the next release. Thanks all.",
"created_at": "2022-05-19T07:19:07Z"
}
],
"number": 42403,
"title": "[9.x] memory exhausted because JSON payload is unwanted parsed twice by Illuminate\\Http\\Request::createFromBase"
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nCloses #42403 \r\n\r\nWhen routes are compiled, the `CompiledRouteCollection@requestWithoutTrailingSlash` method uses the static method `Request@createFromBase` to clone a `Illuminate\\Http\\Request`.\r\n\r\nWhen the request is a JSON request, this call causes the request's JSON payload to be parsed twice:\r\n\r\n- first when the request is captured\r\n- and then when `CompiledRouteCollection@requestWithoutTrailingSlash` is called, which, as noticed on issue #42403 , can cause a noticeable increase on memory usage when processing large JSON payloads.\r\n\r\nActually, issue #42403 describes a memory exhaust scenario with default PHP configuration.\r\n\r\nThe doc block on `CompiledRouteCollection@requestWithoutTrailingSlash` states this method `Get a cloned instance of the given request without any trailing slash on the URI`, so as the original `$request` is already a `Illuminate\\Http\\Request`, e.g. it is already bootstrapped, we can safely change this call to use the `Request@duplicate` method, which internally actually clones the request object, avoiding the double `json_encode` parsing.\r\n\r\nThis PR:\r\n\r\n- Changes the method `CompiledRouteCollection@requestWithoutTrailingSlash` to call `Request@duplicate` instead of `Request@captureFromBase`, to clone the current request.\r\n\r\nNotes:\r\n\r\nThis behavior only happens when routes are cached.\r\n\r\nI didn't add any tests, as I would need to mock the `Illuminate\\Http\\Request` and assert its static method `createFromBase` was not called twice.\r\n\r\nI don't know how to properly mock static methods. If someone can guide me on how to do it, I will appreciate.",
"number": 42420,
"review_comments": [],
"title": "[8.x] Use duplicate instead of createFromBase to clone request when routes are cached"
} | {
"commits": [
{
"message": "prefer cloning a Illuminte\\Http\\Request with duplicate instead of createFromBase"
}
],
"files": [
{
"diff": "@@ -152,7 +152,7 @@ public function match(Request $request)\n */\n protected function requestWithoutTrailingSlash(Request $request)\n {\n- $trimmedRequest = Request::createFromBase($request);\n+ $trimmedRequest = $request->duplicate();\n \n $parts = explode('?', $request->server->get('REQUEST_URI'), 2);\n ",
"filename": "src/Illuminate/Routing/CompiledRouteCollection.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.11.0\r\n\r\n### Description:\r\n\r\nMeaning of **digit**: [any one of the ten numbers 0 to 9](https://dictionary.cambridge.org/dictionary/english/digit)\r\n\r\nA dot (```.```) is **not a digit**.\r\n\r\nThe problem is that the validation rule ```digits_between``` accepts fractions (a dot), multiple dots and **even dots only** (```....```). :rofl:\r\n\r\nNote that the validation rule ```digits``` does not accept fractions (that is good) and that makes an inconsistency between these two validation rules.\r\n\r\nPlease, let the digits **stay digits**! In my opinion, [this PR](https://github.com/laravel/framework/pull/40278) should be rolled back.\r\n\r\nI suggest to make a separate **and a valid** validation rule for fractions. Name it ```floats``` and ```floats_between```, or something like that.\r\n\r\nThis is how validation rule ```digits_between``` looks like in [Laravel v9.11.0](https://github.com/illuminate/validation/blob/v9.11.0/Concerns/ValidatesAttributes.php#L578) (look at ```preg_match```):\r\n\r\n```php\r\npublic function validateDigitsBetween($attribute, $value, $parameters)\r\n{\r\n $this->requireParameterCount(2, $parameters, 'digits_between');\r\n\r\n $length = strlen((string) $value);\r\n\r\n return ! preg_match('/[^0-9.]/', $value)\r\n && $length >= $parameters[0] && $length <= $parameters[1];\r\n}\r\n```\r\n\r\nI found that this validation rule looks like that in these versions: v6.20.44, v8.79.0 (and newer, including v9.x.x)\r\n\r\nThis was fun. No hard feelings about my presentation of the issue, I hope. :wink: \r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$data = [\r\n 'pin' => '1234.78',\r\n // 'pin' => '1234..78', // ok, weird\r\n // 'pin' => '....', // OMG\r\n];\r\n\r\n$validator = \\Illuminate\\Support\\Facades\\Validator::make($data, [\r\n 'pin' => 'digits_between:4,8',\r\n]);\r\n\r\nif (!$validator->fails()) {\r\n echo 'These are not the digits you are looking for.';\r\n} else {\r\n echo 'When you see this, the validation rule digits_between is now fixed.';\r\n}\r\n```\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "I don't think we're going to change this any time soon, sorry.",
"created_at": "2022-05-10T08:36:25Z"
},
{
"body": "Also see the original issue for that: https://github.com/laravel/framework/issues/40264. This should be a numeric value. Maybe digit isn't an 100% word but the rule atm does what it's suppose to do.",
"created_at": "2022-05-10T08:38:18Z"
},
{
"body": "Ah the multiple dots thing is a concern. I'll send in a PR for that.",
"created_at": "2022-05-10T08:39:30Z"
},
{
"body": "I sent in a PR for this: https://github.com/laravel/framework/pull/42330",
"created_at": "2022-05-10T09:21:29Z"
},
{
"body": "@driesvints I disagree.\r\n\r\nWhich one is it then – a [digit](https://dictionary.cambridge.org/dictionary/english/digit) or a [numeric](https://www.php.net/manual/en/language.types.numeric-strings.php)?\r\n* In the code there is a [comment](https://github.com/illuminate/validation/blob/v9.11.0/Concerns/ValidatesAttributes.php#L571) for that validation rule: ```Validate that an attribute is between a given number of digits.```\r\n* In the Laravel's [documentation](https://laravel.com/docs/9.x/validation#rule-digits-between) it says ```The field under validation must be numeric and must have a length between the given min and max.```\r\n\r\n\r\nMore arguments:\r\n* Previously there were no unit tests for fractions in unit tests for validation rule ```digits_between``` – I take that as a sign that this validation rule was never made for fractions, only for digits (as the name suggests).\r\n* There is validation rule ```numeric``` – it can be used in combination with validation rules ```string``` and ```between```\r\n* So what if the documentation said *numeric*? The code (and the comment in docblocks \\* ) says it is digits. Documentation is sometimes wrong. A \"digit\" is a term even outside programming.\r\n* So what if the author of the [issue](https://github.com/laravel/framework/issues/40264) was exploiting the validation rule in a way it was not built for?!\r\n* Apparently, the term \"numeric\" [has been used in PHP documentation](https://www.php.net/ctype_digit) when talking about only digits.\r\n* As I understand, the [validation rule was created](https://github.com/illuminate/validation/blob/c81206b301166c1fc34cb4c4afeabd5aee312bdc/Validator.php#L456) very long time ago by @taylorotwell - maybe it would be better to ask him what to do with this validation rule...\r\n\r\n\\* In programming, a [docblock or DocBlock](https://en.wikipedia.org/wiki/Docblock) is a specially formatted comment specified in source code that is used to document a specific segment of code.",
"created_at": "2022-05-10T12:02:44Z"
},
{
"body": "I'm sorry but I'm not going to change my mind over this. Changing this would be a large breaking change for many apps. It's only terminology and it's clearly documented. If you want, you can attempt a PR that adds a rule that does exactly what you want.",
"created_at": "2022-05-10T12:04:36Z"
}
],
"number": 42326,
"title": "Non-digits allowed in digits_between"
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nToday I learned that since PR #40278 the validation rule ```digits_between``` allows the value to contain also a dot (```.```). I think it is wrong, because a dot is not a digit. But what is done, is done…\r\nI discussed it in issue #42326 but I failed to persuade Laravel core member to roll back that PR. Breaking changes must be prevented… At least, I was encouraged to make a PR to achieve my goal, so this is it.\r\n\r\nI created a third parameter for the validation rule ```digits_between``` – the validation style ```strict```. This is a non-breaking feature and, as written in documentation, can be targeted for 9.x branch.\r\n\r\nTo validate by using ```strict``` validation style and ensure that the value contains digits only:\r\n```php\r\n$data = [\r\n 'pin' => '1234',\r\n];\r\n\r\n$validator = \\Illuminate\\Support\\Facades\\Validator::make($data, [\r\n 'pin' => 'digits_between:4,8,strict',\r\n]);\r\n\r\nif ($validator->passes()) {\r\n echo 'Success!';\r\n} else {\r\n echo 'The PIN number must contain 4-8 digits.';\r\n}\r\n```",
"number": 42339,
"review_comments": [],
"title": "Add strict validation style for validation rule digits_between"
} | {
"commits": [
{
"message": "Add strict validation style for validation rule digits_between"
}
],
"files": [
{
"diff": "@@ -579,19 +579,30 @@ public function validateDigitsBetween($attribute, $value, $parameters)\n {\n $this->requireParameterCount(2, $parameters, 'digits_between');\n \n- $length = strlen((string) $value);\n-\n- if (((string) $value) === '.') {\n+ if (! is_numeric($value)) {\n return false;\n }\n \n- // Make sure there is not more than one dot...\n- if (($length - strlen(str_replace('.', '', (string) $value))) > 1) {\n+ if (is_string($value)) {\n+ // value must not be a dot or contain more than single dot\n+ if ($value === '.' || substr_count($value, '.') > 1) {\n+ return false;\n+ }\n+ } else {\n+ $value = strval($value);\n+ }\n+\n+ $length = strlen($value);\n+\n+ if ($length < $parameters[0] || $length > $parameters[1]) {\n return false;\n }\n \n- return ! preg_match('/[^0-9.]/', $value)\n- && $length >= $parameters[0] && $length <= $parameters[1];\n+ if (isset($parameters[2]) && $parameters[2] === 'strict') {\n+ return ! preg_match('/[^0-9]/', $value);\n+ }\n+\n+ return ! preg_match('/[^0-9.]/', $value);\n }\n \n /**",
"filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php",
"status": "modified"
},
{
"diff": "@@ -2361,6 +2361,12 @@ public function testValidateDigits()\n \n $v = new Validator($trans, ['foo' => '2.'], ['foo' => 'digits_between:1,10']);\n $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['foo' => '12345'], ['foo' => 'digits_between:1,10,strict']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['foo' => '12.3'], ['foo' => 'digits_between:1,10,strict']);\n+ $this->assertTrue($v->fails());\n }\n \n public function testValidateSize()",
"filename": "tests/Validation/ValidationValidatorTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.9.0\r\n- PHP Version: 8.1.5\r\n- Database Driver & Version:\r\n\r\n### Description:\r\n`php artisan down --refresh=5` does not work in combination with ` --render=\"maintenance.index\"` \r\n\r\n### Steps To Reproduce:\r\n\r\ncreate a custom `maintenance.index` view\r\n\r\nrun `php artisan down --refresh=5 --render=\"maintenance.index\"`\r\n\r\n#### Expected behavior:\r\n`maintenance.index` view will be rendered and refreshed every 5 seconds\r\n\r\n#### Actual behavior:\r\n`maintenance.index` view will be rendered but **NOT** refreshed every 5 seconds\r\n\r\n\r\nI found this issue on [stackoverflow ](https://stackoverflow.com/questions/72004966/laravel-maintenance-mode-refresh-and-render-parameter)and proposed the below workaround\r\n\r\n### current workaround:\r\n\r\nParsing the `--refresh=5` argument from `$_SERVER['argv']` if available and conditionally add a refresh meta tag in the blade\r\n```template\r\n$result = array_values(preg_grep('/(--refresh)/', array_values( $_SERVER['argv'] ) ));\r\nif(!empty($result)){\r\n $refresh = substr($result[0], strpos($result[0], \"=\") + 1);\r\n}\r\n```\r\n\r\n\r\n```php\r\n@if(isset($refresh))\r\n <meta http-equiv=\"refresh\" content=\"{{$refresh}}\">\r\n@endif\r\n```\r\n",
"comments": [
{
"body": "Thank you for reporting this. I've sent in a fix for this here: https://github.com/laravel/framework/pull/42217",
"created_at": "2022-05-02T09:52:14Z"
},
{
"body": "Will be in next release. Thanks!",
"created_at": "2022-05-02T13:55:27Z"
}
],
"number": 42208,
"title": "`php artisan down --refresh=5` does not work in combination with ` --render=\"maintenance.index\"`"
} | {
"body": "This PR fixes an issue where the Refresh header was not set when an application is down with a specific template. There was a missing header at the bottom of the maintenance file.\n\nFixes #42208\n",
"number": 42217,
"review_comments": [],
"title": "[8.x] Fix refresh during down"
} | {
"commits": [
{
"message": "Fix refresh during down"
}
],
"files": [
{
"diff": "@@ -69,6 +69,10 @@ if (isset($data['retry'])) {\n header('Retry-After: '.$data['retry']);\n }\n \n+if (isset($data['refresh'])) {\n+ header('Refresh: '.$data['refresh']);\n+}\n+\n echo $data['template'];\n \n exit;",
"filename": "src/Illuminate/Foundation/Console/stubs/maintenance-mode.stub",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.10.0\r\n- PHP Version: 8.1.3\r\n- Database Driver & Version: -\r\n\r\n### Description:\r\n\r\nSince the `v9.10.0`, I encounter many issues on a large project. I can only say \"many issues\" for now, because it's \"just\" failling tests here and there that doesn't seem related to each other, even if everything works fine when I roll back to `v9.9.0`. \r\n\r\nI'm still in the process of digging the problem and to figure out why and when it happens.\r\n\r\nHowever, I've determined this commit https://github.com/laravel/framework/commit/05365f8186044af51fc55fb1e2b5b97caaac59e8 (part of `v9.10.0`) is the cause of these problems. If I checkout on it, it still doesn't work, the moment I manually revert the changes in the `middlewareGroup` public function, it works. With this reverted change, `v9.10.0` works fine too.\r\n\r\nIn the previous version, prior to https://github.com/laravel/framework/commit/05365f8186044af51fc55fb1e2b5b97caaac59e8, the entire middleware group was replaced by a new set of middlewares. In the new version, after https://github.com/laravel/framework/commit/05365f8186044af51fc55fb1e2b5b97caaac59e8, only the missing ones are added. At least it's what I understand for now.\r\n\r\nEven if it's a small change, it's a breaking change that should be reverted.\r\n\r\nWhat do you think?\r\n\r\n### Steps To Reproduce:\r\n\r\nNot yet but the change in behaviour is clear enough to be discussed.\r\n",
"comments": [
{
"body": "can confirm this, revert https://github.com/laravel/framework/commit/05365f8186044af51fc55fb1e2b5b97caaac59e8 fix my problem too (https://github.com/laravel/framework/issues/42156)",
"created_at": "2022-04-27T21:36:36Z"
},
{
"body": "This commit was added with #42004",
"created_at": "2022-04-27T23:47:22Z"
},
{
"body": "I am also having the same problem. I was creating middleware group with empty array to tag routes. Framework cannot find middleware group when I run it with this pr(#42004)",
"created_at": "2022-04-28T03:19:04Z"
},
{
"body": "Behavior of the `middlewareGroup` method changed after PR #42004 as it no longer defines a middleware group when the group is an empty array.\r\n\r\nI sent PR #42161 with a proposed fix.",
"created_at": "2022-04-28T06:47:50Z"
},
{
"body": "Thanks all. We'll try to get this fixed asap.",
"created_at": "2022-04-28T07:03:48Z"
},
{
"body": "We got this reverted and will cut a release shortly. Thanks all.",
"created_at": "2022-04-28T13:15:57Z"
}
],
"number": 42159,
"title": "Change in middlewareGroup function behaviour introduces a breaking change in v9.10.0 "
} | {
"body": "<!--\r\nPlease only send a pull request to branches that are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nCloses #42159 \r\n\r\nAfter PR #42004 the behavior of method `Illuminate\\Routing\\Router@middlewareGroup` was slightly changed, as before it would define a middleware group even if the group was empty, e.g. the group had an empty array of middleware.\r\n\r\nAfter the aforementioned PR, a middleware group with an empty array does not actually add a corresponding middleware group to the stack, thus when running a route with that empty middleware group, the dispatcher would try to instantiate a middleware named as the group which will fail, as reported in #42159 .\r\n\r\nThis PR:\r\n\r\n- Adds a new protected method named `ensureMiddlewareGroup`, which will check if a middleware group is defined, and if not will add it.\r\n- Modify the methods: `middlewareGroup`, `prependMiddlewareToGroup` and `pushMiddlewareToGroup` to use the method above\r\n\r\n\r\nTo reproduce the error described in issue #42159 one could use the following steps:\r\n\r\n1. Create a new laravel app\r\n2. Ensure it uses Laravel version 9.10.0\r\n3. Add an empty middleware group to the app's HTTP kernel (for example, named `public`)\r\n4. Define a route that uses the middleware defined as above\r\n5. Access the defined route through the browser\r\n\r\nAfter applying the changes proposed in this PR, the route will work.\r\n",
"number": 42161,
"review_comments": [],
"title": "[9.x] Ensure middleware group exists"
} | {
"commits": [
{
"message": "Ensure middleware group exists"
}
],
"files": [
{
"diff": "@@ -945,6 +945,19 @@ public function getMiddlewareGroups()\n return $this->middlewareGroups;\n }\n \n+ /**\n+ * Ensure a middleware group is defined.\n+ *\n+ * @param string $name\n+ * @return void\n+ */\n+ protected function ensureMiddlewareGroup($name)\n+ {\n+ if (! $this->hasMiddlewareGroup($name)) {\n+ $this->middlewareGroups[$name] = [];\n+ }\n+ }\n+\n /**\n * Register a group of middleware.\n *\n@@ -954,6 +967,8 @@ public function getMiddlewareGroups()\n */\n public function middlewareGroup($name, array $middleware)\n {\n+ $this->ensureMiddlewareGroup($name);\n+\n foreach ($middleware as $m) {\n $this->pushMiddlewareToGroup($name, $m);\n }\n@@ -972,7 +987,9 @@ public function middlewareGroup($name, array $middleware)\n */\n public function prependMiddlewareToGroup($group, $middleware)\n {\n- if (isset($this->middlewareGroups[$group]) && ! in_array($middleware, $this->middlewareGroups[$group])) {\n+ $this->ensureMiddlewareGroup($group);\n+\n+ if (! in_array($middleware, $this->middlewareGroups[$group])) {\n array_unshift($this->middlewareGroups[$group], $middleware);\n }\n \n@@ -990,9 +1007,7 @@ public function prependMiddlewareToGroup($group, $middleware)\n */\n public function pushMiddlewareToGroup($group, $middleware)\n {\n- if (! array_key_exists($group, $this->middlewareGroups)) {\n- $this->middlewareGroups[$group] = [];\n- }\n+ $this->ensureMiddlewareGroup($group);\n \n if (! in_array($middleware, $this->middlewareGroups[$group])) {\n $this->middlewareGroups[$group][] = $middleware;",
"filename": "src/Illuminate/Routing/Router.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "Fix PhpStan\r\n\r\n```\r\nParameter #3 $remember of static method Illuminate\\Auth\\SessionGuard::attemptWhen() expects false, true given.\r\n```",
"number": 41993,
"review_comments": [],
"title": "[9.x] Fix typo in `SessionGuard::attemptWhen` phpdoc"
} | {
"commits": [
{
"message": "[9.x] Fix Php Doc"
}
],
"files": [
{
"diff": "@@ -391,7 +391,7 @@ public function attempt(array $credentials = [], $remember = false)\n *\n * @param array $credentials\n * @param array|callable $callbacks\n- * @param false $remember\n+ * @param bool $remember\n * @return bool\n */\n public function attemptWhen(array $credentials = [], $callbacks = null, $remember = false)",
"filename": "src/Illuminate/Auth/SessionGuard.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.7.0\r\n- PHP Version: 8.1.4\r\n\r\n### Description:\r\n\r\nAccessing a route with // in the path like http://127.0.0.1:8000//hello emits a deprecated notice. \r\n\r\nDeprecated: urldecode(): Passing null to parameter #1 ($string) of type string is deprecated in /workspaces/xxx/vendor/laravel/framework/src/Illuminate/Foundation/resources/server.php on line 6\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n\r\nAdd a route.\r\n```php\r\nRoute::get('/hello', function () {\r\n return 'hello world';\r\n});\r\n```\r\n```bash\r\n> php artisan serve\r\n```\r\nAccess de route with browser.\r\n\r\n**No notice:**\r\n- http://127.0.0.1:8000/\r\n- http://127.0.0.1:8000//\r\n- http://127.0.0.1:8000/hello\r\n- http://127.0.0.1:8000/hello/\r\n- http://127.0.0.1:8000//hello/\r\n\r\n**Deprecated Notice:**\r\n- http://127.0.0.1:8000//hello\r\n\r\nDeprecated: urldecode(): Passing null to parameter #1 ($string) of type string is deprecated in /workspaces/xxx/vendor/laravel/framework/src/Illuminate/Foundation/resources/server.php on line 6\r\n\r\nIt should show the 404 template, without the notice.\r\n",
"comments": [
{
"body": "It's showing the 404 template for me\r\n\r\n<img width=\"1857\" alt=\"Screenshot 2022-04-12 at 08 44 06\" src=\"https://user-images.githubusercontent.com/594614/162897428-e1e70e99-10b4-497b-927e-87644e824c5f.png\">\r\n",
"created_at": "2022-04-12T06:44:21Z"
},
{
"body": "Ah that was the wrong url. I can reproduce this.",
"created_at": "2022-04-12T06:44:49Z"
},
{
"body": "Sent in a fix for this. Thanks!",
"created_at": "2022-04-12T06:59:29Z"
}
],
"number": 41929,
"title": "Deprecated: urldecode(): Passing null to parameter #1 ($string) of type string is deprecated"
} | {
"body": "This PR fixes an issue where an url has an empty path segment and a non-trailing slash ending. When using artisan serve, the urlencode function in `server.php` will receive `null` which isn't valid anymore on PHP 8.1. \nInstead, what we'll do is pass an empty string if that happens. Since the url couldn't be parsed, we give an empty string, which is an url that will definitely not exist (root is `/`) and it will properly show the 404 \npage.\n\nFixes #41929\n",
"number": 41933,
"review_comments": [],
"title": "[9.x] Fix empty paths for server.php"
} | {
"commits": [
{
"message": "Fix empty paths for server.php"
}
],
"files": [
{
"diff": "@@ -3,7 +3,7 @@\n $publicPath = getcwd();\n \n $uri = urldecode(\n- parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)\n+ parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? ''\n );\n \n // This file allows us to emulate Apache's \"mod_rewrite\" functionality from the",
"filename": "src/Illuminate/Foundation/resources/server.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.0\r\n- PHP Version: 8.1\r\n- Database Driver & Version: MySQL\r\n\r\n### Description:\r\nWhen the email address and name are returned from `routeNotificationForMail` in a modal, the RfcComplianceException is thrown. \r\n\r\n public function routeNotificationForMail($notification) \r\n { \r\n \\Log::debug([$this->email => $this->name]); \r\n return [$this->email => $this->name];\r\n }\r\n\r\n\r\n\r\n\r\nLog\r\n\r\n```\r\n[2022-02-09 16:48:36] local.DEBUG: array (\r\n 'karim.naimy@gmail.com' => 'karim',\r\n) \r\n[2022-02-09 16:48:36] local.DEBUG: array (\r\n 'karim.naimy@gmail.com' => 'karim',\r\n) \r\n[2022-02-09 16:48:36] local.ERROR: Email \"karim\" does not comply with addr-spec of RFC 2822. {\"exception\":\"[object] (Symfony\\\\Component\\\\Mime\\\\Exception\\\\RfcComplianceException(code: 0): Email \\\"karim\\\" does not comply with addr-spec of RFC 2822. at /home/karim/www/example-app/vendor/symfony/mime/Address.php:54)\r\n[stacktrace]\r\n#0 /home/karim/www/example-app/vendor/symfony/mime/Address.php(96): Symfony\\\\Component\\\\Mime\\\\Address->__construct()\r\n#1 /home/karim/www/example-app/vendor/symfony/mime/Address.php(115): Symfony\\\\Component\\\\Mime\\\\Address::create()\r\n#2 /home/karim/www/example-app/vendor/symfony/mime/Email.php(528): Symfony\\\\Component\\\\Mime\\\\Address::createArray()\r\n#3 /home/karim/www/example-app/vendor/symfony/mime/Email.php(169): Symfony\\\\Component\\\\Mime\\\\Email->setListAddressHeaderBody()\r\n#4 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Mail/Message.php(211): Symfony\\\\Component\\\\Mime\\\\Email->to()\r\n#5 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Mail/Message.php(105): Illuminate\\\\Mail\\\\Message->addAddresses()\r\n#6 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(163): Illuminate\\\\Mail\\\\Message->to()\r\n#7 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(135): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->addressMessage()\r\n#8 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(80): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->buildMessage()\r\n#9 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(267): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->Illuminate\\\\Notifications\\\\Channels\\\\{closure}()\r\n#10 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(65): Illuminate\\\\Mail\\\\Mailer->send()\r\n#11 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(148): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->send()\r\n#12 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(106): Illuminate\\\\Notifications\\\\NotificationSender->sendToNotifiable()\r\n#13 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php(19): Illuminate\\\\Notifications\\\\NotificationSender->Illuminate\\\\Notifications\\\\{closure}()\r\n#14 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(109): Illuminate\\\\Notifications\\\\NotificationSender->withLocale()\r\n#15 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(79): Illuminate\\\\Notifications\\\\NotificationSender->sendNow()\r\n#16 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(39): Illuminate\\\\Notifications\\\\NotificationSender->send()\r\n#17 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): Illuminate\\\\Notifications\\\\ChannelManager->send()\r\n#18 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Auth/Passwords/CanResetPassword.php(27): App\\\\Models\\\\User->notify()\r\n......\r\n#70 {main}\r\n\"} \r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Changing the return value of `routeNotificationForMail` function in the modal to match the `FROM_STRING_PATTERN `regex in `Symfony\\Component\\Mime\\Address` is working as expected. \r\n\r\n```\r\n// Symfony\\Component\\Mime\\Address\r\nprivate const FROM_STRING_PATTERN = '~(?<displayName>[^<]*)<(?<addrSpec>.*)>[^>]*~'; \r\n```\r\n\r\n //User Modal\r\n public function routeNotificationForMail($notification) \r\n { \r\n return \"$this->name <$this->email>\"; \r\n }\r\n\r\n\r\n",
"created_at": "2022-02-10T10:28:13Z"
},
{
"body": "Thanks for reporting. I've sent in a fix for this: https://github.com/laravel/framework/pull/40921",
"created_at": "2022-02-10T10:29:42Z"
},
{
"body": "Relatedly, in Laravel v9.5.1 I got a `TypeError: \"Illuminate\\Mail\\Message::Illuminate\\Mail\\{closure}(): Argument #1 ($address) must be of type array|string, null given\"` apparently because my $user->name was null (code simplified):\r\n\r\n```\r\nclass User extends Authenticatable\r\n{\r\n use Notifiable;\r\n\r\n public function routeNotificationForMail($notification)\r\n {\r\n return [$this->email => $this->name];\r\n }\r\n}\r\n```",
"created_at": "2022-03-31T05:02:37Z"
},
{
"body": "@jordanade i think that just surfaces a bug in your code. If the name is null then you should just return the email address. ",
"created_at": "2022-03-31T07:09:51Z"
},
{
"body": "@driesvints Nevertheless, an undocumented breaking change in Laravel 9 for a common situation that arises from boilerplate code (in fact right from the docs). Currently ungoogleable so I'm sure me posting the error message above will help others.",
"created_at": "2022-04-01T23:54:35Z"
},
{
"body": "@jordanade please post the entire stack trace of your error with the correct call lines.",
"created_at": "2022-04-04T10:38:11Z"
},
{
"body": "Sure, here is one of them @driesvints \r\n```\r\nTypeError: Illuminate\\Mail\\Message::Illuminate\\Mail\\{closure}(): Argument #1 ($address) must be of type array|string, null given\r\n#88 /vendor/laravel/framework/src/Illuminate/Mail/Message.php(223): Illuminate\\Mail\\Message::Illuminate\\Mail\\{closure}\r\n#87 [internal](0): array_map\r\n#86 /vendor/laravel/framework/src/Illuminate/Collections/Collection.php(721): Illuminate\\Support\\Collection::map\r\n#85 /vendor/laravel/framework/src/Illuminate/Mail/Message.php(233): Illuminate\\Mail\\Message::addAddresses\r\n#84 /vendor/laravel/framework/src/Illuminate/Mail/Message.php(105): Illuminate\\Mail\\Message::to\r\n#83 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(177): Illuminate\\Notifications\\Channels\\MailChannel::addressMessage\r\n#82 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(137): Illuminate\\Notifications\\Channels\\MailChannel::buildMessage\r\n#81 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(82): Illuminate\\Notifications\\Channels\\MailChannel::Illuminate\\Notifications\\Channels\\{closure}\r\n#80 /vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(267): Illuminate\\Mail\\Mailer::send\r\n#79 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(67): Illuminate\\Notifications\\Channels\\MailChannel::send\r\n#78 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(148): Illuminate\\Notifications\\NotificationSender::sendToNotifiable\r\n#77 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(106): Illuminate\\Notifications\\NotificationSender::Illuminate\\Notifications\\{closure}\r\n#76 /vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php(19): Illuminate\\Notifications\\NotificationSender::withLocale\r\n#75 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(109): Illuminate\\Notifications\\NotificationSender::sendNow\r\n#74 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(79): Illuminate\\Notifications\\NotificationSender::send\r\n#73 /vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(39): Illuminate\\Notifications\\ChannelManager::send\r\n#72 /vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): App\\User::notify\r\n#71 /app/Listeners/UserEventSubscriber.php(19): App\\Listeners\\UserEventSubscriber::handleUserAssignedRole\r\n#70 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(441): Illuminate\\Events\\Dispatcher::Illuminate\\Events\\{closure}\r\n#69 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(249): Illuminate\\Events\\Dispatcher::dispatch\r\n#68 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(206): Illuminate\\Database\\Eloquent\\Model::fireCustomModelEvent\r\n#67 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(181): Illuminate\\Database\\Eloquent\\Model::fireModelEvent\r\n#66 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1176): Illuminate\\Database\\Eloquent\\Model::performInsert\r\n#65 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(996): Illuminate\\Database\\Eloquent\\Model::save\r\n#64 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(531): Illuminate\\Database\\Eloquent\\Builder::Illuminate\\Database\\Eloquent\\{closure}\r\n#63 /vendor/laravel/framework/src/Illuminate/Support/helpers.php(302): tap\r\n#62 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(532): Illuminate\\Database\\Eloquent\\Builder::firstOrCreate\r\n#61 /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php(23): Illuminate\\Database\\Eloquent\\Model::forwardCallTo\r\n#60 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2133): Illuminate\\Database\\Eloquent\\Model::__call\r\n#59 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2145): Illuminate\\Database\\Eloquent\\Model::__callStatic\r\n#58 /app/User.php(76): App\\User::assignRole\r\n#57 /app/Site.php(104): App\\Site::assignUserWithRole\r\n#56 /app/Http/Controllers/SiteUserController.php(39): App\\Http\\Controllers\\SiteUserController::store\r\n#55 /vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): Illuminate\\Routing\\Controller::callAction\r\n#54 /vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\ControllerDispatcher::dispatch\r\n#53 /vendor/laravel/framework/src/Illuminate/Routing/Route.php(261): Illuminate\\Routing\\Route::runController\r\n#52 /vendor/laravel/framework/src/Illuminate/Routing/Route.php(204): Illuminate\\Routing\\Route::run\r\n#51 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(725): Illuminate\\Routing\\Router::Illuminate\\Routing\\{closure}\r\n#50 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#49 /app/Http/Middleware/PageRequestInjector.php(33): App\\Http\\Middleware\\PageRequestInjector::handle\r\n#48 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#47 /vendor/spatie/laravel-referer/src/CaptureReferer.php(21): Spatie\\Referer\\CaptureReferer::handle\r\n#46 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#45 /vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\Routing\\Middleware\\SubstituteBindings::handle\r\n#44 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#43 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(78): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken::handle\r\n#42 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#41 /vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\View\\Middleware\\ShareErrorsFromSession::handle\r\n#40 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#39 /vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(121): Illuminate\\Session\\Middleware\\StartSession::handleStatefulRequest\r\n#38 /vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(64): Illuminate\\Session\\Middleware\\StartSession::handle\r\n#37 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#36 /vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse::handle\r\n#35 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#34 /vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(67): Illuminate\\Cookie\\Middleware\\EncryptCookies::handle\r\n#33 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#32 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline::then\r\n#31 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(727): Illuminate\\Routing\\Router::runRouteWithinStack\r\n#30 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(702): Illuminate\\Routing\\Router::runRoute\r\n#29 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(666): Illuminate\\Routing\\Router::dispatchToRoute\r\n#28 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(655): Illuminate\\Routing\\Router::dispatch\r\n#27 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(167): Illuminate\\Foundation\\Http\\Kernel::Illuminate\\Foundation\\Http\\{closure}\r\n#26 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#25 /vendor/sentry/sentry-laravel/src/Sentry/Laravel/Http/SetRequestIpMiddleware.php(45): Sentry\\Laravel\\Http\\SetRequestIpMiddleware::handle\r\n#24 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#23 /vendor/sentry/sentry-laravel/src/Sentry/Laravel/Http/SetRequestMiddleware.php(42): Sentry\\Laravel\\Http\\SetRequestMiddleware::handle\r\n#22 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#21 /vendor/livewire/livewire/src/DisableBrowserCache.php(19): Livewire\\DisableBrowserCache::handle\r\n#20 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#19 /vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php(60): Barryvdh\\Debugbar\\Middleware\\InjectDebugbar::handle\r\n#18 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#17 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest::handle\r\n#16 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::handle\r\n#15 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#14 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest::handle\r\n#13 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\\Foundation\\Http\\Middleware\\TrimStrings::handle\r\n#12 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#11 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::handle\r\n#10 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#9 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance::handle\r\n#8 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#7 /vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php(39): Illuminate\\Http\\Middleware\\TrustProxies::handle\r\n#6 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#5 /vendor/sentry/sentry-laravel/src/Sentry/Laravel/Tracing/Middleware.php(53): Sentry\\Laravel\\Tracing\\Middleware::handle\r\n#4 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#3 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline::then\r\n#2 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(142): Illuminate\\Foundation\\Http\\Kernel::sendRequestThroughRouter\r\n#1 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(111): Illuminate\\Foundation\\Http\\Kernel::handle\r\n#0 /public/index.php(53): null\r\n```",
"created_at": "2022-04-06T09:06:22Z"
},
{
"body": "Heya, I tried to provide a fix through https://github.com/laravel/framework/pull/41870. Still, this will not notify you of the fact that no name was provided. It's best that you also add a check in userland.",
"created_at": "2022-04-07T13:11:03Z"
}
],
"number": 40895,
"title": "Email Notification Customizing The Recipient Bug in Laravel9"
} | {
"body": "This PR fixes an issue where a user may have defined a null name for their address/email key/value combination. Technically this is a userland issue but since this was handled gracefully before we should do this as well in Laravel v9.\r\n\r\nSee #40895\r\n",
"number": 41870,
"review_comments": [],
"title": "[9.x] Fix null name for email address"
} | {
"commits": [
{
"message": "Fix null name"
}
],
"files": [
{
"diff": "@@ -220,7 +220,7 @@ protected function addAddresses($address, $name, $type)\n if (is_array($address)) {\n $type = lcfirst($type);\n \n- $addresses = collect($address)->map(function (string|array $address, $key) {\n+ $addresses = collect($address)->map(function ($address, $key) {\n if (is_string($key) && is_string($address)) {\n return new Address($key, $address);\n }\n@@ -229,6 +229,10 @@ protected function addAddresses($address, $name, $type)\n return new Address($address['email'] ?? $address['address'], $address['name'] ?? null);\n }\n \n+ if (is_null($address)) {\n+ return new Address($key);\n+ }\n+\n return $address;\n })->all();\n ",
"filename": "src/Illuminate/Mail/Message.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: v8.21.0\r\n- PHP Version: 7.4.11\r\n- Database Driver & Version: psql (PostgreSQL) 12.4 (Ubuntu 12.4-1.pgdg20.04+1) - It doesn't depend on DB driver.\r\n\r\n### Description:\r\n\r\n`DB::afterCommit` callbacks aren't run when `RefreshDatabase` trait is used because `ManagesTransactions` trait only commits when all transactions are executed, but `RefreshDatabase` uses a transaction. Then the callbacks aren't called.\r\n\r\n### Steps To Reproduce:\r\n\r\nI've created a reproduction repo: https://github.com/mariomka/laravel-after-commit-repro\r\n\r\nThere are two tests, one with `RefreshDatabase` (it fails) and one without `RefreshDatabase` (it passes): https://github.com/mariomka/laravel-after-commit-repro/tree/master/tests\r\n\r\nBoth tests run the same \"action\": https://github.com/mariomka/laravel-after-commit-repro/blob/master/app/AfterCommitAction.php\r\n\r\nStep by step reproduction:\r\n\r\n```sh\r\ngit clone git@github.com:mariomka/laravel-after-commit-repro.git\r\ncd laravel-after-commit-repro\r\ncp .env.example .env\r\ncomposer install\r\nphp vendor/bin/homestead make\r\n# Enable postgresql in Homestead.yaml\r\nvagrant up\r\nvagrant ssh\r\ncd code\r\nphp vendor/bin/phpunit\r\n```",
"comments": [
{
"body": "I've installed your repo locally and both tests pass for me. Can you first please try one of the support channels below? If you can actually identify this as a bug, feel free to report back and I'll gladly help you out and re-open this issue.\r\n\r\n- [Laracasts Forums](https://laracasts.com/discuss)\r\n- [Laravel.io Forums](https://laravel.io/forum)\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/laravel)\r\n- [Discord](https://discordapp.com/invite/KxwQuKb)\r\n- [Larachat](https://larachat.co)\r\n- [IRC](https://webchat.freenode.net/?nick=laravelnewbie&channels=%23laravel&prompt=1)\r\n\r\nThanks!",
"created_at": "2021-01-12T10:20:35Z"
},
{
"body": "@driesvints have you used MySQL or Postgres driver? with SQLite runs because I think it doesn't run transactions",
"created_at": "2021-01-12T10:26:14Z"
},
{
"body": "Ah, you said:\r\n\r\n> It doesn't depend on DB driver.\r\n\r\nSo I tried with SQLite indeed. \r\n\r\nBut still, can you maybe try a support channel first? `DB::afterCommit` isn't documented atm and I suspect it might just be a misplacement. I'm not 100% sure myself.",
"created_at": "2021-01-12T10:28:53Z"
},
{
"body": "@driesvints I'm Sorry, I didn't think about SQLite.\r\n\r\nI'm sure that this is not intended behavior, it works perfectly outside the tests. The issue only occurs in tests.\r\n\r\nCheckout this fragment: https://github.com/laravel/framework/blob/374e9565b2718c549f329af5c137e84a7d753a28/src/Illuminate/Database/Concerns/ManagesTransactions.php#L43\r\n\r\n\r\n\r\nIt only commits when there is only one transaction, if I run the action directly without tests it runs because there is only one transaction but for testing, I need to use `RefreshDatabase` and it uses a transaction.\r\n\r\nThere is the line where `DatabaseTransactionsManager` runs callbacks when a transaction is committed: https://github.com/laravel/framework/blob/374e9565b2718c549f329af5c137e84a7d753a28/src/Illuminate/Database/DatabaseTransactionsManager.php#L59",
"created_at": "2021-01-12T10:44:15Z"
},
{
"body": "@mariomka can you maybe try a support channel first? If you can confirm the bug feel free to report back.",
"created_at": "2021-01-12T13:34:15Z"
},
{
"body": "> But still, can you maybe try a support channel first? `DB::afterCommit` isn't documented atm and I suspect it might just be a misplacement. I'm not 100% sure myself.\r\n\r\n@driesvints Thank you for your time but I don't know what you want me to ask the community. Seeing some comments on #35373 (https://github.com/laravel/framework/pull/35373#issuecomment-734333318, https://github.com/laravel/framework/pull/35373#issuecomment-734396793, https://github.com/laravel/framework/pull/35373#issuecomment-734730916) `DB::afterCommit` should be inside a transaction, then when the transaction is committed callback is called. In fact, it works fine. However, it is untestable when the test needs the RefreshDatabase trait (common when you are using a DB in tests).\r\n",
"created_at": "2021-01-12T14:14:16Z"
},
{
"body": "Hi,\r\n\r\nI've got the same issue. I've just discovered `$afterCommit`, applied it to one of my observers and now the related tests fail, because yeah, the database transaction is never committed as a result (using a MySQL instance to run my tests too, not SQLite). I guess we'd need a way to ignore `$afterCommit` in the context of a test suite",
"created_at": "2021-05-11T10:21:44Z"
},
{
"body": "> I guess we'd need a way to ignore `$afterCommit` in the context of a test suite\r\n\r\nThis feels wrong, then you do not know whether something was supposed to be done or not?",
"created_at": "2021-05-11T19:34:53Z"
},
{
"body": "> This feels wrong, then you do not know whether something was supposed to be done or not?\r\n\r\nNot entirely sure what you mean, but since `$afterCommit = true` needs all transactions to be committed, but Laravel won’t let said transactions get committed in the context of a test suite using MySQL, the only way to test whether what’s supposed to happen once they are committed does happen, would seem to be able to ignore `$afterCommit = true` in the context of the test suite, somehow.",
"created_at": "2021-05-11T20:49:20Z"
},
{
"body": "Wait.\r\n\r\nDoesn't it support nested transactions?\r\n\r\nApologies, because I use https://github.com/fntneves/laravel-transactional-events and the transaction opened via the trait (to wrap a test in transactions) does not count as influencing \"transactionable ware\" code triggered in _nested_ transactions.\r\n\r\n(btw I use this together with Postgres with great success).\r\n\r\nIt would be irritating to me to test a part of an application, which makes use of such a feature and then not knowing whether it was _supposed_ to be executed or not just because the test is wrapped in a transaction. 🤔",
"created_at": "2021-05-12T06:29:45Z"
},
{
"body": "@mariomka I have the same issue when using `DB::transaction()`, but not when handling the transaction manually with `DB::beginTransaction()` and `DB::commit()`. Do you have the answer for this?",
"created_at": "2021-05-13T06:08:01Z"
},
{
"body": "anyone find a solution for this? i am trying to test a job that creates some models in an DB transaction... and i am trying to test that some jobs are dispatched in the model observer... we are using afterCommit = true in the observer... and they are not being fired",
"created_at": "2022-03-08T16:34:04Z"
},
{
"body": "@simonmaass \r\n\r\nI just found this thread, and I didn't see an answer either. I went ahead and solved it myself. For everyone else coming here in the future, here's how I resolved this issue.\r\n\r\nThe way Laravel handles the \"after commit\" functionality is by the new `DatabaseTransactionsManager` introduced in Laravel 8.x. All forms of \"after commit\" logic funnel into the `addCallback` method:\r\n\r\n```php\r\npublic function addCallback($callback)\r\n{\r\n if ($current = $this->transactions->last()) {\r\n return $current->addCallback($callback);\r\n }\r\n\r\n call_user_func($callback);\r\n}\r\n```\r\n\r\nAs seen above, if the connection currently has a transaction, all of the callbacks are bound to the ending of that transaction (which in the case of testing, has the scenario where it may never commit).\r\n\r\nI overrode the `DatabaseTransactionsManager` like so:\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App\\Providers;\r\n\r\nuse App\\Testing\\DatabaseTransactionsManager;\r\nuse Illuminate\\Support\\ServiceProvider;\r\n\r\nclass TestServiceProvider extends ServiceProvider\r\n{\r\n /**\r\n * Register the service provider.\r\n *\r\n * @return void\r\n */\r\n public function register()\r\n {\r\n if (! $this->app->runningUnitTests()) {\r\n return;\r\n }\r\n\r\n $this->registerDatabaseTransactionsManager();\r\n }\r\n\r\n /**\r\n * Registers the database transaction manager.\r\n */\r\n protected function registerDatabaseTransactionsManager()\r\n {\r\n // Our automated tests wrap everything inside of a database\r\n // transactions, which means the \"afterCommit\" behavior\r\n // is never invoked. We'll need to tweak this a bit.\r\n\r\n $this->app->singleton('db.transactions', function () {\r\n return new DatabaseTransactionsManager;\r\n });\r\n }\r\n}\r\n```\r\n\r\nThis binds my own `DatabaseTransactionsManager` in place of the original one. Here's what that looks like:\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App\\Testing;\r\n\r\nuse Illuminate\\Database\\DatabaseTransactionsManager as Manager;\r\n\r\nclass DatabaseTransactionsManager extends Manager\r\n{\r\n /**\r\n * The baseline transaction depth.\r\n */\r\n protected $baselineDepth = 0;\r\n\r\n /**\r\n * Register a transaction callback.\r\n *\r\n * @param callable $callback\r\n *\r\n * @return void\r\n */\r\n public function addCallback($callback)\r\n {\r\n if ($this->transactions->count() > $this->baselineDepth) {\r\n return parent::addCallback($callback);\r\n }\r\n\r\n call_user_func($callback);\r\n }\r\n\r\n /**\r\n * Updates the baseline transaction depth to the current transaction depth.\r\n *\r\n * @return $this\r\n */\r\n public function captureTransactionDepth()\r\n {\r\n $this->baselineDepth = $this->transactions->count();\r\n\r\n return $this;\r\n }\r\n}\r\n```\r\n\r\nThe new manager allows you to capture a \"baseline depth\", of which, upon reaching it, all callbacks are immediately fired, rather than deferred to a transaction committal.\r\n\r\nNow you just need to capture the transaction depth in the correct place, which can be done inside of your test:\r\n```php\r\npublic function setUp(): void\r\n{\r\n parent::setUp();\r\n\r\n $this->app->make('db.transactions')->captureTransactionDepth();\r\n}\r\n```\r\n\r\nAnd with that all in place, any \"after commit\" calls on top of the refresh transactions will be called immediately. If you have a transaction _within_ your test, the callback will be deferred until the end of that specific transaction, but will still be called at some point in your test.",
"created_at": "2022-03-08T22:07:24Z"
},
{
"body": "@tylernathanreed your solution only work if only one transaction is perform in your application code. I implemented your solution, and with following code in my controller :\r\n\r\n```php\r\n DB::transaction(function () {\r\n DB::afterCommit(function () { dump('This is executed'); });\r\n });\r\n DB::transaction(function () {});\r\n DB::transaction(function () {});\r\n DB::transaction(function () {\r\n DB::afterCommit(function () { dd('This is not'); });\r\n });\r\n```\r\n\r\nit doesn't dd()\r\n\r\nBecause, each time you start a transaction with `DB::transaction(function () {});` it increment the `$this->transactions->count()`.\r\nBut, there is no code that can decrement it. Transaction cleaning is done when calling `commit()` on the DatabaseTransactionsManager which is only called when the very first level transaction is committed. (Check code here : https://github.com/laravel/framework/blob/b9203fca96960ef9cd8860cb4ec99d1279353a8d/src/Illuminate/Database/Concerns/ManagesTransactions.php#L48-L52) (That transaction in our concerns would be the one that hold the database refresh. or here https://github.com/laravel/framework/blob/b9203fca96960ef9cd8860cb4ec99d1279353a8d/src/Illuminate/Database/Concerns/ManagesTransactions.php#L194-L198",
"created_at": "2022-03-09T15:11:20Z"
},
{
"body": "@driesvints Can you reconsider re-opening this issue ? It looks we are several people (including me) experiencing this issue with non-sqlite db driver.",
"created_at": "2022-03-09T15:15:08Z"
},
{
"body": "Sure. Appreciating PR's to solve this.",
"created_at": "2022-03-14T16:06:52Z"
},
{
"body": "@driesvints could you please also re-open this issue?",
"created_at": "2022-03-14T17:12:03Z"
},
{
"body": "+1 subscribing for the solution.\r\n\r\nFor now this workaround works:\r\n```\r\npublic bool $afterCommit = true;\r\n\r\npublic function __construct()\r\n{\r\n if (app()->runningUnitTests()) {\r\n $this->afterCommit = false;\r\n }\r\n}\r\n```",
"created_at": "2022-03-28T19:22:16Z"
},
{
"body": "Potential fix https://github.com/laravel/framework/pull/41782\r\n\r\nWould appreciate feedback / testing.\r\n\r\nOf course, the other fix / existing work around is to use the `DatabaseMigrations` trait instead of `RefreshDatabase` for your test cases that test things using `afterCommit`.",
"created_at": "2022-04-01T19:00:03Z"
},
{
"body": "Personally I very much appreciate everything @taylorotwell and his team are doing on managing a free framework that makes our life easier.\r\n@driesvints is making an excellent job at handling the laravel repos.\r\nI totally agree that the issues isn't a forum and is reserved specifically to framework bugs reporting, and issues that are usage questions, or asking for help with something should be closed and the author should try the forum ...\r\nBut when it comes to issues that are not usage questions, but issues that seem to be an issue shouldn't be closed as fast as it currently happens, because it could be a real bug, closing the issue very fast will not let it be visible and no one will attempt to fix it.\r\nHaving an open issue that we are not 100% sure is a bug and allow the community to see it, discuss and come up with a solution is better then closing it right away.\r\nMaybe when an issue that is not a confirmed bug could be labeled and after some period let's say 20 days if no one showed an interest in that particular issue, then it could be closed. Maybe also you can use a bot to do that.\r\nI hope you will take this into consideration.\r\nHope all the best for you guys.\r\n",
"created_at": "2022-04-04T10:06:44Z"
},
{
"body": "I truly appreciate the kind words @shadoWalker89 but we're not going to change the way we work, sorry.",
"created_at": "2022-04-04T13:14:36Z"
},
{
"body": "Hey @driesvints I just ran into this `DB::afterCommit` callback testing bug in 8.x for one of my projects. (8.x is also the version in which the bug was reported.) When Taylor fixed it, he sent it to 9.x in Apr 2022 a few months before the bug support policy ran out for 8.x. Could we get the fix in #41782 backported? I can send in a PR, but I worry about it getting closed.",
"created_at": "2022-10-04T14:53:38Z"
},
{
"body": "I'm sorry @BrandonSurowiec but 8.x is closed for bug fixes. You should upgrade as soon as you can.",
"created_at": "2022-10-04T14:55:47Z"
}
],
"number": 35857,
"title": "`DB::afterCommit` callbacks aren't run in tests when `RefreshDatabase` trait is used"
} | {
"body": "Previously, using the `RefreshDatabase` trait was fundamentally incompatible with `afterCommit`. This is because the trait is based around the fact that it opens a transaction and rolls it back at the end of the test, never committing it. \r\n\r\nThis slight modification updates the `DatabaseTransactionManager` to \"ignore\" a given transaction when determining if a callback should be executed, since we want the outer transaction to essentially be invisible.\r\n\r\nWould appreciate some feedback on if this solves people's problems and / or creates new problems.\r\n\r\nFix #35857 ",
"number": 41782,
"review_comments": [],
"title": "[9.x] Fix afterCommit and RefreshDatabase"
} | {
"commits": [
{
"message": "fix afterCommit and refreshDatabase"
},
{
"message": "additional work"
},
{
"message": "method extraction"
}
],
"files": [
{
"diff": "@@ -47,7 +47,7 @@ public function transaction(Closure $callback, $attempts = 1)\n \n $this->transactions = max(0, $this->transactions - 1);\n \n- if ($this->transactions == 0) {\n+ if ($this->afterCommitCallbacksShouldBeExecuted()) {\n $this->transactionsManager?->commit($this->getName());\n }\n } catch (Throwable $e) {\n@@ -193,13 +193,25 @@ public function commit()\n \n $this->transactions = max(0, $this->transactions - 1);\n \n- if ($this->transactions == 0) {\n+ if ($this->afterCommitCallbacksShouldBeExecuted()) {\n $this->transactionsManager?->commit($this->getName());\n }\n \n $this->fireConnectionEvent('committed');\n }\n \n+ /**\n+ * Determine if after commit callbacks should be executed.\n+ *\n+ * @return bool\n+ */\n+ protected function afterCommitCallbacksShouldBeExecuted()\n+ {\n+ return $this->transactions == 0 ||\n+ ($this->transactionsManager &&\n+ $this->transactionsManager->callbackApplicableTransactions()->count() === 1);\n+ }\n+\n /**\n * Handle an exception encountered when committing a transaction.\n *",
"filename": "src/Illuminate/Database/Concerns/ManagesTransactions.php",
"status": "modified"
},
{
"diff": "@@ -11,6 +11,13 @@ class DatabaseTransactionsManager\n */\n protected $transactions;\n \n+ /**\n+ * The database transaction that should be ignored by callbacks.\n+ *\n+ * @var \\Illuminate\\Database\\DatabaseTransactionRecord\n+ */\n+ protected $callbacksShouldIgnore;\n+\n /**\n * Create a new database transactions manager instance.\n *\n@@ -47,6 +54,10 @@ public function rollback($connection, $level)\n $this->transactions = $this->transactions->reject(\n fn ($transaction) => $transaction->connection == $connection && $transaction->level > $level\n )->values();\n+\n+ if ($this->transactions->isEmpty()) {\n+ $this->callbacksShouldIgnore = null;\n+ }\n }\n \n /**\n@@ -64,6 +75,10 @@ public function commit($connection)\n $this->transactions = $forOtherConnections->values();\n \n $forThisConnection->map->executeCallbacks();\n+\n+ if ($this->transactions->isEmpty()) {\n+ $this->callbacksShouldIgnore = null;\n+ }\n }\n \n /**\n@@ -74,13 +89,38 @@ public function commit($connection)\n */\n public function addCallback($callback)\n {\n- if ($current = $this->transactions->last()) {\n+ if ($current = $this->callbackApplicableTransactions()->last()) {\n return $current->addCallback($callback);\n }\n \n $callback();\n }\n \n+ /**\n+ * Specify that callbacks should ignore the given transaction when determining if they should be executed.\n+ *\n+ * @param \\Illuminate\\Database\\DatabaseTransactionRecord $transaction\n+ * @return $this\n+ */\n+ public function callbacksShouldIgnore(DatabaseTransactionRecord $transaction)\n+ {\n+ $this->callbacksShouldIgnore = $transaction;\n+\n+ return $this;\n+ }\n+\n+ /**\n+ * Get the transactions that are applicable to callbacks.\n+ *\n+ * @return \\Illuminate\\Support\\Collection\n+ */\n+ public function callbackApplicableTransactions()\n+ {\n+ return $this->transactions->reject(function ($transaction) {\n+ return $transaction === $this->callbacksShouldIgnore;\n+ })->values();\n+ }\n+\n /**\n * Get all the transactions.\n *",
"filename": "src/Illuminate/Database/DatabaseTransactionsManager.php",
"status": "modified"
},
{
"diff": "@@ -93,6 +93,12 @@ public function beginDatabaseTransaction()\n $connection->unsetEventDispatcher();\n $connection->beginTransaction();\n $connection->setEventDispatcher($dispatcher);\n+\n+ if ($this->app->resolved('db.transactions')) {\n+ $this->app->make('db.transactions')->callbacksShouldIgnore(\n+ $this->app->make('db.transactions')->getTransactions()->first()\n+ );\n+ }\n }\n \n $this->beforeApplicationDestroyed(function () use ($database) {",
"filename": "src/Illuminate/Foundation/Testing/RefreshDatabase.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.4.1\r\n- PHP Version: 8.1.3\r\n- Database Driver & Version: postgres\r\n\r\n### Description:\r\nWe have two schemas in our app. During update to laravel 9 we updated postgress config. `schema` was replaced with `search_path` with value `schemaA,schemaB`\r\nCommand db:wipe clears all tables in both schemas except migrations table in second schema. We have to call this command twice to clear DB\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Please post your `database.php` file.\r\n\r\n@cbj4074 since you worked on this: do you have any idea here?",
"created_at": "2022-03-15T08:18:34Z"
},
{
"body": "`database.php`:\r\n\r\n```\r\n<?php\r\n\r\nreturn [\r\n 'default' => env('DB_CONNECTION', 'pgsql'),\r\n\r\n 'connections' => [\r\n 'pgsql' => [\r\n 'driver' => 'pgbouncer',\r\n 'host' => env('DB_HOST', '...'),\r\n 'port' => env('DB_PORT', '...'),\r\n 'database' => env('DB_DATABASE', '...'),\r\n 'username' => env('DB_USERNAME', '...'),\r\n 'password' => env('DB_PASSWORD', ''),\r\n 'charset' => 'utf8',\r\n 'prefix' => '',\r\n 'search_path' => 'public,common',\r\n 'sslmode' => 'prefer',\r\n 'options' => [\r\n PDO::ATTR_EMULATE_PREPARES => true,\r\n ],\r\n ],\r\n ],\r\n\r\n 'migrations' => 'migrations',\r\n];\r\n\r\n```",
"created_at": "2022-03-15T08:22:12Z"
},
{
"body": "Does it work if you try `'search_path' => '\"public\",\"common\"',`?",
"created_at": "2022-03-15T08:26:37Z"
},
{
"body": "No, one migrations table is left after wipe:\r\n<img width=\"256\" alt=\"image\" src=\"https://user-images.githubusercontent.com/6592868/158336901-7e505543-6f47-4ed0-b565-7f9e248effa5.png\">\r\n",
"created_at": "2022-03-15T08:29:26Z"
},
{
"body": "And this definitely worked in Laravel 8?",
"created_at": "2022-03-15T08:49:34Z"
},
{
"body": "No, it didn't work in Laravel 8 at all. The second schema was ignored by wipe. We used to call `db:wipe` twice with different connections (for each schema).\r\nWhen we switched to `search_path` it started to work much better - all tables in all schemas were removed, except migrations in the second schema",
"created_at": "2022-03-15T09:00:16Z"
},
{
"body": "I see. Thanks for that info. I currently do not now how to solve this one.",
"created_at": "2022-03-15T09:38:27Z"
},
{
"body": "Absolutely; I'm happy to take a look at this, but it will probably be later today or tomorrow.",
"created_at": "2022-03-15T12:22:23Z"
},
{
"body": "Maybe in this [line](https://github.com/laravel/framework/blob/650ca875d3bd7e876ed89f803c705d5d6c121d90/src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php#L275) drop table should be with a schema name? Something like: `drop table schemaA.tableName cascade;`",
"created_at": "2022-03-16T08:17:11Z"
},
{
"body": "Finally getting a chance to dig into this in earnest...\r\n\r\nAs is the case with all things `search_path`-related, the fix is likely to be nuanced and will have to be vetted carefully so as not to break anything else, as not all of the affected code has test coverage (particularly the older code).\r\n\r\nIt doesn't look like I've touched any of the `db:wipe`-related functionality to date (only `schema:dump`), but my hunch is that the fix here will be similar.\r\n\r\nFor anyone else who is interested, #36046 contains a lot of background information regarding `schema:dump`, much of which is probably relevant to this issue.\r\n\r\nI'm hoping to be able to propose a fix today.",
"created_at": "2022-03-16T13:14:25Z"
},
{
"body": "Okay, I've had a chance to assess the issue pretty thoroughly at this point.\r\n\r\nThis is a complicated problem and understanding #36046 is important to ascertaining why.\r\n\r\n@abelharisov , `artisan db:wipe` only \"kind-of works\" for you because the table names across your two schemas are unique, with the exception of `migrations` (which is why that one is not dropped from the second schema). That is to say, if you had the exact same tables in both schemas, only the tables in the first schema listed would be dropped, and _none_ of the tables in any subsequent schema with the same name would be dropped.\r\n\r\nThe reason for this is rooted in the following method:\r\n\r\nhttps://github.com/laravel/framework/blob/d10ab79687c7f9d915e9e97c3533a1d413e6cda1/src/Illuminate/Database/Schema/PostgresBuilder.php#L139-L148\r\n\r\nIn a multi-schema configuration, if one were to run `php artisan migrate` on two different schemas, so that both contain the exact same tables, this method will return something like the following:\r\n\r\n```sql\r\nselect tablename from pg_catalog.pg_tables where schemaname in ('laravel','public');\r\n```\r\n\r\n```\r\n tablename\r\n------------------------\r\n migrations\r\n users\r\n password_resets\r\n password_resets\r\n migrations\r\n users\r\n failed_jobs\r\n personal_access_tokens\r\n failed_jobs\r\n personal_access_tokens\r\n(10 rows)\r\n```\r\n\r\nThe `dropAllTables()` method (by way of the `compileDropAllTables()` method) simply implodes that list and executes it in a _single SQL statement_, the effect of which is to drop each _unique_ table name from the _first schema in which it is found_.\r\n\r\nAn important point of note here is that if the `DROP TABLE ...` command were run `$y` times, where `$y` is simply the number of schemas defined in the `search_path`, it would drop _any of those table names_ from _every schema_. The reason for this is not straightforward: with each `DROP TABLE ...` invocation, the tables with those names are dropped from the first schema in which they are found, and then with each successive `DROP TABLE ...` execution, the previously-emptied schema would be skipped, and the tables would be dropped from the next schema in the `search_path`, and so on.\r\n\r\nThat said, I don't think that would necessarily be the best or most intuitive way to handle this.\r\n\r\nRather, https://github.com/laravel/framework/blob/650ca875d3bd7e876ed89f803c705d5d6c121d90/src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php#L306-L309 could be modified to include the `schemaname`, e.g.:\r\n\r\n```\r\npostgres=# select schemaname, tablename, CONCAT(schemaname, '.', tablename) AS fully_qualified_name from pg_catalog.pg_tables where schemaname in ('laravel','public');\r\n schemaname | tablename | fully_qualified_name \r\n------------+------------------------+-------------------------------- \r\n laravel | migrations | laravel.migrations \r\n laravel | users | laravel.users \r\n laravel | password_resets | laravel.password_resets \r\n public | password_resets | public.password_resets \r\n public | migrations | public.migrations \r\n public | users | public.users \r\n public | failed_jobs | public.failed_jobs \r\n public | personal_access_tokens | public.personal_access_tokens \r\n laravel | failed_jobs | laravel.failed_jobs \r\n laravel | personal_access_tokens | laravel.personal_access_tokens \r\n(10 rows) \r\n```\r\n\r\nWe could then target the various tables in the appropriate schemas. _However_, there were specific reasons for which I didn't modify that method in this way previously, which I'll do my best to articulate in a subsequent post, as I'm out of time for today. (The gist of it was that while it might be desirable in this specific scenario, it could be undesirable to use the fully-qualified object names in others, in which doing so would actually mitigate and work against the usefulness of the search_path's intent.)\r\n\r\nI'll continue to think through possible solutions to this and post another update tomorrow.",
"created_at": "2022-03-16T21:03:39Z"
},
{
"body": "I have a draft PR, #41541 , which should resolve this issue (and potentially other yet-to-be-identified issues of a similar nature), if anybody wants take it for a spin before I submit it for review. \"Works for me!\", of course. ;-)",
"created_at": "2022-03-18T17:28:45Z"
},
{
"body": "Thank you!",
"created_at": "2022-03-28T14:17:53Z"
}
],
"number": 41483,
"title": "db:wipe doesn't remove migrations table from second schema"
} | {
"body": "#41483 describes a flaw that manifests in the Artisan `db:wipe` command, whereby the tables are not deleted from all schemas.\r\n\r\nThe problem is not so much with the `db:wipe` command itself, but rather, how the underlying library acquires the names of the tables to be deleted.\r\n\r\nThis PR seeks to fix the underlying problem in a backwards-compatible way, and adds a `escapeObjectReferences()` method that offloads the table escaping (quoting) that is applied to schema-qualified and non-schema-qualified table object references to a dedicated method (instead of repeating the same `implode()` code all over the place).",
"number": 41541,
"review_comments": [
{
"body": "This is a 9.x breaking change for the `$excludedTables` check on line 72. Existing apps with values in `config('database.pgsql.dont_drop')` won't be schema-qualified with wrapping quotes. Even the hardcoded `$excludedTables = ['spatial_ref_sys']` default value used by 99.9% of Laravel/Postgres apps will fail to be skipped.",
"created_at": "2022-03-18T20:59:19Z"
},
{
"body": "Great catch! Thank you! This is exactly why I said the following in the related Issue:\r\n\r\n> As is the case with all things search_path-related, the fix is likely to be nuanced and will have to be vetted carefully so as not to break anything else, as not all of the affected code has test coverage (particularly the older code).\r\n\r\nI'll work on a solution to this. Thanks again!",
"created_at": "2022-03-19T15:13:00Z"
},
{
"body": "Whenever it's convenient, please take a look at the new commit that I pushed. My hope is that it resolves the concern that you raise here.\r\n\r\nNow, tables are excluded in a backwards-compatible way, so that all of the following table notations would be excluded:\r\n\r\n```php\r\n'dont_drop' => [\r\n 'users',\r\n '\"password_resets\"',\r\n 'public.failed_jobs',\r\n '\"public\".\"personal_access_tokens\"',\r\n 'spatial_ref_sys'\r\n],\r\n```\r\n\r\nThis configuration produces the following `DROP` query in a stock Laravel installation in which `php artisan migrate` has been run (and `migrations` is the only table we _didn't_ exclude):\r\n\r\n```\r\n\"drop table \"public\".\"migrations\" cascade\"\r\n```\r\n\r\nSo, in essence, the user can schema-qualify those `dont_drop` references if desired, and if not, the unqualified references will be treated just as they have been prior to this PR. That is to say, when a reference is unqualified, the table will not be dropped from _any_ schema in which it exists.\r\n\r\nAs a related aside, the the current logic around the `spatial_ref_sys` table that exists when the `postgis` extension is enabled seems a little odd to me.\r\n\r\nIn essence, the logic is, \"If the user has _not_ specified tables to be excluded, then exclude `spatial_ref_sys`, else, exclude the specified tables (in which case `spatial_ref_sys` will be dropped).\"\r\n\r\nIs that necessarily the desired behavior? It seems all too easy to drop `spatial_ref_sys` without even realizing it's happening, merely by specifying some other, completely unrelated table(s) to be excluded. I suppose once the user realizes what's happening, they'll add `spatial_ref_sys` to the `dont_drop` array, too.\r\n\r\nThe same is true of the `dropAllViews()` method. It'll drop the two views that are created for `postgis` (`geography_columns` and `geometry_columns`):\r\n\r\n```\r\nlaravel=# CREATE EXTENSION postgis; \r\nCREATE EXTENSION \r\nlaravel=# \\d \r\n List of relations \r\n Schema | Name | Type | Owner \r\n--------+-------------------+-------+----------\r\n public | geography_columns | view | postgres \r\n public | geometry_columns | view | postgres \r\n public | spatial_ref_sys | table | postgres \r\n(3 rows) \r\n```\r\n\r\nI don't know if any of this is of concern to anybody, I just figured I'd mention it while on the subject.",
"created_at": "2022-03-21T16:28:12Z"
}
],
"title": "[9.x] Fix \"artisan db:wipe\" command does not drop tables in all schemas"
} | {
"commits": [
{
"message": "fix: \"artisan db:wipe\" command does not drop tables in all schemas\n\nFixes #41483"
}
],
"files": [
{
"diff": "@@ -272,7 +272,7 @@ public function compileDropIfExists(Blueprint $blueprint, Fluent $command)\n */\n public function compileDropAllTables($tables)\n {\n- return 'drop table \"'.implode('\",\"', $tables).'\" cascade';\n+ return 'drop table '.implode(',', $this->escapeObjectReferences($tables)).' cascade';\n }\n \n /**\n@@ -283,7 +283,7 @@ public function compileDropAllTables($tables)\n */\n public function compileDropAllViews($views)\n {\n- return 'drop view \"'.implode('\",\"', $views).'\" cascade';\n+ return 'drop view '.implode(',', $this->escapeObjectReferences($views)).' cascade';\n }\n \n /**\n@@ -294,7 +294,7 @@ public function compileDropAllViews($views)\n */\n public function compileDropAllTypes($types)\n {\n- return 'drop type \"'.implode('\",\"', $types).'\" cascade';\n+ return 'drop type '.implode(',', $this->escapeObjectReferences($types)).' cascade';\n }\n \n /**\n@@ -305,7 +305,7 @@ public function compileDropAllTypes($types)\n */\n public function compileGetAllTables($searchPath)\n {\n- return \"select tablename from pg_catalog.pg_tables where schemaname in ('\".implode(\"','\", (array) $searchPath).\"')\";\n+ return \"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('\".implode(\"','\", (array) $searchPath).\"')\";\n }\n \n /**\n@@ -316,7 +316,7 @@ public function compileGetAllTables($searchPath)\n */\n public function compileGetAllViews($searchPath)\n {\n- return \"select viewname from pg_catalog.pg_views where schemaname in ('\".implode(\"','\", (array) $searchPath).\"')\";\n+ return \"select viewname, schemaname from pg_catalog.pg_views where schemaname in ('\".implode(\"','\", (array) $searchPath).\"')\";\n }\n \n /**\n@@ -1070,4 +1070,31 @@ protected function modifyStoredAs(Blueprint $blueprint, Fluent $column)\n return \" generated always as ({$column->storedAs}) stored\";\n }\n }\n+\n+ /**\n+ * Escape database object references consitently, schema-qualified or not.\n+ *\n+ * @param array $objects\n+ * @return array\n+ */\n+ public function escapeObjectReferences(array $objects): array\n+ {\n+ $escapedObjects = [];\n+\n+ foreach ($objects as $object) {\n+ $parts = explode('.', $object);\n+\n+ $newParts = [];\n+\n+ array_walk($parts, function (&$part) use (&$newParts) {\n+ $part = str_replace(['\"', \"'\"], '', $part);\n+\n+ $newParts[] = $part;\n+ });\n+\n+ $escapedObjects[] = '\"'.implode('\".\"', $parts).'\"';\n+ }\n+\n+ return $escapedObjects;\n+ }\n }",
"filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php",
"status": "modified"
},
{
"diff": "@@ -64,12 +64,14 @@ public function dropAllTables()\n \n $excludedTables = $this->connection->getConfig('dont_drop') ?? ['spatial_ref_sys'];\n \n+ $excludedTables = $this->grammar->escapeObjectReferences($excludedTables);\n+\n foreach ($this->getAllTables() as $row) {\n $row = (array) $row;\n \n- $table = reset($row);\n+ $table = '\"'.$row['schemaname'].'\".\"'.$row['tablename'].'\"';\n \n- if (! in_array($table, $excludedTables)) {\n+ if (! in_array('\"'.$row['tablename'].'\"', $excludedTables) && ! in_array($table, $excludedTables)) {\n $tables[] = $table;\n }\n }\n@@ -95,7 +97,7 @@ public function dropAllViews()\n foreach ($this->getAllViews() as $row) {\n $row = (array) $row;\n \n- $views[] = reset($row);\n+ $views[] = '\"'.$row['schemaname'].'\".\"'.$row['viewname'].'\"';\n }\n \n if (empty($views)) {",
"filename": "src/Illuminate/Database/Schema/PostgresBuilder.php",
"status": "modified"
},
{
"diff": "@@ -238,10 +238,11 @@ public function testDropAllTablesWhenSearchPathIsString()\n $connection->shouldReceive('getConfig')->with('dont_drop')->andReturn(['foo']);\n $grammar = m::mock(PostgresGrammar::class);\n $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);\n- $grammar->shouldReceive('compileGetAllTables')->with(['public'])->andReturn(\"select tablename from pg_catalog.pg_tables where schemaname in ('public')\");\n- $connection->shouldReceive('select')->with(\"select tablename from pg_catalog.pg_tables where schemaname in ('public')\")->andReturn(['users']);\n- $grammar->shouldReceive('compileDropAllTables')->with(['users'])->andReturn('drop table \"'.implode('\",\"', ['users']).'\" cascade');\n- $connection->shouldReceive('statement')->with('drop table \"'.implode('\",\"', ['users']).'\" cascade');\n+ $grammar->shouldReceive('compileGetAllTables')->with(['public'])->andReturn(\"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('public')\");\n+ $connection->shouldReceive('select')->with(\"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('public')\")->andReturn([['schemaname' => 'public', 'tablename' => 'users']]);\n+ $grammar->shouldReceive('escapeObjectReferences')->with(['foo'])->andReturn(['\"foo\"']);\n+ $grammar->shouldReceive('compileDropAllTables')->with(['\"public\".\"users\"'])->andReturn('drop table \"public\".\"users\" cascade');\n+ $connection->shouldReceive('statement')->with('drop table \"public\".\"users\" cascade');\n $builder = $this->getBuilder($connection);\n \n $builder->dropAllTables();\n@@ -255,10 +256,11 @@ public function testDropAllTablesWhenSearchPathIsStringOfMany()\n $connection->shouldReceive('getConfig')->with('dont_drop')->andReturn(['foo']);\n $grammar = m::mock(PostgresGrammar::class);\n $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);\n- $grammar->shouldReceive('compileGetAllTables')->with(['foouser', 'public', 'foo_bar-Baz.Áüõß'])->andReturn(\"select tablename from pg_catalog.pg_tables where schemaname in ('foouser','public','foo_bar-Baz.Áüõß')\");\n- $connection->shouldReceive('select')->with(\"select tablename from pg_catalog.pg_tables where schemaname in ('foouser','public','foo_bar-Baz.Áüõß')\")->andReturn(['users', 'users']);\n- $grammar->shouldReceive('compileDropAllTables')->with(['users', 'users'])->andReturn('drop table \"'.implode('\",\"', ['users', 'users']).'\" cascade');\n- $connection->shouldReceive('statement')->with('drop table \"'.implode('\",\"', ['users', 'users']).'\" cascade');\n+ $grammar->shouldReceive('compileGetAllTables')->with(['foouser', 'public', 'foo_bar-Baz.Áüõß'])->andReturn(\"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('foouser','public','foo_bar-Baz.Áüõß')\");\n+ $connection->shouldReceive('select')->with(\"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('foouser','public','foo_bar-Baz.Áüõß')\")->andReturn([['schemaname' => 'users', 'tablename' => 'users']]);\n+ $grammar->shouldReceive('escapeObjectReferences')->with(['foo'])->andReturn(['\"foo\"']);\n+ $grammar->shouldReceive('compileDropAllTables')->with(['\"users\".\"users\"'])->andReturn('drop table \"users\".\"users\" cascade');\n+ $connection->shouldReceive('statement')->with('drop table \"users\".\"users\" cascade');\n $builder = $this->getBuilder($connection);\n \n $builder->dropAllTables();\n@@ -277,10 +279,11 @@ public function testDropAllTablesWhenSearchPathIsArrayOfMany()\n $connection->shouldReceive('getConfig')->with('dont_drop')->andReturn(['foo']);\n $grammar = m::mock(PostgresGrammar::class);\n $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);\n- $grammar->shouldReceive('compileGetAllTables')->with(['foouser', 'dev', 'test', 'spaced schema'])->andReturn(\"select tablename from pg_catalog.pg_tables where schemaname in ('foouser','dev','test','spaced schema')\");\n- $connection->shouldReceive('select')->with(\"select tablename from pg_catalog.pg_tables where schemaname in ('foouser','dev','test','spaced schema')\")->andReturn(['users', 'users']);\n- $grammar->shouldReceive('compileDropAllTables')->with(['users', 'users'])->andReturn('drop table \"'.implode('\",\"', ['users', 'users']).'\" cascade');\n- $connection->shouldReceive('statement')->with('drop table \"'.implode('\",\"', ['users', 'users']).'\" cascade');\n+ $grammar->shouldReceive('compileGetAllTables')->with(['foouser', 'dev', 'test', 'spaced schema'])->andReturn(\"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('foouser','dev','test','spaced schema')\");\n+ $connection->shouldReceive('select')->with(\"select tablename, schemaname from pg_catalog.pg_tables where schemaname in ('foouser','dev','test','spaced schema')\")->andReturn([['schemaname' => 'users', 'tablename' => 'users']]);\n+ $grammar->shouldReceive('escapeObjectReferences')->with(['foo'])->andReturn(['\"foo\"']);\n+ $grammar->shouldReceive('compileDropAllTables')->with(['\"users\".\"users\"'])->andReturn('drop table \"users\".\"users\" cascade');\n+ $connection->shouldReceive('statement')->with('drop table \"users\".\"users\" cascade');\n $builder = $this->getBuilder($connection);\n \n $builder->dropAllTables();",
"filename": "tests/Database/DatabasePostgresBuilderTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.6.11, but the problem is present in 9.x / main\r\n- PHP Version: 8.1.0\r\n- Database Driver & Version: n/a\r\n\r\n### Description:\r\n\r\nThe `sliding` implementation [here](https://github.com/laravel/framework/blob/9.x/src/Illuminate/Collections/LazyCollection.php#L1027) for `Illuminate\\Support\\LazyCollection` as defined on `Illuminate\\Support\\Enumerable` [here](https://github.com/laravel/framework/blob/9.x/src/Illuminate/Collections/Enumerable.php#L872) uses the `tap` helper, which the file as defined [here](https://github.com/laravel/framework/blob/9.x/src/Illuminate/Support/helpers.php#L288) is not present for when installing the `illuminate\\collections` package standalone, as it doesn't depend on `illuminate/support`\r\n\r\n### Steps To Reproduce:\r\n\r\n- Initialize empty composer project\r\n- `composer require illuminate/collections`\r\n- run the following:\r\n\r\n```\r\nLazyCollection::make(function () {\r\n foreach (range(1, 10) as $value) {\r\n yield $value;\r\n }\r\n})->slide()->dd()\r\n```\r\n\r\nThis gave me\r\n\r\n```\r\nPHP Fatal error: Uncaught Error: Call to undefined function Illuminate\\Support\\tap() in /[redacted]/vendor/illuminate/collections/LazyCollection.php:974\r\nStack trace:\r\n#0 /[redacted]/vendor/illuminate/collections/Traits/EnumeratesValues.php(243): Illuminate\\Support\\LazyCollection->Illuminate\\Support\\{closure}()\r\n#1 /[redacted]/src/import.php(69): Illuminate\\Support\\LazyCollection->each()\r\n#2 {main}\r\n thrown in /[redacted]/vendor/illuminate/collections/LazyCollection.php on line 974\r\n```\r\n\r\nwhich is in line with the above.\r\n\r\nI think the correct solution is to not use `tap` here, as it seems not worth it to go into dependency hell to resolve this -> depending on `illuminate/support` _within_ `illuminate/collections` seems to defeat the purpose of why they were separated in the first place not that long ago.\r\n\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Thanks for your report. @JosephSilber was the original contributor and is gonna look into a fix for this.",
"created_at": "2022-03-03T14:32:21Z"
}
],
"number": 41298,
"title": "LazyCollection depends on tap helper"
} | {
"body": "Closes #41298",
"number": 41326,
"review_comments": [],
"title": "[9.x] Don't use global `tap` helper"
} | {
"commits": [
{
"message": "Don't use global `tap` helper"
}
],
"files": [
{
"diff": "@@ -1024,7 +1024,7 @@ public function sliding($size = 2, $step = 1)\n $chunk[$iterator->key()] = $iterator->current();\n \n if (count($chunk) == $size) {\n- yield tap(new static($chunk), function () use (&$chunk, $step) {\n+ yield (new static($chunk))->tap(function () use (&$chunk, $step) {\n $chunk = array_slice($chunk, $step, null, true);\n });\n ",
"filename": "src/Illuminate/Collections/LazyCollection.php",
"status": "modified"
}
]
} |
{
"body": "### Discussed in https://github.com/laravel/framework/discussions/41299\r\n\r\n\r\n\r\n<sup>Originally posted by **Brenneisen** March 2, 2022</sup>\r\n<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.3.0\r\n- PHP Version: 8.1.1\r\n- Database Driver & Version: MySQL Ver 8.0.27-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))\r\n\r\n### Description:\r\n\r\nI get an error when running `php artisan migrate`. With version `9.2.0` the migrations still work. With `9.3.0` our integration tests throw an error when migrating because of an SSL connection error. For me it seems to be due to the new config `--ssl-ca=\"${:LARAVEL_LOAD_SSL_CA}\"`.\r\n\r\n```\r\nThe command \"mysql --user=\"${:LARAVEL_LOAD_USER}\" --password=\"${:LARAVEL_LOAD_PASSWORD}\" --host=\"${:LARAVEL_LOAD_HOST}\" --port=\"${:LARAVEL_LOAD_PORT}\" --ssl-ca=\"${:LARAVEL_LOAD_SSL_CA}\" --database=\"${:LARAVEL_LOAD_DATABASE}\" < \"${:LARAVEL_LOAD_PATH}\"\" failed.\r\n```\r\n\r\nError Output:\r\n\r\n```\r\nmysql: [Warning] Using a password on the command line interface can be insecure.\r\nERROR 2026 (HY000): SSL connection error: SSL_CTX_set_default_verify_paths failed\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\nRun `php artisan migrate`.\r\n",
"comments": [
{
"body": "I believe it is due to the fact that an empty string is passed: #40931 ",
"created_at": "2022-03-02T21:15:46Z"
},
{
"body": "What is the MySQL client version?",
"created_at": "2022-03-02T22:45:41Z"
},
{
"body": "@DeepDiver1975 \r\n\r\n<img width=\"947\" alt=\"Bildschirmfoto 2022-03-03 um 08 45 47\" src=\"https://user-images.githubusercontent.com/5833477/156519817-be2a6e25-8442-4062-95fd-d91538ede2c4.png\">\r\n",
"created_at": "2022-03-03T07:47:54Z"
},
{
"body": "I will provide a PR later today.\r\nUsing the mariadb client this was not observed. Sorry for the trouble.",
"created_at": "2022-03-03T08:10:46Z"
},
{
"body": "Indeed i just updated to 9.3 and got the same error when my tests runs the migrations: \r\n\r\n```shell\r\nSymfony\\Component\\Process\\Exception\\ProcessFailedException : The command \"mysql --user=\"${:LARAVEL_LOAD_USER}\" --password=\"${:LARAVEL_LOAD_PASSWORD}\" --host=\"${:LARAVEL_LOAD_HOST}\" --port=\"${:LARAVEL_LOAD_PORT}\" --ssl-ca=\"${:LARAVEL_LOAD_SSL_CA}\" --database=\"${:LARAVEL_LOAD_DATABASE}\" < \"${:LARAVEL_LOAD_PATH}\"\" failed.\r\n\r\nExit Code: 1(General error)\r\n\r\nWorking directory: /app\r\n\r\nOutput:\r\n================\r\n\r\nError Output:\r\n================\r\nERROR 2026 (HY000): SSL connection error: Error while reading file.\r\n\r\n/app/vendor/symfony/process/Process.php:267\r\n/app/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlSchemaState.php:77\r\n/app/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:145\r\n...\r\n```\r\n\r\nMy environment is using `mysql Ver 15.1 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) using EditLine wrapper` as client and no configuration on SSL certificates on databases for testing.\r\n\r\nI hope it helps !\r\n\r\n",
"created_at": "2022-03-03T10:17:52Z"
},
{
"body": "Spotted this yesterday while running github action tests that require mysql connection.\r\n\r\nGlad its being looked at already.",
"created_at": "2022-03-03T10:19:05Z"
},
{
"body": "@DeepDiver1975 when will you have time to send in a PR? Otherwise we'll probably revert this for now to unblock people.",
"created_at": "2022-03-03T10:31:11Z"
},
{
"body": "Within the next hour ",
"created_at": "2022-03-03T11:50:13Z"
}
],
"number": 41300,
"title": "ERROR 2026 (HY000): SSL connection error: SSL_CTX_set_default_verify_paths failed"
} | {
"body": "…gured\r\n\r\nfixes #41300 ",
"number": 41315,
"review_comments": [
{
"body": "\" is placed wrong .... will provide fix ...",
"created_at": "2022-03-03T13:00:14Z"
}
],
"title": "[9.x] Fix MySqlSchemaState does not add --ssl-ca to mysql cli "
} | {
"commits": [
{
"message": "fix: MySqlSchemaState does not add --ssl-ca to mysql cli it not configured"
},
{
"message": "Update MySqlSchemaState.php"
}
],
"files": [
{
"diff": "@@ -103,9 +103,15 @@ protected function connectionString()\n {\n $value = ' --user=\"${:LARAVEL_LOAD_USER}\" --password=\"${:LARAVEL_LOAD_PASSWORD}\"';\n \n- $value .= $this->connection->getConfig()['unix_socket'] ?? false\n+ $config = $this->connection->getConfig();\n+\n+ $value .= $config['unix_socket'] ?? false\n ? ' --socket=\"${:LARAVEL_LOAD_SOCKET}\"'\n- : ' --host=\"${:LARAVEL_LOAD_HOST}\" --port=\"${:LARAVEL_LOAD_PORT}\" --ssl-ca=\"${:LARAVEL_LOAD_SSL_CA}\"';\n+ : ' --host=\"${:LARAVEL_LOAD_HOST}\" --port=\"${:LARAVEL_LOAD_PORT}\"';\n+\n+ if (isset($config['options'][\\PDO::MYSQL_ATTR_SSL_CA])) {\n+ $value .= ' --ssl-ca=\"${:LARAVEL_LOAD_SSL_CA}\"';\n+ }\n \n return $value;\n }",
"filename": "src/Illuminate/Database/Schema/MySqlSchemaState.php",
"status": "modified"
},
{
"diff": "@@ -0,0 +1,86 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Database;\n+\n+use Illuminate\\Database\\MySqlConnection;\n+use Illuminate\\Database\\Schema\\MySqlSchemaState;\n+use PHPUnit\\Framework\\TestCase;\n+\n+class DatabaseMySqlSchemaStateTest extends TestCase\n+{\n+ /**\n+ * @dataProvider provider\n+ */\n+ public function testConnectionString(string $expectedConnectionString, array $expectedVariables, array $dbConfig): void\n+ {\n+ $connection = $this->createMock(MySqlConnection::class);\n+ $connection->method('getConfig')->willReturn($dbConfig);\n+\n+ $schemaState = new MySqlSchemaState($connection);\n+\n+ // test connectionString\n+ $method = new \\ReflectionMethod(get_class($schemaState), 'connectionString');\n+ $connString = tap($method)->setAccessible(true)->invoke($schemaState);\n+\n+ self::assertEquals($expectedConnectionString, $connString);\n+\n+ // test baseVariables\n+ $method = new \\ReflectionMethod(get_class($schemaState), 'baseVariables');\n+ $variables = tap($method)->setAccessible(true)->invoke($schemaState, $dbConfig);\n+\n+ self::assertEquals($expectedVariables, $variables);\n+ }\n+\n+ public function provider(): \\Generator\n+ {\n+ yield 'default' => [\n+ ' --user=\"${:LARAVEL_LOAD_USER}\" --password=\"${:LARAVEL_LOAD_PASSWORD}\" --host=\"${:LARAVEL_LOAD_HOST}\" --port=\"${:LARAVEL_LOAD_PORT}\"', [\n+ 'LARAVEL_LOAD_SOCKET' => '',\n+ 'LARAVEL_LOAD_HOST' => '127.0.0.1',\n+ 'LARAVEL_LOAD_PORT' => '',\n+ 'LARAVEL_LOAD_USER' => 'root',\n+ 'LARAVEL_LOAD_PASSWORD' => '',\n+ 'LARAVEL_LOAD_DATABASE' => 'forge',\n+ 'LARAVEL_LOAD_SSL_CA' => '',\n+ ], [\n+ 'username' => 'root',\n+ 'host' => '127.0.0.1',\n+ 'database' => 'forge',\n+ ],\n+ ];\n+\n+ yield 'ssl_ca' => [\n+ ' --user=\"${:LARAVEL_LOAD_USER}\" --password=\"${:LARAVEL_LOAD_PASSWORD}\" --host=\"${:LARAVEL_LOAD_HOST}\" --port=\"${:LARAVEL_LOAD_PORT}\" --ssl-ca=\"${:LARAVEL_LOAD_SSL_CA}\"', [\n+ 'LARAVEL_LOAD_SOCKET' => '',\n+ 'LARAVEL_LOAD_HOST' => '',\n+ 'LARAVEL_LOAD_PORT' => '',\n+ 'LARAVEL_LOAD_USER' => 'root',\n+ 'LARAVEL_LOAD_PASSWORD' => '',\n+ 'LARAVEL_LOAD_DATABASE' => 'forge',\n+ 'LARAVEL_LOAD_SSL_CA' => 'ssl.ca',\n+ ], [\n+ 'username' => 'root',\n+ 'database' => 'forge',\n+ 'options' => [\n+ \\PDO::MYSQL_ATTR_SSL_CA => 'ssl.ca',\n+ ],\n+ ],\n+ ];\n+\n+ yield 'unix socket' => [\n+ ' --user=\"${:LARAVEL_LOAD_USER}\" --password=\"${:LARAVEL_LOAD_PASSWORD}\" --socket=\"${:LARAVEL_LOAD_SOCKET}\"', [\n+ 'LARAVEL_LOAD_SOCKET' => '/tmp/mysql.sock',\n+ 'LARAVEL_LOAD_HOST' => '',\n+ 'LARAVEL_LOAD_PORT' => '',\n+ 'LARAVEL_LOAD_USER' => 'root',\n+ 'LARAVEL_LOAD_PASSWORD' => '',\n+ 'LARAVEL_LOAD_DATABASE' => 'forge',\n+ 'LARAVEL_LOAD_SSL_CA' => '',\n+ ], [\n+ 'username' => 'root',\n+ 'database' => 'forge',\n+ 'unix_socket' => '/tmp/mysql.sock',\n+ ],\n+ ];\n+ }\n+}",
"filename": "tests/Database/DatabaseMySqlSchemaStateTest.php",
"status": "added"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.1.0\r\n- PHP Version: 8.0.8\r\n\r\n### Description:\r\nSending email with priority using Illuminate\\Notifications\\Messages\\MailMessage cause error:\r\n```\r\nCall to undefined method Illuminate\\Mail\\Message::setPriority()\r\n```\r\nThis is because calling wrong function name. Need to replace from `setPriority()` to `priority()` in Illuminate\\Notifications\\Channels\\MailChannel:146\r\n",
"comments": [
{
"body": "This was fixed in Laravel 9.0.2 so just run `composer update`\r\n",
"created_at": "2022-02-19T14:42:30Z"
},
{
"body": "> \r\n\r\nI'm sorry, I'm typo when writing laravel version and the class name. I was edit it.",
"created_at": "2022-02-19T15:03:57Z"
},
{
"body": "A PR was sent in for this, thanks @Jubeki ",
"created_at": "2022-02-21T14:30:31Z"
}
],
"number": 41119,
"title": "Laravel 9 - Error when sending email with priority using MailMessage"
} | {
"body": "Fixes #41119 \r\n\r\nThere seems to be some leftover from Swiftmailer which still uses setPriority.",
"number": 41120,
"review_comments": [],
"title": "[9.x] Fix setPriority Call for MailChannel"
} | {
"commits": [
{
"message": "Fix setPriority Call for MailChannel"
}
],
"files": [
{
"diff": "@@ -143,7 +143,7 @@ protected function buildMessage($mailMessage, $notifiable, $notification, $messa\n $this->addAttachments($mailMessage, $message);\n \n if (! is_null($message->priority)) {\n- $mailMessage->setPriority($message->priority);\n+ $mailMessage->priority($message->priority);\n }\n \n if ($message->tags) {",
"filename": "src/Illuminate/Notifications/Channels/MailChannel.php",
"status": "modified"
},
{
"diff": "@@ -98,7 +98,7 @@ public function testMailIsSent()\n \n $message->shouldReceive('subject')->once()->with('Test Mail Notification');\n \n- $message->shouldReceive('setPriority')->once()->with(1);\n+ $message->shouldReceive('priority')->once()->with(1);\n \n $closure($message);\n \n@@ -144,7 +144,7 @@ public function testMailIsSentToNamedAddress()\n \n $message->shouldReceive('subject')->once()->with('Test Mail Notification');\n \n- $message->shouldReceive('setPriority')->once()->with(1);\n+ $message->shouldReceive('priority')->once()->with(1);\n \n $closure($message);\n ",
"filename": "tests/Integration/Notifications/SendingMailNotificationsTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.83.x, 9.0.x\r\n- PHP Version: 8.1.1\r\n- Database Driver & Version: Postgresql 10\r\n\r\n### Description:\r\n\r\nWhen calling the firstWhere() method of a Model with the second Parameter being \"-\" and when there is no database entry with \"-\" it returns a seemingly random Model object.\r\n\r\nProbably it assumes \"-\" is the operator and value is \"null\". Which is not correct.\r\n\r\n### Steps To Reproduce:\r\n\r\nFailing Test:\r\n\r\n```\r\n User::factory()->create([\r\n \"name\" => 'Foo'\r\n ]);\r\n\r\n $user = User::firstWhere('name', '-');\r\n\r\n $this->assertNull($user);\r\n```\r\n\r\nThis test is using the User model. But every other model will do.\r\n\r\nWhen explicitly specifying an operator it works as expected:\r\n\r\n```php\r\n$user = User::query()->firstWhere('name', '=', '-');\r\n```",
"comments": [
{
"body": "I think this is Postgres specific behavior? I get `null` back on MySQL.",
"created_at": "2022-02-18T13:06:04Z"
},
{
"body": "@driesvints It is still a Laravel bug though.\r\n\r\nTry something different (this one should work in MySQL too):\r\n```\r\n User::factory()->create([\r\n \"name\" => '='\r\n ]);\r\n\r\n $user = User::firstWhere('name', '=');\r\n\r\n $this->assertNotNull($user); // FAIL\r\n```\r\n\r\nYou are expecting it is looking for a user with name `=`. But it does something completely different. The query looks something like this:\r\n\r\n```\r\nSELECT * FROM 'users' WHERE name = null\r\n```\r\n\r\nWhen using `where` and `first` it gives you a different result:\r\n\r\n```\r\n User::factory()->create([\r\n \"name\" => '='\r\n ]);\r\n\r\n $user = User::where('name', '=')->first();\r\n\r\n $this->assertNotNull($user); // PASS\r\n```\r\n\r\nThis one does the correct query:\r\n\r\n```\r\nSELECT * FROM 'users' WHERE name = '='\r\n```\r\n\r\nPassing 2 arguments to a `where` function (even `firstWhere`) should result in the default operator being `=` in all cases. It is a problem with passing the arguments from the `firstWhere` to the actual `where` function.\r\n\r\nThe query builder will always receive more than 2 arguments when it is called through `firstWhere`:\r\n\r\nhttps://github.com/laravel/framework/blob/dbcb3a2e8d771fcc4002580a84ea107de128bf00/src/Illuminate/Database/Query/Builder.php#L706-L708",
"created_at": "2022-02-18T13:59:31Z"
},
{
"body": "@marvinrabe I still get `null` for your first example. Please try a support channel.",
"created_at": "2022-02-18T14:01:05Z"
},
{
"body": "@driesvints Please note the assertion is different that time.\r\n\r\n```\r\n User::factory()->create([\r\n \"name\" => '='\r\n ]);\r\n\r\n $user = User::firstWhere('name', '=');\r\n\r\n $this->assertNotNull($user); // FAIL\r\n```\r\n\r\nThis `$user` should not be NULL in this case.",
"created_at": "2022-02-18T14:05:16Z"
},
{
"body": "Hah, I finally managed to reproduce that, thanks.",
"created_at": "2022-02-18T14:08:15Z"
},
{
"body": "The problem only occurs when the value (passing it as `$operator`) is a valid Operator according to the specific `\\Illuminate\\Database\\Query\\Grammars\\Grammar`. Otherwise it is fixed on this line:\r\n\r\nhttps://github.com/laravel/framework/blob/dbcb3a2e8d771fcc4002580a84ea107de128bf00/src/Illuminate/Database/Query/Builder.php#L730-L732\r\n",
"created_at": "2022-02-18T14:16:14Z"
},
{
"body": "This issue also effects passing enums to the `firstWhere` method:\r\n\r\n```\r\nenum SpecialPeople: string\r\n{\r\n case Taylor = 'Taylor Otwell';\r\n}\r\n\r\nUser::firstWhere('name', SpecialPeople::Taylor);\r\n```\r\n\r\nThe above throws an error while validating `SpecialPeople::Taylor` as an operator:\r\n\r\n```\r\nTypeError : strtolower(): Argument #1 ($string) must be of type string, Tests\\Feature\\Suit given\r\n```\r\n\r\nThis would not happen when the default operator is correctly applied on Line 706 (Builder).",
"created_at": "2022-02-18T14:45:14Z"
},
{
"body": "@marvinrabe that seems more of a feature request to me.",
"created_at": "2022-02-18T14:47:01Z"
},
{
"body": "@driesvints It would be a feature request if I wanted to pass an enum as an operator. But in this case the Enum should be the value. But because of the error in the default handling it is not working correctly. This is an additional unwanted side effect of always passing more than 2 parameters from `firstWhere` to `where`. Fixing this issue, fixes passing Enums as value to `firstWhere` too.\r\n\r\nPlease note that in this case everything works perfectly:\r\n```\r\nenum SpecialPeople: string\r\n{\r\n case Taylor = 'Taylor Otwell';\r\n}\r\n\r\nUser::firstWhere('name', '=', SpecialPeople::Taylor);\r\n```\r\n\r\nThis error exists because of validating an operator, that should not be an operator in the first place.",
"created_at": "2022-02-18T14:55:06Z"
}
],
"number": 41098,
"title": "Eloquent: firstWhere returns wrong result when passing an operator as value"
} | {
"body": "Fixes #41098",
"number": 41099,
"review_comments": [],
"title": "[9.x] Eloquent: firstWhere returns Object instead of NULL"
} | {
"commits": [
{
"message": "Eloquent: firstWhere returns Object instead of NULL"
}
],
"files": [
{
"diff": "@@ -296,7 +296,7 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'\n */\n public function firstWhere($column, $operator = null, $value = null, $boolean = 'and')\n {\n- return $this->where($column, $operator, $value, $boolean)->first();\n+ return $this->where(...func_get_args())->first();\n }\n \n /**",
"filename": "src/Illuminate/Database/Eloquent/Builder.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.0.1\r\n- PHP Version: 8.1.2\r\n- Database Driver & Version: irrelevant\r\n\r\n### Description:\r\nUsing an or sign (`|`) within a regex validation rule for an array item breaks on Laravel 9.x. This works fine on Laravel 8.x.\r\n\r\nIt seems somewhere the rules are parsed and the `|` is interpreted as start of another validation rule instead of as being part of the regex rule, causing the parsed regex rule to be `regex:/^(typeA|`. \r\n\r\nMost probably related to https://github.com/laravel/framework/pull/40498.\r\n\r\n### Steps To Reproduce:\r\n\r\nSee https://github.com/jnoordsij/laravel/tree/regex-validation-bug-8.x for the (working) 8.x version and https://github.com/jnoordsij/laravel/tree/regex-validation-bug-9.x for the test breaking on 9.x.\r\n\r\n1. clone repo\r\n2. `composer install`\r\n3. `cp .env.example .env.testing`\r\n4. `php artisan key:generate --env=testing`\r\n5. `php artisan test tests/Feature/SimpleRequestTest.php`\r\n\r\nResulting exception:\r\n`ErrorException: preg_match(): No ending delimiter '/' found in ...`\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "You should wrap your `regex` rule in an array. For example, this will fail:\r\n\r\n```php\r\n$v = new Validator($trans, ['x' => 'foo'], ['x' => 'Regex:/^(taylor|james)$/i']);\r\n$this->assertTrue($v->passes());\r\n```\r\n\r\nBut this will pass:\r\n\r\n```diff\r\n-$v = new Validator($trans, ['x' => 'foo'], ['x' => 'Regex:/^(taylor|james)$/i']);\r\n+$v = new Validator($trans, ['x' => 'foo'], ['x' => ['Regex:/^(taylor|james)$/i']]);\r\n$this->assertTrue($v->passes());\r\n```",
"created_at": "2022-02-10T11:42:55Z"
},
{
"body": "Note that this is what the documentation instructs you to do, when your regex contains a `|`. https://laravel.com/docs/9.x/validation#rule-regex",
"created_at": "2022-02-10T11:44:41Z"
},
{
"body": "Sorry, I see this is more nuanced as it's affecting nested rules only. I'll re-open whilst I investigate.",
"created_at": "2022-02-10T11:46:48Z"
},
{
"body": "The regex rule is actually in array form; I could understand that using something like `'contact.phonenumbers.*.type' => 'regex:/^(typeA|typeB|typeC)$/|required|string'` would be too ambiguous to parse, but the example I provided seems to comply with what the documentation instructs.",
"created_at": "2022-02-10T11:59:57Z"
},
{
"body": "Right, this passes in 8.x but fails in 9.x.\r\n\r\n```php\r\n$v = new Validator($trans,\r\n ['x' => ['y' => ['z' => 'james']]],\r\n ['x.*.z' => [\r\n 'required',\r\n 'string',\r\n 'Regex:/^(taylor|james)$/i'\r\n ]]\r\n);\r\n$this->assertTrue($v->passes());\r\n```\r\n\r\n```\r\n1) Illuminate\\Tests\\Validation\\ValidationValidatorTest::testValidateRegex\r\npreg_match(): No ending delimiter '/' found\r\n```",
"created_at": "2022-02-10T12:00:04Z"
},
{
"body": "@stevebauman any idea how to solve this? Otherwise, we need to revert Rule::forEach",
"created_at": "2022-02-10T15:07:12Z"
},
{
"body": "Give me a moment -- investigating now 👍 ",
"created_at": "2022-02-10T15:08:36Z"
},
{
"body": "@stevebauman from my investigation so far the error is around here:\r\n\r\nhttps://github.com/laravel/framework/blob/4c7cd8c4e95d161c0c6ada6efa0a5af4d0d487c9/src/Illuminate/Validation/ValidationRuleParser.php#L145-L161\r\n\r\nIf I replace the lines above by their 8.x counterpart...\r\n\r\nhttps://github.com/laravel/framework/blob/29bc8779103909ebc428478b339ee6fa8703e193/src/Illuminate/Validation/ValidationRuleParser.php#L133-L137\r\n\r\n...it works (tested `->passes()`, `->fails()` and `->validated()`)\r\n\r\nI am still digging into it, but I thought it would be nice to share",
"created_at": "2022-02-10T15:17:28Z"
},
{
"body": "@stevebauman in 8.x when `$rule` was a regex and reached here:\r\n\r\nhttps://github.com/laravel/framework/blob/4c7cd8c4e95d161c0c6ada6efa0a5af4d0d487c9/src/Illuminate/Validation/ValidationRuleParser.php#L85-L98\r\n\r\nIt was wrapped into an array, now it reaches here as a string, thus it gets on the first `if` clause that explodes it.\r\n\r\nOne other thing: if the regex validation rule is a top-level rule it works. It only fails when it is nested.",
"created_at": "2022-02-10T15:37:12Z"
},
{
"body": "@stevebauman if we change this line:\r\n\r\nhttps://github.com/laravel/framework/blob/4c7cd8c4e95d161c0c6ada6efa0a5af4d0d487c9/src/Illuminate/Validation/ValidationRuleParser.php#L145\r\n\r\nback to as it was in 8.x\r\n\r\n~~~php\r\nforeach ((array) $rules as $rule) {\r\n~~~\r\n\r\nIt works. From the blame this line was changed by you on PR #40498\r\n\r\nI will run the tests with this change and report back.\r\n\r\nEDIT: it works with the test case provided by OP",
"created_at": "2022-02-10T15:44:09Z"
},
{
"body": "@stevebauman Changing it back as of my last comment makes these two tests fail:\r\n\r\n~~~\r\nThere were 2 failures:\r\n\r\n1) Illuminate\\Tests\\Validation\\ValidationRuleParserTest::testExplodeHandlesArraysOfNestedRules\r\nFailed asserting that two arrays are equal.\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n Array (\r\n 'users.0.name' => Array (\r\n- 0 => 'required'\r\n- 1 => 'in:\"taylor\"'\r\n+ 0 => Array (...)\r\n+ 1 => Array (...)\r\n )\r\n 'users.1.name' => Array (\r\n- 0 => 'required'\r\n- 1 => 'in:\"abigail\"'\r\n+ 0 => Array (...)\r\n+ 1 => Array (...)\r\n )\r\n )\r\n\r\n/home/rodrigo/code/open-source/framework/tests/Validation/ValidationRuleParserTest.php:171\r\n\r\n2) Illuminate\\Tests\\Validation\\ValidationRuleParserTest::testExplodeHandlesRecursivelyNestedRules\r\nFailed asserting that null matches expected 'Taylor Otwell'.\r\n\r\n/home/rodrigo/code/open-source/framework/tests/Validation/ValidationRuleParserTest.php:192\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/NestedRules.php:37\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:122\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:96\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:71\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:201\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:187\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:159\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:67\r\n/home/rodrigo/code/open-source/framework/src/Illuminate/Validation/ValidationRuleParser.php:49\r\n/home/rodrigo/code/open-source/framework/tests/Validation/ValidationRuleParserTest.php:209\r\n~~~\r\n\r\nI have an appointment in 10 minutes, so I will only be able to look into it further later. Hope it helps you out :)",
"created_at": "2022-02-10T15:52:10Z"
}
],
"number": 40924,
"title": "[9.x] Regex validation rules for array items containing 'or' seperators cause ErrorException on input validation"
} | {
"body": "Working to fix #40924",
"number": 40929,
"review_comments": [],
"title": "[9.x] Add failing test for `forEach` validation using regex"
} | {
"commits": [
{
"message": "Add failing test for `forEach` validation using regex"
},
{
"message": "Apply fixes from StyleCI"
}
],
"files": [
{
"diff": "@@ -201,6 +201,32 @@ public function testForEachCallbacksCanReturnDifferentRules()\n ], $v->getMessageBag()->toArray());\n }\n \n+ public function testNestedCallbacksDoNotBreakRegexRules()\n+ {\n+ $data = [\n+ 'items' => [\n+ ['users' => [['type' => 'super'], ['type' => 'admin']]],\n+ ],\n+ ];\n+\n+ $rules = [\n+ 'items.*' => Rule::forEach(function () {\n+ return ['users.*.type' => 'regex:/^(super|admin)$/i'];\n+ }),\n+ ];\n+\n+ $trans = $this->getIlluminateArrayTranslator();\n+\n+ $v = new Validator($trans, $data, $rules);\n+\n+ $this->assertFalse($v->passes());\n+\n+ $this->assertEquals([\n+ 'items.0.users.0.type' => ['validation.regex'],\n+ 'items.0.users.1.type' => ['validation.regex'],\n+ ], $v->getMessageBag()->toArray());\n+ }\n+\n protected function getTranslator()\n {\n return m::mock(TranslatorContract::class);",
"filename": "tests/Validation/ValidationForEachTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.0\r\n- PHP Version: 8.1\r\n- Database Driver & Version: MySQL\r\n\r\n### Description:\r\nWhen the email address and name are returned from `routeNotificationForMail` in a modal, the RfcComplianceException is thrown. \r\n\r\n public function routeNotificationForMail($notification) \r\n { \r\n \\Log::debug([$this->email => $this->name]); \r\n return [$this->email => $this->name];\r\n }\r\n\r\n\r\n\r\n\r\nLog\r\n\r\n```\r\n[2022-02-09 16:48:36] local.DEBUG: array (\r\n 'karim.naimy@gmail.com' => 'karim',\r\n) \r\n[2022-02-09 16:48:36] local.DEBUG: array (\r\n 'karim.naimy@gmail.com' => 'karim',\r\n) \r\n[2022-02-09 16:48:36] local.ERROR: Email \"karim\" does not comply with addr-spec of RFC 2822. {\"exception\":\"[object] (Symfony\\\\Component\\\\Mime\\\\Exception\\\\RfcComplianceException(code: 0): Email \\\"karim\\\" does not comply with addr-spec of RFC 2822. at /home/karim/www/example-app/vendor/symfony/mime/Address.php:54)\r\n[stacktrace]\r\n#0 /home/karim/www/example-app/vendor/symfony/mime/Address.php(96): Symfony\\\\Component\\\\Mime\\\\Address->__construct()\r\n#1 /home/karim/www/example-app/vendor/symfony/mime/Address.php(115): Symfony\\\\Component\\\\Mime\\\\Address::create()\r\n#2 /home/karim/www/example-app/vendor/symfony/mime/Email.php(528): Symfony\\\\Component\\\\Mime\\\\Address::createArray()\r\n#3 /home/karim/www/example-app/vendor/symfony/mime/Email.php(169): Symfony\\\\Component\\\\Mime\\\\Email->setListAddressHeaderBody()\r\n#4 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Mail/Message.php(211): Symfony\\\\Component\\\\Mime\\\\Email->to()\r\n#5 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Mail/Message.php(105): Illuminate\\\\Mail\\\\Message->addAddresses()\r\n#6 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(163): Illuminate\\\\Mail\\\\Message->to()\r\n#7 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(135): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->addressMessage()\r\n#8 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(80): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->buildMessage()\r\n#9 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(267): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->Illuminate\\\\Notifications\\\\Channels\\\\{closure}()\r\n#10 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(65): Illuminate\\\\Mail\\\\Mailer->send()\r\n#11 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(148): Illuminate\\\\Notifications\\\\Channels\\\\MailChannel->send()\r\n#12 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(106): Illuminate\\\\Notifications\\\\NotificationSender->sendToNotifiable()\r\n#13 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php(19): Illuminate\\\\Notifications\\\\NotificationSender->Illuminate\\\\Notifications\\\\{closure}()\r\n#14 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(109): Illuminate\\\\Notifications\\\\NotificationSender->withLocale()\r\n#15 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(79): Illuminate\\\\Notifications\\\\NotificationSender->sendNow()\r\n#16 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(39): Illuminate\\\\Notifications\\\\NotificationSender->send()\r\n#17 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): Illuminate\\\\Notifications\\\\ChannelManager->send()\r\n#18 /home/karim/www/example-app/vendor/laravel/framework/src/Illuminate/Auth/Passwords/CanResetPassword.php(27): App\\\\Models\\\\User->notify()\r\n......\r\n#70 {main}\r\n\"} \r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Changing the return value of `routeNotificationForMail` function in the modal to match the `FROM_STRING_PATTERN `regex in `Symfony\\Component\\Mime\\Address` is working as expected. \r\n\r\n```\r\n// Symfony\\Component\\Mime\\Address\r\nprivate const FROM_STRING_PATTERN = '~(?<displayName>[^<]*)<(?<addrSpec>.*)>[^>]*~'; \r\n```\r\n\r\n //User Modal\r\n public function routeNotificationForMail($notification) \r\n { \r\n return \"$this->name <$this->email>\"; \r\n }\r\n\r\n\r\n",
"created_at": "2022-02-10T10:28:13Z"
},
{
"body": "Thanks for reporting. I've sent in a fix for this: https://github.com/laravel/framework/pull/40921",
"created_at": "2022-02-10T10:29:42Z"
},
{
"body": "Relatedly, in Laravel v9.5.1 I got a `TypeError: \"Illuminate\\Mail\\Message::Illuminate\\Mail\\{closure}(): Argument #1 ($address) must be of type array|string, null given\"` apparently because my $user->name was null (code simplified):\r\n\r\n```\r\nclass User extends Authenticatable\r\n{\r\n use Notifiable;\r\n\r\n public function routeNotificationForMail($notification)\r\n {\r\n return [$this->email => $this->name];\r\n }\r\n}\r\n```",
"created_at": "2022-03-31T05:02:37Z"
},
{
"body": "@jordanade i think that just surfaces a bug in your code. If the name is null then you should just return the email address. ",
"created_at": "2022-03-31T07:09:51Z"
},
{
"body": "@driesvints Nevertheless, an undocumented breaking change in Laravel 9 for a common situation that arises from boilerplate code (in fact right from the docs). Currently ungoogleable so I'm sure me posting the error message above will help others.",
"created_at": "2022-04-01T23:54:35Z"
},
{
"body": "@jordanade please post the entire stack trace of your error with the correct call lines.",
"created_at": "2022-04-04T10:38:11Z"
},
{
"body": "Sure, here is one of them @driesvints \r\n```\r\nTypeError: Illuminate\\Mail\\Message::Illuminate\\Mail\\{closure}(): Argument #1 ($address) must be of type array|string, null given\r\n#88 /vendor/laravel/framework/src/Illuminate/Mail/Message.php(223): Illuminate\\Mail\\Message::Illuminate\\Mail\\{closure}\r\n#87 [internal](0): array_map\r\n#86 /vendor/laravel/framework/src/Illuminate/Collections/Collection.php(721): Illuminate\\Support\\Collection::map\r\n#85 /vendor/laravel/framework/src/Illuminate/Mail/Message.php(233): Illuminate\\Mail\\Message::addAddresses\r\n#84 /vendor/laravel/framework/src/Illuminate/Mail/Message.php(105): Illuminate\\Mail\\Message::to\r\n#83 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(177): Illuminate\\Notifications\\Channels\\MailChannel::addressMessage\r\n#82 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(137): Illuminate\\Notifications\\Channels\\MailChannel::buildMessage\r\n#81 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(82): Illuminate\\Notifications\\Channels\\MailChannel::Illuminate\\Notifications\\Channels\\{closure}\r\n#80 /vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(267): Illuminate\\Mail\\Mailer::send\r\n#79 /vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(67): Illuminate\\Notifications\\Channels\\MailChannel::send\r\n#78 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(148): Illuminate\\Notifications\\NotificationSender::sendToNotifiable\r\n#77 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(106): Illuminate\\Notifications\\NotificationSender::Illuminate\\Notifications\\{closure}\r\n#76 /vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php(19): Illuminate\\Notifications\\NotificationSender::withLocale\r\n#75 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(109): Illuminate\\Notifications\\NotificationSender::sendNow\r\n#74 /vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(79): Illuminate\\Notifications\\NotificationSender::send\r\n#73 /vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(39): Illuminate\\Notifications\\ChannelManager::send\r\n#72 /vendor/laravel/framework/src/Illuminate/Notifications/RoutesNotifications.php(18): App\\User::notify\r\n#71 /app/Listeners/UserEventSubscriber.php(19): App\\Listeners\\UserEventSubscriber::handleUserAssignedRole\r\n#70 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(441): Illuminate\\Events\\Dispatcher::Illuminate\\Events\\{closure}\r\n#69 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(249): Illuminate\\Events\\Dispatcher::dispatch\r\n#68 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(206): Illuminate\\Database\\Eloquent\\Model::fireCustomModelEvent\r\n#67 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(181): Illuminate\\Database\\Eloquent\\Model::fireModelEvent\r\n#66 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1176): Illuminate\\Database\\Eloquent\\Model::performInsert\r\n#65 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(996): Illuminate\\Database\\Eloquent\\Model::save\r\n#64 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(531): Illuminate\\Database\\Eloquent\\Builder::Illuminate\\Database\\Eloquent\\{closure}\r\n#63 /vendor/laravel/framework/src/Illuminate/Support/helpers.php(302): tap\r\n#62 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(532): Illuminate\\Database\\Eloquent\\Builder::firstOrCreate\r\n#61 /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php(23): Illuminate\\Database\\Eloquent\\Model::forwardCallTo\r\n#60 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2133): Illuminate\\Database\\Eloquent\\Model::__call\r\n#59 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2145): Illuminate\\Database\\Eloquent\\Model::__callStatic\r\n#58 /app/User.php(76): App\\User::assignRole\r\n#57 /app/Site.php(104): App\\Site::assignUserWithRole\r\n#56 /app/Http/Controllers/SiteUserController.php(39): App\\Http\\Controllers\\SiteUserController::store\r\n#55 /vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): Illuminate\\Routing\\Controller::callAction\r\n#54 /vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\ControllerDispatcher::dispatch\r\n#53 /vendor/laravel/framework/src/Illuminate/Routing/Route.php(261): Illuminate\\Routing\\Route::runController\r\n#52 /vendor/laravel/framework/src/Illuminate/Routing/Route.php(204): Illuminate\\Routing\\Route::run\r\n#51 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(725): Illuminate\\Routing\\Router::Illuminate\\Routing\\{closure}\r\n#50 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#49 /app/Http/Middleware/PageRequestInjector.php(33): App\\Http\\Middleware\\PageRequestInjector::handle\r\n#48 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#47 /vendor/spatie/laravel-referer/src/CaptureReferer.php(21): Spatie\\Referer\\CaptureReferer::handle\r\n#46 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#45 /vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\Routing\\Middleware\\SubstituteBindings::handle\r\n#44 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#43 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(78): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken::handle\r\n#42 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#41 /vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\View\\Middleware\\ShareErrorsFromSession::handle\r\n#40 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#39 /vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(121): Illuminate\\Session\\Middleware\\StartSession::handleStatefulRequest\r\n#38 /vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(64): Illuminate\\Session\\Middleware\\StartSession::handle\r\n#37 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#36 /vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse::handle\r\n#35 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#34 /vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(67): Illuminate\\Cookie\\Middleware\\EncryptCookies::handle\r\n#33 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#32 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline::then\r\n#31 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(727): Illuminate\\Routing\\Router::runRouteWithinStack\r\n#30 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(702): Illuminate\\Routing\\Router::runRoute\r\n#29 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(666): Illuminate\\Routing\\Router::dispatchToRoute\r\n#28 /vendor/laravel/framework/src/Illuminate/Routing/Router.php(655): Illuminate\\Routing\\Router::dispatch\r\n#27 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(167): Illuminate\\Foundation\\Http\\Kernel::Illuminate\\Foundation\\Http\\{closure}\r\n#26 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#25 /vendor/sentry/sentry-laravel/src/Sentry/Laravel/Http/SetRequestIpMiddleware.php(45): Sentry\\Laravel\\Http\\SetRequestIpMiddleware::handle\r\n#24 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#23 /vendor/sentry/sentry-laravel/src/Sentry/Laravel/Http/SetRequestMiddleware.php(42): Sentry\\Laravel\\Http\\SetRequestMiddleware::handle\r\n#22 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#21 /vendor/livewire/livewire/src/DisableBrowserCache.php(19): Livewire\\DisableBrowserCache::handle\r\n#20 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#19 /vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php(60): Barryvdh\\Debugbar\\Middleware\\InjectDebugbar::handle\r\n#18 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#17 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest::handle\r\n#16 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::handle\r\n#15 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#14 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest::handle\r\n#13 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\\Foundation\\Http\\Middleware\\TrimStrings::handle\r\n#12 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#11 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::handle\r\n#10 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#9 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance::handle\r\n#8 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#7 /vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php(39): Illuminate\\Http\\Middleware\\TrustProxies::handle\r\n#6 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#5 /vendor/sentry/sentry-laravel/src/Sentry/Laravel/Tracing/Middleware.php(53): Sentry\\Laravel\\Tracing\\Middleware::handle\r\n#4 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}\r\n#3 /vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline::then\r\n#2 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(142): Illuminate\\Foundation\\Http\\Kernel::sendRequestThroughRouter\r\n#1 /vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(111): Illuminate\\Foundation\\Http\\Kernel::handle\r\n#0 /public/index.php(53): null\r\n```",
"created_at": "2022-04-06T09:06:22Z"
},
{
"body": "Heya, I tried to provide a fix through https://github.com/laravel/framework/pull/41870. Still, this will not notify you of the fact that no name was provided. It's best that you also add a check in userland.",
"created_at": "2022-04-07T13:11:03Z"
}
],
"number": 40895,
"title": "Email Notification Customizing The Recipient Bug in Laravel9"
} | {
"body": "This PR fixes an issue where the address of a notifiable for email sending is returned as a key/value array. Fixes #40895\n",
"number": 40921,
"review_comments": [],
"title": "[9.x] Fix notification email recipient"
} | {
"commits": [
{
"message": "Fix notification email recipient"
},
{
"message": "Add test"
}
],
"files": [
{
"diff": "@@ -200,7 +200,11 @@ protected function addAddresses($address, $name, $type)\n if (is_array($address)) {\n $type = lcfirst($type);\n \n- $addresses = collect($address)->map(function (string|array $address) {\n+ $addresses = collect($address)->map(function (string|array $address, $key) {\n+ if (is_string($key) && is_string($address)) {\n+ return new Address($key, $address);\n+ }\n+\n if (is_array($address)) {\n return new Address($address['email'] ?? $address['address'], $address['name'] ?? null);\n }",
"filename": "src/Illuminate/Mail/Message.php",
"status": "modified"
},
{
"diff": "@@ -41,8 +41,11 @@ public function testReturnPathMethod()\n \n public function testToMethod()\n {\n- $this->assertInstanceOf(Message::class, $message = $this->message->to('foo@bar.baz', 'Foo', false));\n+ $this->assertInstanceOf(Message::class, $message = $this->message->to('foo@bar.baz', 'Foo'));\n $this->assertEquals(new Address('foo@bar.baz', 'Foo'), $message->getSymfonyMessage()->getTo()[0]);\n+\n+ $this->assertInstanceOf(Message::class, $message = $this->message->to(['bar@bar.baz' => 'Bar']));\n+ $this->assertEquals(new Address('bar@bar.baz', 'Bar'), $message->getSymfonyMessage()->getTo()[0]);\n }\n \n public function testToMethodWithOverride()",
"filename": "tests/Mail/MailMessageTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 9.0.1\r\n- PHP Version: 8.0.14\r\n\r\n### Description:\r\n\r\nMailable->priority() errors when being sent\r\n\r\nCurrent:\r\n```php\r\n public function priority($level = 3)\r\n {\r\n $this->callbacks[] = function ($message) use ($level) {\r\n $message->setPriority($level);\r\n };\r\n\r\n return $this;\r\n }\r\n```\r\n\r\nSymfony Email class doesn't have `setPriority`, but instead `priority` function.\r\n",
"comments": [],
"number": 40916,
"title": "[9.x] Mailable Priority Error"
} | {
"body": "Fixes #40916",
"number": 40917,
"review_comments": [],
"title": "[9.x] Fix Mailable->priority()"
} | {
"commits": [
{
"message": "Fix Mailable->priority()\n\nFixes #40916"
}
],
"files": [
{
"diff": "@@ -488,7 +488,7 @@ public function locale($locale)\n public function priority($level = 3)\n {\n $this->callbacks[] = function ($message) use ($level) {\n- $message->setPriority($level);\n+ $message->priority($level);\n };\n \n return $this;",
"filename": "src/Illuminate/Mail/Mailable.php",
"status": "modified"
},
{
"diff": "@@ -2,11 +2,20 @@\n \n namespace Illuminate\\Tests\\Mail;\n \n+use Illuminate\\Contracts\\View\\Factory;\n use Illuminate\\Mail\\Mailable;\n+use Illuminate\\Mail\\Mailer;\n+use Illuminate\\Mail\\Transport\\ArrayTransport;\n+use Mockery as m;\n use PHPUnit\\Framework\\TestCase;\n \n class MailMailableTest extends TestCase\n {\n+ protected function tearDown(): void\n+ {\n+ m::close();\n+ }\n+\n public function testMailableSetsRecipientsCorrectly()\n {\n $mailable = new WelcomeMailableStub;\n@@ -417,6 +426,25 @@ public function testMailerMayBeSet()\n \n $this->assertSame('array', $mailable->mailer);\n }\n+\n+ public function testMailablePriorityGetsSent()\n+ {\n+ $view = m::mock(Factory::class);\n+\n+ $mailer = new Mailer('array', $view, new ArrayTransport);\n+\n+ $mailable = new WelcomeMailableStub;\n+ $mailable->to('hello@laravel.com');\n+ $mailable->from('taylor@laravel.com');\n+ $mailable->html('test content');\n+\n+ $mailable->priority(1);\n+\n+ $sentMessage = $mailer->send($mailable);\n+\n+ $this->assertSame('hello@laravel.com', $sentMessage->getEnvelope()->getRecipients()[0]->getAddress());\n+ $this->assertStringContainsString('X-Priority: 1 (Highest)', $sentMessage->toString());\n+ }\n }\n \n class WelcomeMailableStub extends Mailable",
"filename": "tests/Mail/MailMailableTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 6.13.1\r\n- PHP Version: 7.2.27\r\n- Database Driver & Version: Redis\r\n\r\n### Description:\r\n`RedisStore::serialize()` and `unserialize()` don't do right when it comes to caching numbers. I think the code has some considerations that Redis stores strings that are integers more efficient than normal integers. But the implementation is wrong.\r\nFrom https://redis.io/commands/INCR:\r\n> Redis stores integers in their integer representation, so for string values that actually hold an integer, there is no overhead for storing the string representation of the integer.\r\n\r\n### Steps To Reproduce:\r\nSet cache driver to redis and try the followings:\r\n```php\r\nCache::put('test', '1');\r\nCache::get('test');; // expected = actual = \"1\"\r\nCache::put('test', 1);\r\nCache::get('test'); // expected: 1, actual \"1\"\r\nCache::put('test', 1.0);\r\nCache::get('test'); // expected: 1.0, actual \"1\"\r\nCache::put('test', INF)\r\nCache::get('test'); // expected INF, actual: PHP Notice: unserialize(): Error at offset 0 of 3 bytes\r\nCache::put('test', -INF)\r\nCache::get('test'); // expected -INF, actual: PHP Notice: unserialize(): Error at offset 0 of 4 bytes\r\nCache::put('test', NAN);\r\nCache::get('test');// expected: NAN, actual: PHP Notice: unserialize(): Error at offset 0 of 3 bytes \r\n```\r\nI don't know if other drivers have similar issues.\r\n",
"comments": [
{
"body": "Managed to reproduce this. Sending in a fix. Also not really sure about other stores.",
"created_at": "2020-02-04T13:04:07Z"
},
{
"body": "Should the complete fix be for the next major release, as considering returning 1 instead of \"1\" be a possible breaking change?",
"created_at": "2020-02-04T13:10:38Z"
},
{
"body": "@halaei I guess this is now completely broken atm and never worked? I sent in a fix here: https://github.com/laravel/framework/pull/31348\r\n\r\nLet me know what you think.",
"created_at": "2020-02-04T13:21:50Z"
},
{
"body": "Came across this today when we tried switching to redis. Some of the stuff in our cache is type sensitive, so when some of the cache keys went from `1` to `\"1\"` the `===` checks failed.\r\n\r\nIt seems this is sort of broken for all numeric strings, since `is_numeric()` is being used, and then skips serializing it. Why not just consistently serialize everything before storing it, like in the file and memcached stores? A quick test shows me that the outcome of `Cache::put('test', 123)` with the cache drivers `file`, `array`, `database`, `apc` and `memcached` all return an integer, but for `redis` I get a string.",
"created_at": "2020-05-16T17:50:58Z"
},
{
"body": "@carestad I agree. These are some reasons for the inconsistency, although I don't think they are good enough:\r\n1. Storing integers without serialization makes it possible to use incr, decr, incrby, and decrby Redis commands to implement Cache::increment() and Cache::decrement() functions.\r\n2. Storing float without serialization makes use of incrbyfloat command possible, altough it is not used in Laravel. So floating point increment is not yet support.\r\n3. (Less important) Storing integers as integer in Redis causes some considerable memory reduction when storing a lot of integers, something near 10x I guess.\r\n\r\nI suggest to update Redis driver to only skip serialization if the data type is int, but not when the data is float or a numeric string. This change probably is a breaking change for some other applications.\r\nSome configuration options may be helpful to make things BC and let users to store floats without serialization as well.",
"created_at": "2020-05-16T19:42:06Z"
},
{
"body": "@halaei Tough one. It all boils down to the fact that redis don't have its own numerical type I suppose.\r\n\r\nBut I was not really aware of this before trying it out. I feel like this should be mentioned in the documentation somewhere, that integers and float types will not be preserved when using redis? Especially since all the other cache providers does this (haven't tried dynamodb and apc yet though so I can't say 100% for that one, but I have tested `file`, `array`, `database` and `memcached`). So switching from anyone of the other cache providers to redis could easily cause problems in type-aware applications.\r\n\r\nWhat about a `force_numeric_serialization` config option that defaults to false, but can be overridden? Either always force-run the value through `serialize()` when setting and `unserialize()` when getting, or force-cast numeric strings to int/float (only when getting). And when that option is set, the increment/decrement functions will need to compute this in PHP instead of using redis' own `INCR`/`DECR`. But I'd much rather have consistency between caching providers than how it is right now.",
"created_at": "2020-05-17T22:38:35Z"
},
{
"body": "Just got burned by this as we switched our cache store from database to redis - suddenly this throws an error on the second call:\r\n\r\n```php\r\nfunction foo(): int\r\n{\r\n return Cache::remember('foo', 60, function() {\r\n return 1;\r\n });\r\n}\r\n```\r\n=> `expected int but got string instead`\r\n\r\nIs there any fix other than manually casting to int everywhere that's the expected type? The fix that closes this issue (#31348) deals with storing `INF` values, but that's not the whole problem here.",
"created_at": "2021-05-24T13:51:45Z"
},
{
"body": "@robin-vendredi\r\n\r\nyou can use PHP’s serialize/unserialize to store type info",
"created_at": "2021-05-24T13:59:12Z"
},
{
"body": "@lptn Thanks for your reply. \r\n\r\nIf I understand it correctly, this would look something like `return serialize(1);`? I would be afraid it might lead to double serialization (esp. if I switch cache driver in future), and I'd hope for a more global solution where I don't have to remember that \"integer needs to be manually serialized each time\" and my code breaks if I forget.\r\n\r\nI could write a custom driver extending the [RedisStore](https://github.com/laravel/framework/blob/8.x/src/Illuminate/Cache/RedisStore.php) to not skip the integer serialization they are doing here: https://github.com/laravel/framework/blob/6718ae61acac3bfb7f88a9769ed74c1e39240861/src/Illuminate/Cache/RedisStore.php#L332-L335\r\n\r\nBut that would have an impact on the `increment`/`decrement` functions too and I'd like to avoid writing my own store. Are there any other solutions?",
"created_at": "2021-05-24T14:09:13Z"
},
{
"body": "Can this be reopened? This inconsistency bug is still present in laravel 8",
"created_at": "2021-09-23T08:09:24Z"
},
{
"body": "Running into this whilst profiling/memory tuning redis, if this is fixed, it would provide a big memory saving:\r\n\r\n> Sets that contain only integers are extremely efficient memory wise. If your set contains strings, try to use integers by mapping string identifiers to integers.\r\n> You can either use enums in your programming language, or you can use a redis hash data structure to map values to integers. Once you switch to integers, Redis will use the IntSet encoding internally.",
"created_at": "2021-12-14T00:59:07Z"
},
{
"body": "Why this is closed when it's not fixed or resolved anyhow? @taylorotwell your PR closed this, not sure if this was mistake or what.",
"created_at": "2022-04-05T11:45:54Z"
}
],
"number": 31345,
"title": "Redis cache store issues on numeric values"
} | {
"body": "Fix the issues in #31345\r\n\r\n```php\r\nCache::put('test', 1);\r\nCache::get('test'); // expected: 1, actual: \"1\"\r\nCache::put('test', 1.0);\r\nCache::get('test'); // expected: 1.0, actual: \"1\"\r\n\r\n// throws an error on the second call\r\nfunction foo(): int\r\n{\r\n return Cache::remember('foo', 60, function() {\r\n return 1;\r\n });\r\n}\r\n```\r\n\r\n## Implement \r\n\r\n- Store raw value of int and float to Redis\r\n- Use \".\" to distinguish int and float\r\n- Serialize other type(including string) before store to Redis\r\n\r\n## BREAKING CHANGES\r\n\r\n- Reading existing numeric values in Redis will be converted from string to int or float\r\n- Increment new stored string value wont work, use int instead\r\n\r\n```php\r\nCache::set('test', '1'); // store \"s:1:\"1\";\" in Redis\r\nCache::increment('test'); // (error) ERR value is not an integer or out of range\r\n```\r\n\r\nTo avoid breaking changes, we can add option like `keepNumeric`/`keepType` ? to enable this feature.\r\n\r\n",
"number": 40801,
"review_comments": [],
"title": "[10.x] Fix Redis store set int value, but get returns string"
} | {
"commits": [
{
"message": "fix Redis store set int value, but get returns string"
},
{
"message": "fix style"
}
],
"files": [
{
"diff": "@@ -327,11 +327,22 @@ public function setPrefix($prefix)\n * Serialize the value.\n *\n * @param mixed $value\n- * @return mixed\n+ * @return int|string\n */\n protected function serialize($value)\n {\n- return is_numeric($value) && ! in_array($value, [INF, -INF]) && ! is_nan($value) ? $value : serialize($value);\n+ if (is_int($value)) {\n+ return $value;\n+ }\n+\n+ if (is_float($value) && ! in_array($value, [\\INF, -\\INF], true) && ! is_nan($value)) {\n+ // Note that float like \"1.0\" will be converted to string \"1\"\n+ $value = (string) $value;\n+ // Append missing \".\", because we use \".\" to detect float (trailing 0 could be ignored)\n+ return str_contains($value, '.') ? $value : ($value.'.');\n+ }\n+\n+ return serialize($value);\n }\n \n /**\n@@ -342,6 +353,10 @@ protected function serialize($value)\n */\n protected function unserialize($value)\n {\n- return is_numeric($value) ? $value : unserialize($value);\n+ if (is_numeric($value)) {\n+ return str_contains($value, '.') ? (float) $value : (int) $value;\n+ }\n+\n+ return unserialize($value);\n }\n }",
"filename": "src/Illuminate/Cache/RedisStore.php",
"status": "modified"
},
{
"diff": "@@ -4,7 +4,9 @@\n \n use Illuminate\\Foundation\\Testing\\Concerns\\InteractsWithRedis;\n use Illuminate\\Support\\Facades\\Cache;\n+use const INF;\n use Orchestra\\Testbench\\TestCase;\n+use stdClass;\n \n class RedisStoreTest extends TestCase\n {\n@@ -24,25 +26,51 @@ protected function tearDown(): void\n $this->tearDownRedis();\n }\n \n- public function testItCanStoreInfinite()\n+ public function testItCanStoreNan()\n {\n Cache::store('redis')->clear();\n \n- $result = Cache::store('redis')->put('foo', INF);\n- $this->assertTrue($result);\n- $this->assertSame(INF, Cache::store('redis')->get('foo'));\n-\n- $result = Cache::store('redis')->put('bar', -INF);\n+ $result = Cache::store('redis')->put('foo', NAN);\n $this->assertTrue($result);\n- $this->assertSame(-INF, Cache::store('redis')->get('bar'));\n+ $this->assertNan(Cache::store('redis')->get('foo'));\n }\n \n- public function testItCanStoreNan()\n+ /**\n+ * @dataProvider valuesDataProvider\n+ */\n+ public function testValues(string $key, $value)\n {\n Cache::store('redis')->clear();\n \n- $result = Cache::store('redis')->put('foo', NAN);\n+ $result = Cache::store('redis')->put($key, $value);\n $this->assertTrue($result);\n- $this->assertNan(Cache::store('redis')->get('foo'));\n+\n+ $cache = Cache::store('redis')->get($key);\n+ if (is_scalar($value)) {\n+ $this->assertSame($value, $cache);\n+ } else {\n+ $this->assertEquals($value, $cache);\n+ }\n+ }\n+\n+ public function valuesDataProvider(): array\n+ {\n+ return [\n+ ['string', 'string'],\n+ ['string-int', '1'],\n+ ['string-float', '1.1'],\n+ ['array', []],\n+ ['bool', true],\n+ ['bool-false', false],\n+ ['int', 1],\n+ ['float', 1.2],\n+ ['float-int', 1.0],\n+ ['float-e', 7E+20],\n+ ['float-ne', 7E-20],\n+ ['float-inf', INF],\n+ ['float-ninf', -INF],\n+ ['null', null],\n+ ['object', new stdClass()],\n+ ];\n }\n }",
"filename": "tests/Integration/Cache/RedisStoreTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.0.0-beta.3\r\n- PHP Version: 8.1.0\r\n\r\n# Description:\r\nIn 9.x, the trimString middleware removes NBSP. #38117\r\nThis is causing the problem. When dealing with multi-byte words (in my case Japanese), we have some problems. A few words are garbled.\r\nWhen I put `だ` or `ム` in the end of text, those words will be garbled.\r\n\r\n## Steps to Reproduce (quick version)\r\n\r\nAdd below to the welcome.blade.php.\r\n```php\r\n<h1>Hello {{ request()->name }}</h1>\r\n```\r\n\r\nAccess the url.\r\nhttp://localhost/?name=やま\r\nhttp://localhost/?name=やまだ\r\n\r\n(Replace `localhost` to your domain. やま or やまだ may be encoded in the URL field of your browser.)\r\n\r\nYou can see やま is ok. But if you add だ, it's not working.\r\n\r\n\r\n\r\n## Steps To Reproduce: (Original version)\r\n[Caution]\r\nYou cannot just copy and paste the below. NBSP is replaced with the normal space.\r\nPlease use NBSP as the second argument of the trim function.\r\nYou can copy NBSP from the real source code. (Please don't copy from the github website.)\r\n\r\n```php\r\n$str = 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらをわがぎぐげござしずぜぞだぢづでどばびぶべぼぱぴぷぺぽ'\r\n . 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラヲワガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ';\r\n\r\n$words = preg_split('//u', $str); // split a string into each words. (This part is not related with the problem)\r\n\r\nforeach ($words as $word) {\r\n echo $word.' '.bin2hex($word).' '.trim($word, \" \").\"<br>\";\r\n}\r\n```\r\n\r\n\r\nI guess the reason is that `だ` is like `e381a0` and `ム` is like `e383a0` and the NBSP is like U+00A0 in Unicode.\r\nSo If I put `だ` in the end of text, the last part of word `a0` is trimmed and the word is garbled.\r\nWe (Japanese) also use chinese characters which I didn't looked into.\r\n\r\n\r\n\r\n\r\n\r\nThank you for reading.\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" --\r\n\r\n>",
"comments": [
{
"body": "Ping @allowing ",
"created_at": "2022-01-24T08:15:05Z"
},
{
"body": "Hey @nshiro , I can't replicate this issue...\r\n\r\nI used an expanded version from your code:\r\n\r\n```php\r\n<?php\r\n\r\n$str = 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらをわがぎぐげござしずぜぞだぢづでどばびぶべぼぱぴぷぺぽ'\r\n . 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラヲワガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ';\r\n\r\n// split a string into each words. (This part is not related with the problem)\r\n$words = preg_split('//u', $str);\r\n\r\n// Maybe try adding this to your code sample\r\necho '<meta charset=\"utf-8\">', PHP_EOL;\r\n\r\necho '<table border=\"1\">', PHP_EOL;\r\n\r\nforeach ($words as $word) {\r\n echo '<tr>', PHP_EOL;\r\n\r\n // raw word\r\n echo '<td>', $word, '</td>', PHP_EOL;\r\n echo '<td>', bin2hex($word), '</td>', PHP_EOL;\r\n\r\n // raw trim\r\n echo '<td>', trim($word), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word)), '</td>', PHP_EOL;\r\n\r\n // trim with just an space\r\n echo '<td>', trim($word, \" \"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \")), '</td>', PHP_EOL;\r\n\r\n // trim as PR #38117\r\n echo '<td>', trim($word, \" \\t\\n\\r\\0\\x0B\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\t\\n\\r\\0\\x0B\")), '</td>', PHP_EOL;\r\n\r\n // trim as I use in my projects\r\n // I add the \\x08 to the default parameter as described into PHP docs\r\n // https://www.php.net/manual/en/function.trim\r\n echo '<td>', trim($word, \" \\n\\r\\t\\v\\x00\\x08\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\n\\r\\t\\v\\x00\\x08\")), '</td>', PHP_EOL;\r\n\r\n\r\n echo '</tr>', PHP_EOL;\r\n}\r\n\r\necho '</table>', PHP_EOL;\r\n```\r\n\r\nI got these results on firefox:\r\n\r\n\r\n\r\n\r\n\r\nAnd these results on chromium:\r\n\r\n\r\n\r\n\r\n\r\nNote I added the `<meta charset=\"utf-8\">` to the script's output (see line 10)\r\n\r\nAlso check if your code editor is saving the file with UTF-8 encoding:\r\n\r\n\r\n\r\n",
"created_at": "2022-01-24T20:20:52Z"
},
{
"body": "@rodrigopedra\r\nThank you for your response and I'm sorry for the inconvenience.\r\nI assume you were using normal space not NBSP.\r\nI updated the comment.\r\n\r\nLooks like NBSP is replaced with the normal space in the github website.\r\nSo please use NBSP as the second argument of the trim function.\r\nYou can copy NBSP from the real source code. (Please don't copy from the github website.)\r\n\r\nPlease check the below. The problem still happens. I used your script (not all).\r\n\r\n\r\n\r\nI also added another version that can be reproduced quickly. Please see the first comment.",
"created_at": "2022-01-25T00:33:47Z"
},
{
"body": "@nshiro thanks for the heads up, maybe when I copied and pasted the code, either my browser, OS or editor converted the NBSP to a regular space.\r\n\r\nSo I was looking into my recent projects and I actually use a newer approach to deal with NBSP. I use `preg_replace` with the unicode modifier:\r\n\r\n~~~php\r\n<?php\r\n\r\n$str = 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらをわがぎぐげござしずぜぞだぢづでどばびぶべぼぱぴぷぺぽ'\r\n . 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラヲワガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ';\r\n\r\n// split a string into each words. (This part is not related with the problem)\r\n$words = preg_split('//u', $str);\r\n\r\n// adding two more test characters\r\n$words[] = ' だ '; // 2x NBSP before, 2x regular spaces after\r\n$words[] = ' だ '; // 2x regular spaces before, 2x NBSP after\r\n$words[] = ' だ '; // NBSP + regular space before and after\r\n\r\n$words[] = ' ム '; // 2x NBSP before, 2x regular spaces after\r\n$words[] = ' ム '; // 2x regular spaces before, 2x NBSP after\r\n$words[] = ' ム '; // NBSP + regular space before and after\r\n\r\n// Maybe try adding this to your code sample\r\necho '<meta charset=\"utf-8\">', PHP_EOL;\r\n\r\necho '<table border=\"1\">', PHP_EOL;\r\n\r\nforeach ($words as $word) {\r\n echo '<tr>', PHP_EOL;\r\n\r\n // raw word\r\n echo '<td>', $word, '</td>', PHP_EOL;\r\n echo '<td>', bin2hex($word), '</td>', PHP_EOL;\r\n\r\n // raw trim\r\n echo '<td>', trim($word), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word)), '</td>', PHP_EOL;\r\n\r\n // trim with just an space\r\n echo '<td>', trim($word, \" \"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \")), '</td>', PHP_EOL;\r\n\r\n // trim as PR #38117\r\n echo '<td>', trim($word, \" \\t\\n\\r\\0\\x0B\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\t\\n\\r\\0\\x0B\")), '</td>', PHP_EOL;\r\n\r\n // trim as I **used** in my projects\r\n // I add the \\x08 to the default parameter as described into PHP docs\r\n // https://www.php.net/manual/en/function.trim\r\n echo '<td>', trim($word, \" \\n\\r\\t\\v\\x00\\x08\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\n\\r\\t\\v\\x00\\x08\")), '</td>', PHP_EOL;\r\n\r\n // transform I now use in my projects\r\n $value = preg_replace('~^\\s+|\\s+$~iu', '', $word);\r\n\r\n echo '<td>', $value, '</td>', PHP_EOL;\r\n echo '<td>', bin2hex($value), '</td>', PHP_EOL;\r\n\r\n echo '</tr>', PHP_EOL;\r\n}\r\n\r\necho '</table>', PHP_EOL;\r\n~~~\r\n\r\nYou can see I added some additional cases to test it better, and the results are these:\r\n\r\n\r\n\r\nI sent PR #40600 to modify the `TrimStrings` middleware to use `preg_replace`",
"created_at": "2022-01-25T02:28:37Z"
},
{
"body": "@rodrigopedra\r\nI tested your script and there was no problem.\r\nI also tested it with some kanji, emojis and other characters and found no problem.\r\nLooks good to me !\r\n\r\nThank you for your support.",
"created_at": "2022-01-25T04:19:19Z"
},
{
"body": "ping @nshiro and @foremtehan \r\n\r\nCould you take a look at my comment on PR #40600 about supporting the word-joiner?\r\n\r\nhttps://github.com/laravel/framework/pull/40600#issuecomment-1021476584\r\n\r\nI didn't want to spam a closed PR to avoid annoying the maintainers.",
"created_at": "2022-01-26T06:22:11Z"
},
{
"body": "@nshiro 哈哈,来自日本的朋友你好。很抱歉今天才看到这个 issue 。我解决`NBSP`的方案太过于简单粗暴。\r\n你看一下这个会不会带来同样的问题: #41949。\r\n\r\nTranslate:\r\n\r\nHaha, hello friends from Japan. Sorry I only saw this issue today. My solution to `NBSP` is too simplistic.\r\nSee if this brings up the same problem: #41949.",
"created_at": "2022-04-13T10:38:57Z"
}
],
"number": 40577,
"title": "Multi-byte word problem with TrimStrings Middleware."
} | {
"body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nPR #38117 introduced the ability to other space unicode characters to the `TrimStrings` middleware.\r\n\r\nAs issue #40577 stated the current implementation conflicts with some other unicode characters which end with the same escape sequence as the NBSP character.\r\n\r\nIn particular these japanese characters:\r\n\r\n- だ (unicode `E381A0`)\r\n- ム (unicode `E383A0`)\r\n\r\nThe implementation from PR #38117 causes the `A0` sequence to be trimmed, which converts the sequence to an invalid one.\r\n\r\nThis PR:\r\n\r\n- Changes the implementation to use `preg_replace` to trim the spaces using the proper modifiers\r\n- Add additional test cases that failed with the previous implementation and passed with the proposed one\r\n\r\n\r\nCloses #40577 ",
"number": 40600,
"review_comments": [],
"title": "[9.x] Handle unicode characters on TrimStrings middleware"
} | {
"commits": [
{
"message": "Handle unicode characters on TrimStrings middleware"
}
],
"files": [
{
"diff": "@@ -53,7 +53,7 @@ protected function transform($key, $value)\n return $value;\n }\n \n- return is_string($value) ? trim($value, \" \\t\\n\\r\\0\\x0B\") : $value;\n+ return is_string($value) ? preg_replace('~^\\s+|\\s+$~iu', '', $value) : $value;\n }\n \n /**",
"filename": "src/Illuminate/Foundation/Http/Middleware/TrimStrings.php",
"status": "modified"
},
{
"diff": "@@ -35,12 +35,20 @@ public function testTrimStringsNBSP()\n $symfonyRequest = new SymfonyRequest([\n // Here has some NBSP, but it still display to space.\n 'abc' => ' 123 ',\n+ 'xyz' => 'だ',\n+ 'foo' => 'ム',\n+ 'bar' => ' だ ',\n+ 'baz' => ' ム ',\n ]);\n $symfonyRequest->server->set('REQUEST_METHOD', 'GET');\n $request = Request::createFromBase($symfonyRequest);\n \n $middleware->handle($request, function (Request $request) {\n $this->assertSame('123', $request->get('abc'));\n+ $this->assertSame('だ', $request->get('xyz'));\n+ $this->assertSame('ム', $request->get('foo'));\n+ $this->assertSame('だ', $request->get('bar'));\n+ $this->assertSame('ム', $request->get('baz'));\n });\n }\n }",
"filename": "tests/Foundation/Http/Middleware/TrimStringsTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 9.0.0-beta.3\r\n- PHP Version: 8.1.0\r\n\r\n# Description:\r\nIn 9.x, the trimString middleware removes NBSP. #38117\r\nThis is causing the problem. When dealing with multi-byte words (in my case Japanese), we have some problems. A few words are garbled.\r\nWhen I put `だ` or `ム` in the end of text, those words will be garbled.\r\n\r\n## Steps to Reproduce (quick version)\r\n\r\nAdd below to the welcome.blade.php.\r\n```php\r\n<h1>Hello {{ request()->name }}</h1>\r\n```\r\n\r\nAccess the url.\r\nhttp://localhost/?name=やま\r\nhttp://localhost/?name=やまだ\r\n\r\n(Replace `localhost` to your domain. やま or やまだ may be encoded in the URL field of your browser.)\r\n\r\nYou can see やま is ok. But if you add だ, it's not working.\r\n\r\n\r\n\r\n## Steps To Reproduce: (Original version)\r\n[Caution]\r\nYou cannot just copy and paste the below. NBSP is replaced with the normal space.\r\nPlease use NBSP as the second argument of the trim function.\r\nYou can copy NBSP from the real source code. (Please don't copy from the github website.)\r\n\r\n```php\r\n$str = 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらをわがぎぐげござしずぜぞだぢづでどばびぶべぼぱぴぷぺぽ'\r\n . 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラヲワガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ';\r\n\r\n$words = preg_split('//u', $str); // split a string into each words. (This part is not related with the problem)\r\n\r\nforeach ($words as $word) {\r\n echo $word.' '.bin2hex($word).' '.trim($word, \" \").\"<br>\";\r\n}\r\n```\r\n\r\n\r\nI guess the reason is that `だ` is like `e381a0` and `ム` is like `e383a0` and the NBSP is like U+00A0 in Unicode.\r\nSo If I put `だ` in the end of text, the last part of word `a0` is trimmed and the word is garbled.\r\nWe (Japanese) also use chinese characters which I didn't looked into.\r\n\r\n\r\n\r\n\r\n\r\nThank you for reading.\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" --\r\n\r\n>",
"comments": [
{
"body": "Ping @allowing ",
"created_at": "2022-01-24T08:15:05Z"
},
{
"body": "Hey @nshiro , I can't replicate this issue...\r\n\r\nI used an expanded version from your code:\r\n\r\n```php\r\n<?php\r\n\r\n$str = 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらをわがぎぐげござしずぜぞだぢづでどばびぶべぼぱぴぷぺぽ'\r\n . 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラヲワガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ';\r\n\r\n// split a string into each words. (This part is not related with the problem)\r\n$words = preg_split('//u', $str);\r\n\r\n// Maybe try adding this to your code sample\r\necho '<meta charset=\"utf-8\">', PHP_EOL;\r\n\r\necho '<table border=\"1\">', PHP_EOL;\r\n\r\nforeach ($words as $word) {\r\n echo '<tr>', PHP_EOL;\r\n\r\n // raw word\r\n echo '<td>', $word, '</td>', PHP_EOL;\r\n echo '<td>', bin2hex($word), '</td>', PHP_EOL;\r\n\r\n // raw trim\r\n echo '<td>', trim($word), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word)), '</td>', PHP_EOL;\r\n\r\n // trim with just an space\r\n echo '<td>', trim($word, \" \"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \")), '</td>', PHP_EOL;\r\n\r\n // trim as PR #38117\r\n echo '<td>', trim($word, \" \\t\\n\\r\\0\\x0B\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\t\\n\\r\\0\\x0B\")), '</td>', PHP_EOL;\r\n\r\n // trim as I use in my projects\r\n // I add the \\x08 to the default parameter as described into PHP docs\r\n // https://www.php.net/manual/en/function.trim\r\n echo '<td>', trim($word, \" \\n\\r\\t\\v\\x00\\x08\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\n\\r\\t\\v\\x00\\x08\")), '</td>', PHP_EOL;\r\n\r\n\r\n echo '</tr>', PHP_EOL;\r\n}\r\n\r\necho '</table>', PHP_EOL;\r\n```\r\n\r\nI got these results on firefox:\r\n\r\n\r\n\r\n\r\n\r\nAnd these results on chromium:\r\n\r\n\r\n\r\n\r\n\r\nNote I added the `<meta charset=\"utf-8\">` to the script's output (see line 10)\r\n\r\nAlso check if your code editor is saving the file with UTF-8 encoding:\r\n\r\n\r\n\r\n",
"created_at": "2022-01-24T20:20:52Z"
},
{
"body": "@rodrigopedra\r\nThank you for your response and I'm sorry for the inconvenience.\r\nI assume you were using normal space not NBSP.\r\nI updated the comment.\r\n\r\nLooks like NBSP is replaced with the normal space in the github website.\r\nSo please use NBSP as the second argument of the trim function.\r\nYou can copy NBSP from the real source code. (Please don't copy from the github website.)\r\n\r\nPlease check the below. The problem still happens. I used your script (not all).\r\n\r\n\r\n\r\nI also added another version that can be reproduced quickly. Please see the first comment.",
"created_at": "2022-01-25T00:33:47Z"
},
{
"body": "@nshiro thanks for the heads up, maybe when I copied and pasted the code, either my browser, OS or editor converted the NBSP to a regular space.\r\n\r\nSo I was looking into my recent projects and I actually use a newer approach to deal with NBSP. I use `preg_replace` with the unicode modifier:\r\n\r\n~~~php\r\n<?php\r\n\r\n$str = 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらをわがぎぐげござしずぜぞだぢづでどばびぶべぼぱぴぷぺぽ'\r\n . 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラヲワガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ';\r\n\r\n// split a string into each words. (This part is not related with the problem)\r\n$words = preg_split('//u', $str);\r\n\r\n// adding two more test characters\r\n$words[] = ' だ '; // 2x NBSP before, 2x regular spaces after\r\n$words[] = ' だ '; // 2x regular spaces before, 2x NBSP after\r\n$words[] = ' だ '; // NBSP + regular space before and after\r\n\r\n$words[] = ' ム '; // 2x NBSP before, 2x regular spaces after\r\n$words[] = ' ム '; // 2x regular spaces before, 2x NBSP after\r\n$words[] = ' ム '; // NBSP + regular space before and after\r\n\r\n// Maybe try adding this to your code sample\r\necho '<meta charset=\"utf-8\">', PHP_EOL;\r\n\r\necho '<table border=\"1\">', PHP_EOL;\r\n\r\nforeach ($words as $word) {\r\n echo '<tr>', PHP_EOL;\r\n\r\n // raw word\r\n echo '<td>', $word, '</td>', PHP_EOL;\r\n echo '<td>', bin2hex($word), '</td>', PHP_EOL;\r\n\r\n // raw trim\r\n echo '<td>', trim($word), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word)), '</td>', PHP_EOL;\r\n\r\n // trim with just an space\r\n echo '<td>', trim($word, \" \"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \")), '</td>', PHP_EOL;\r\n\r\n // trim as PR #38117\r\n echo '<td>', trim($word, \" \\t\\n\\r\\0\\x0B\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\t\\n\\r\\0\\x0B\")), '</td>', PHP_EOL;\r\n\r\n // trim as I **used** in my projects\r\n // I add the \\x08 to the default parameter as described into PHP docs\r\n // https://www.php.net/manual/en/function.trim\r\n echo '<td>', trim($word, \" \\n\\r\\t\\v\\x00\\x08\"), '</td>', PHP_EOL;\r\n echo '<td>', bin2hex(trim($word, \" \\n\\r\\t\\v\\x00\\x08\")), '</td>', PHP_EOL;\r\n\r\n // transform I now use in my projects\r\n $value = preg_replace('~^\\s+|\\s+$~iu', '', $word);\r\n\r\n echo '<td>', $value, '</td>', PHP_EOL;\r\n echo '<td>', bin2hex($value), '</td>', PHP_EOL;\r\n\r\n echo '</tr>', PHP_EOL;\r\n}\r\n\r\necho '</table>', PHP_EOL;\r\n~~~\r\n\r\nYou can see I added some additional cases to test it better, and the results are these:\r\n\r\n\r\n\r\nI sent PR #40600 to modify the `TrimStrings` middleware to use `preg_replace`",
"created_at": "2022-01-25T02:28:37Z"
},
{
"body": "@rodrigopedra\r\nI tested your script and there was no problem.\r\nI also tested it with some kanji, emojis and other characters and found no problem.\r\nLooks good to me !\r\n\r\nThank you for your support.",
"created_at": "2022-01-25T04:19:19Z"
},
{
"body": "ping @nshiro and @foremtehan \r\n\r\nCould you take a look at my comment on PR #40600 about supporting the word-joiner?\r\n\r\nhttps://github.com/laravel/framework/pull/40600#issuecomment-1021476584\r\n\r\nI didn't want to spam a closed PR to avoid annoying the maintainers.",
"created_at": "2022-01-26T06:22:11Z"
},
{
"body": "@nshiro 哈哈,来自日本的朋友你好。很抱歉今天才看到这个 issue 。我解决`NBSP`的方案太过于简单粗暴。\r\n你看一下这个会不会带来同样的问题: #41949。\r\n\r\nTranslate:\r\n\r\nHaha, hello friends from Japan. Sorry I only saw this issue today. My solution to `NBSP` is too simplistic.\r\nSee if this brings up the same problem: #41949.",
"created_at": "2022-04-13T10:38:57Z"
}
],
"number": 40577,
"title": "Multi-byte word problem with TrimStrings Middleware."
} | {
"body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\n\r\nPR #38117 introduced the ability to other space unicode characters to the `TrimStrings` middleware.\r\n\r\nAs issue #40577 stated the current implementation conflicts with some other unicode characters which end with the same escape sequence as the NBSP character.\r\n\r\nIn particular these japanese characters:\r\n\r\n- だ (unicode `E381A0`)\r\n- ム (unicode `E383A0`)\r\n\r\nThe implementation from PR #38117 causes the `A0` sequence to be trimmed, which converts the sequence to an invalid one.\r\n\r\nThis PR:\r\n\r\n- Changes the implementation to use `preg_replace` to trim the spaces using the proper modifiers\r\n- Add additional test cases that failed with the previous implementation and passed with the proposed one\r\n\r\n\r\nCloses #40577 ",
"number": 40596,
"review_comments": [],
"title": "Handle unicode characters on TrimStrings middleware"
} | {
"commits": [
{
"message": "[10.x] Prepare Laravel 10 (#40382)\n\n* 10.x-dev\r\n\r\n* version\r\n\r\n* Update splitter\r\n\r\n* Prepare Laravel 10 components\r\n\r\n* Bump testbench"
},
{
"message": "wip"
},
{
"message": "Merge branch '9.x'"
},
{
"message": "Update CHANGELOG.md"
},
{
"message": "Merge branch '9.x'\n\n# Conflicts:\n#\tCHANGELOG.md"
},
{
"message": "wip"
},
{
"message": "Merge branch '9.x'"
},
{
"message": "Merge branch '9.x'"
},
{
"message": "Merge branch '9.x'"
},
{
"message": "Handle unicode characters on TrimStrings middleware"
}
],
"files": [
{
"diff": "@@ -1,8 +1,8 @@\n-# Release Notes for 9.x\n+# Release Notes for 10.x\n \n-## [Unreleased](https://github.com/laravel/framework/compare/v9.0.0...9.x)\n+## [Unreleased](https://github.com/laravel/framework/compare/v10.0.0..master)\n \n \n-## [v9.0.0 (2022-??-??)](https://github.com/laravel/framework/compare/v8.80.0...v9.0.0)\n+## [v10.0.0 (2022-??-??)](https://github.com/laravel/framework/compare/v9.0.0...master)\n \n-Check the upgrade guide in the [Official Laravel Upgrade Documentation](https://laravel.com/docs/9.x/upgrade). Also you can see some release notes in the [Official Laravel Release Documentation](https://laravel.com/docs/9.x/releases).\n+Check the upgrade guide in the [Official Laravel Upgrade Documentation](https://laravel.com/docs/10.x/upgrade). Also you can see some release notes in the [Official Laravel Release Documentation](https://laravel.com/docs/10.x/releases).",
"filename": "CHANGELOG.md",
"status": "modified"
},
{
"diff": "@@ -10,7 +10,7 @@ then\n exit 1\n fi\n \n-RELEASE_BRANCH=\"9.x\"\n+RELEASE_BRANCH=\"master\"\n CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)\n VERSION=$1\n ",
"filename": "bin/release.sh",
"status": "modified"
},
{
"diff": "@@ -3,7 +3,7 @@\n set -e\n set -x\n \n-CURRENT_BRANCH=\"9.x\"\n+CURRENT_BRANCH=\"master\"\n \n function split()\n {",
"filename": "bin/split.sh",
"status": "modified"
},
{
"diff": "@@ -87,7 +87,7 @@\n \"league/flysystem-ftp\": \"^3.0\",\n \"league/flysystem-sftp-v3\": \"^3.0\",\n \"mockery/mockery\": \"^1.4.4\",\n- \"orchestra/testbench-core\": \"^7.0\",\n+ \"orchestra/testbench-core\": \"^8.0\",\n \"pda/pheanstalk\": \"^4.0\",\n \"phpstan/phpstan\": \"^1.0\",\n \"predis/predis\": \"^1.1.9\",\n@@ -127,7 +127,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {",
"filename": "composer.json",
"status": "modified"
},
{
"diff": "@@ -15,12 +15,12 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/http\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/queue\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/http\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/queue\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -29,13 +29,13 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/console\": \"Required to use the auth:clear-resets command (^9.0).\",\n- \"illuminate/queue\": \"Required to fire login / logout events (^9.0).\",\n- \"illuminate/session\": \"Required to use the session based guard (^9.0).\"\n+ \"illuminate/console\": \"Required to use the auth:clear-resets command (^10.0).\",\n+ \"illuminate/queue\": \"Required to fire login / logout events (^10.0).\",\n+ \"illuminate/session\": \"Required to use the session based guard (^10.0).\"\n },\n \"config\": {\n \"sort-packages\": true",
"filename": "src/Illuminate/Auth/composer.json",
"status": "modified"
},
{
"diff": "@@ -17,11 +17,11 @@\n \"php\": \"^8.0.2\",\n \"ext-json\": \"*\",\n \"psr/log\": \"^1.0|^2.0|^3.0\",\n- \"illuminate/bus\": \"^9.0\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/queue\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/bus\": \"^10.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/queue\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -30,7 +30,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {",
"filename": "src/Illuminate/Broadcasting/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/pipeline\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/pipeline\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -27,7 +27,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {",
"filename": "src/Illuminate/Bus/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"provide\": {\n \"psr/simple-cache-implementation\": \"1.0|2.0|3.0\"\n@@ -30,14 +30,14 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {\n \"ext-memcached\": \"Required to use the memcache cache driver.\",\n- \"illuminate/database\": \"Required to use the database cache driver (^9.0).\",\n- \"illuminate/filesystem\": \"Required to use the file cache driver (^9.0).\",\n- \"illuminate/redis\": \"Required to use the redis cache driver (^9.0).\",\n+ \"illuminate/database\": \"Required to use the database cache driver (^10.0).\",\n+ \"illuminate/filesystem\": \"Required to use the file cache driver (^10.0).\",\n+ \"illuminate/redis\": \"Required to use the redis cache driver (^10.0).\",\n \"symfony/cache\": \"Required to use PSR-6 cache bridge (^6.0).\"\n },\n \"config\": {",
"filename": "src/Illuminate/Cache/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,9 +15,9 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/conditionable\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\"\n+ \"illuminate/conditionable\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -29,7 +29,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {",
"filename": "src/Illuminate/Collections/composer.json",
"status": "modified"
},
{
"diff": "@@ -23,7 +23,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Conditionable/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\"\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Config/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"symfony/console\": \"^6.0\",\n \"symfony/process\": \"^6.0\"\n },\n@@ -29,16 +29,16 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {\n \"dragonmantank/cron-expression\": \"Required to use scheduler (^3.1).\",\n \"guzzlehttp/guzzle\": \"Required to use the ping methods on schedules (^7.2).\",\n- \"illuminate/bus\": \"Required to use the scheduled job dispatcher (^9.0).\",\n- \"illuminate/container\": \"Required to use the scheduler (^9.0).\",\n- \"illuminate/filesystem\": \"Required to use the generator command (^9.0).\",\n- \"illuminate/queue\": \"Required to use closures for scheduled jobs (^9.0).\"\n+ \"illuminate/bus\": \"Required to use the scheduled job dispatcher (^10.0).\",\n+ \"illuminate/container\": \"Required to use the scheduler (^10.0).\",\n+ \"illuminate/filesystem\": \"Required to use the generator command (^10.0).\",\n+ \"illuminate/queue\": \"Required to use closures for scheduled jobs (^10.0).\"\n },\n \"config\": {\n \"sort-packages\": true",
"filename": "src/Illuminate/Console/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,7 +15,7 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n \"psr/container\": \"^1.1.1|^2.0.1\"\n },\n \"provide\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Container/composer.json",
"status": "modified"
},
{
"diff": "@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Contracts/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"symfony/http-foundation\": \"^6.0\",\n \"symfony/http-kernel\": \"^6.0\"\n },\n@@ -29,7 +29,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Cookie/composer.json",
"status": "modified"
},
{
"diff": "@@ -17,11 +17,11 @@\n \"require\": {\n \"php\": \"^8.0.2\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/container\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/container\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"symfony/console\": \"^6.0\"\n },\n \"autoload\": {\n@@ -31,16 +31,16 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {\n \"doctrine/dbal\": \"Required to rename columns and drop SQLite columns (^2.13.3|^3.1.4).\",\n \"fakerphp/faker\": \"Required to use the eloquent factory builder (^1.9.1).\",\n- \"illuminate/console\": \"Required to use the database commands (^9.0).\",\n- \"illuminate/events\": \"Required to use the observers with Eloquent (^9.0).\",\n- \"illuminate/filesystem\": \"Required to use the migrations (^9.0).\",\n- \"illuminate/pagination\": \"Required to paginate the result set (^9.0).\",\n+ \"illuminate/console\": \"Required to use the database commands (^10.0).\",\n+ \"illuminate/events\": \"Required to use the observers with Eloquent (^10.0).\",\n+ \"illuminate/filesystem\": \"Required to use the migrations (^10.0).\",\n+ \"illuminate/pagination\": \"Required to paginate the result set (^10.0).\",\n \"symfony/finder\": \"Required to use Eloquent model factories (^6.0).\"\n },\n \"config\": {",
"filename": "src/Illuminate/Database/composer.json",
"status": "modified"
},
{
"diff": "@@ -18,8 +18,8 @@\n \"ext-json\": \"*\",\n \"ext-mbstring\": \"*\",\n \"ext-openssl\": \"*\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Encryption/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,12 +15,12 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/bus\": \"^9.0\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/container\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/bus\": \"^10.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/container\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -32,7 +32,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Events/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"symfony/finder\": \"^6.0\"\n },\n \"autoload\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {",
"filename": "src/Illuminate/Filesystem/composer.json",
"status": "modified"
},
{
"diff": "@@ -35,7 +35,7 @@ class Application extends Container implements ApplicationContract, CachesConfig\n *\n * @var string\n */\n- const VERSION = '9.x-dev';\n+ const VERSION = '10.x-dev';\n \n /**\n * The base path for the Laravel installation.",
"filename": "src/Illuminate/Foundation/Application.php",
"status": "modified"
},
{
"diff": "@@ -53,7 +53,7 @@ protected function transform($key, $value)\n return $value;\n }\n \n- return is_string($value) ? trim($value, \" \\t\\n\\r\\0\\x0B\") : $value;\n+ return is_string($value) ? preg_replace('~^\\s+|\\s+$~iu', '', $value) : $value;\n }\n \n /**",
"filename": "src/Illuminate/Foundation/Http/Middleware/TrimStrings.php",
"status": "modified"
},
{
"diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Hashing/composer.json",
"status": "modified"
},
{
"diff": "@@ -16,10 +16,10 @@\n \"require\": {\n \"php\": \"^8.0.2\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/session\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/session\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"symfony/http-foundation\": \"^6.0\",\n \"symfony/http-kernel\": \"^6.0\",\n \"symfony/mime\": \"^6.0\"\n@@ -35,7 +35,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Http/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"monolog/monolog\": \"^2.0\"\n },\n \"autoload\": {\n@@ -26,7 +26,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Log/composer.json",
"status": "modified"
},
{
"diff": "@@ -23,7 +23,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Macroable/composer.json",
"status": "modified"
},
{
"diff": "@@ -16,11 +16,11 @@\n \"require\": {\n \"php\": \"^8.0.2\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/container\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/macroable\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/container\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/macroable\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"league/commonmark\": \"^2.0.2\",\n \"psr/log\": \"^1.0|^2.0|^3.0\",\n \"symfony/mailer\": \"^6.0\",\n@@ -33,7 +33,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {",
"filename": "src/Illuminate/Mail/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,15 +15,15 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/broadcasting\": \"^9.0\",\n- \"illuminate/bus\": \"^9.0\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/container\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/filesystem\": \"^9.0\",\n- \"illuminate/mail\": \"^9.0\",\n- \"illuminate/queue\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/broadcasting\": \"^10.0\",\n+ \"illuminate/bus\": \"^10.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/container\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/filesystem\": \"^10.0\",\n+ \"illuminate/mail\": \"^10.0\",\n+ \"illuminate/queue\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -32,11 +32,11 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/database\": \"Required to use the database transport (^9.0).\"\n+ \"illuminate/database\": \"Required to use the database transport (^10.0).\"\n },\n \"config\": {\n \"sort-packages\": true",
"filename": "src/Illuminate/Notifications/composer.json",
"status": "modified"
},
{
"diff": "@@ -16,9 +16,9 @@\n \"require\": {\n \"php\": \"^8.0.2\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -27,7 +27,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Pagination/composer.json",
"status": "modified"
},
{
"diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^8.0.2\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\"\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"config\": {",
"filename": "src/Illuminate/Pipeline/composer.json",
"status": "modified"
},
{
"diff": "@@ -16,14 +16,14 @@\n \"require\": {\n \"php\": \"^8.0.2\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^9.0\",\n- \"illuminate/console\": \"^9.0\",\n- \"illuminate/container\": \"^9.0\",\n- \"illuminate/contracts\": \"^9.0\",\n- \"illuminate/database\": \"^9.0\",\n- \"illuminate/filesystem\": \"^9.0\",\n- \"illuminate/pipeline\": \"^9.0\",\n- \"illuminate/support\": \"^9.0\",\n+ \"illuminate/collections\": \"^10.0\",\n+ \"illuminate/console\": \"^10.0\",\n+ \"illuminate/container\": \"^10.0\",\n+ \"illuminate/contracts\": \"^10.0\",\n+ \"illuminate/database\": \"^10.0\",\n+ \"illuminate/filesystem\": \"^10.0\",\n+ \"illuminate/pipeline\": \"^10.0\",\n+ \"illuminate/support\": \"^10.0\",\n \"laravel/serializable-closure\": \"^1.0\",\n \"ramsey/uuid\": \"^4.2.2\",\n \"symfony/process\": \"^6.0\"\n@@ -35,14 +35,14 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"9.x-dev\"\n+ \"dev-master\": \"10.x-dev\"\n }\n },\n \"suggest\": {\n \"ext-pcntl\": \"Required to use all features of the queue worker.\",\n \"ext-posix\": \"Required to use all features of the queue worker.\",\n \"aws/aws-sdk-php\": \"Required to use the SQS queue driver and DynamoDb failed job storage (^3.198.1).\",\n- \"illuminate/redis\": \"Required to use the Redis queue driver (^9.0).\",\n+ \"illuminate/redis\": \"Required to use the Redis queue driver (^10.0).\",\n \"pda/pheanstalk\": \"Required to use the Beanstalk queue driver (^4.0).\"\n },\n \"config\": {",
"filename": "src/Illuminate/Queue/composer.json",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.78.1\r\n- PHP Version: 7.4, 8.0\r\n\r\n### Description:\r\n\r\n`php artisan make:policy` will produce invalid output, similar to what's been reported [here](https://github.com/laravel/framework/issues/32647), [here](https://github.com/laravel/framework/issues/32397) and [here](https://github.com/laravel/framework/issues/21117) (missing user class) if a non-default `auth.providers.users` configuration is in place.\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n\r\n1. `composer create-project laravel/laravel`\r\n2. Change the user provider configuration. E.G: \r\n```php\r\n// config/auth.php\r\n// ...\r\n 'providers' => [\r\n 'users' => [\r\n 'driver' => 'database',\r\n 'table' => 'users',\r\n ],\r\n ],\r\n// ...\r\n```\r\n3. `php artisan make:policy CommentPolicy --model=Comment`\r\n\r\nNote the generated code in Policies: it is missing the User class and is invalid. \r\n\r\nI realized this happens when the provider configuration is missing the `model` key, which was my case too (except I had a custom driver, and I never needed the `model` key).\r\n\r\n### Expected behaviour\r\n\r\nThe `make:policy` command throws an error if it needs explicit user class configuration or otherwise inserts a default user class.\r\n",
"comments": [
{
"body": "Just tested it with a new Laravel Project:\r\n\r\n```\r\n'providers' => [\r\n //'users' => [\r\n // 'driver' => 'eloquent',\r\n // 'model' => App\\Models\\User::class,\r\n //],\r\n\r\n 'users' => [\r\n 'driver' => 'database',\r\n 'table' => 'users',\r\n ],\r\n ],\r\n```\r\n\r\nOutput:\r\n```\r\n\r\n❯ php artisan make:policy CommentPolicy --model=Comment\r\nPolicy created successfully.\r\n```",
"created_at": "2022-01-11T17:34:10Z"
},
{
"body": "@hmennen90 check the generated policy code.",
"created_at": "2022-01-11T17:35:39Z"
},
{
"body": "The Target Models are in use Statements using App\\Models Namespace in both cases: -m and --model\r\n\r\nIf no Model is specified, there is a blank Policy created\r\n\r\n```\r\nuse App\\Models\\Comment;\r\nuse App\\Models\\User;\r\nuse Illuminate\\Auth\\Access\\HandlesAuthorization;\r\n```",
"created_at": "2022-01-11T17:43:28Z"
},
{
"body": "hmm i try it on php 8.0 - i'm currently on 8.1.1\r\n",
"created_at": "2022-01-11T17:44:03Z"
},
{
"body": "Results on PHP8.0 and PHP7.4 are same as at PHP8.1.1\r\n\r\nMaybe anyone else can reproduce your issue?",
"created_at": "2022-01-11T17:47:06Z"
},
{
"body": "@slavicd command back ;-) Can now confirm your issue also on PHP 8.1.1 - had the config cached...\r\n\r\nDid you mean the following Output?\r\n\r\n```\r\nnamespace App\\Policies;\r\n\r\nuse App\\Models\\Comment;\r\nuse Illuminate\\Auth\\Access\\HandlesAuthorization;\r\nuse ;\r\n\r\nclass CommentPolicy\r\n{\r\n use HandlesAuthorization;\r\n\r\n /**\r\n * Determine whether the user can view any models.\r\n *\r\n * @param \\ $\r\n * @return \\Illuminate\\Auth\\Access\\Response|bool\r\n */\r\n public function viewAny( $)\r\n {\r\n //\r\n }\r\n```",
"created_at": "2022-01-11T17:51:54Z"
},
{
"body": "You're changing the guard to one that doesn't have a model. Then it's normal that you'll get an error. A policy always requires a model.",
"created_at": "2022-01-11T19:00:42Z"
},
{
"body": "@driesvints the command is generating invalid code. The problem is that **I am not getting an error**. The fact that I have a custom user provider is not documented anywhere as related to this, and even if it were, spitting out an error or warning or an explanatory message all seem more appropriate than generating a half-stub that is really hard to decode.",
"created_at": "2022-01-11T19:27:22Z"
},
{
"body": "@slavicd ah I see what you mean. What would need to happen here is that the `if (! $model) {` throws an exception I think instead of the stub. Because a model is clearly required here.",
"created_at": "2022-01-11T19:35:02Z"
},
{
"body": "Precisely. I'll try to write a PR now. ",
"created_at": "2022-01-11T19:44:53Z"
}
],
"number": 40345,
"title": "Artisan command make:policy generates invalid policy code with a non-default user provider configuration"
} | {
"body": "If the model config key is not present in `auth.providers.users` the `make:policy` command will silently spit out some very poor stub.\r\n\r\nFixes: #40345",
"number": 40348,
"review_comments": [],
"title": "[8.x] Throws an error upon make:policy if no model class is configured"
} | {
"commits": [
{
"message": "Fixes issue #40345"
},
{
"message": "Addresses coding style complaint."
},
{
"message": "Update PolicyMakeCommand.php"
},
{
"message": "Update PolicyMakeCommand.php"
},
{
"message": "use default user model"
}
],
"files": [
{
"diff": "@@ -85,6 +85,10 @@ protected function userProviderModel()\n throw new LogicException('The ['.$guard.'] guard is not defined in your \"auth\" configuration file.');\n }\n \n+ if (! $config->get('auth.providers.'.$guardProvider.'.model')) {\n+ return 'App\\\\Models\\\\User';\n+ }\n+\n return $config->get(\n 'auth.providers.'.$guardProvider.'.model'\n );",
"filename": "src/Illuminate/Foundation/Console/PolicyMakeCommand.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.78.1\r\n- PHP Version: 7.4, 8.0\r\n\r\n### Description:\r\n\r\n`php artisan make:policy` will produce invalid output, similar to what's been reported [here](https://github.com/laravel/framework/issues/32647), [here](https://github.com/laravel/framework/issues/32397) and [here](https://github.com/laravel/framework/issues/21117) (missing user class) if a non-default `auth.providers.users` configuration is in place.\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n\r\n1. `composer create-project laravel/laravel`\r\n2. Change the user provider configuration. E.G: \r\n```php\r\n// config/auth.php\r\n// ...\r\n 'providers' => [\r\n 'users' => [\r\n 'driver' => 'database',\r\n 'table' => 'users',\r\n ],\r\n ],\r\n// ...\r\n```\r\n3. `php artisan make:policy CommentPolicy --model=Comment`\r\n\r\nNote the generated code in Policies: it is missing the User class and is invalid. \r\n\r\nI realized this happens when the provider configuration is missing the `model` key, which was my case too (except I had a custom driver, and I never needed the `model` key).\r\n\r\n### Expected behaviour\r\n\r\nThe `make:policy` command throws an error if it needs explicit user class configuration or otherwise inserts a default user class.\r\n",
"comments": [
{
"body": "Just tested it with a new Laravel Project:\r\n\r\n```\r\n'providers' => [\r\n //'users' => [\r\n // 'driver' => 'eloquent',\r\n // 'model' => App\\Models\\User::class,\r\n //],\r\n\r\n 'users' => [\r\n 'driver' => 'database',\r\n 'table' => 'users',\r\n ],\r\n ],\r\n```\r\n\r\nOutput:\r\n```\r\n\r\n❯ php artisan make:policy CommentPolicy --model=Comment\r\nPolicy created successfully.\r\n```",
"created_at": "2022-01-11T17:34:10Z"
},
{
"body": "@hmennen90 check the generated policy code.",
"created_at": "2022-01-11T17:35:39Z"
},
{
"body": "The Target Models are in use Statements using App\\Models Namespace in both cases: -m and --model\r\n\r\nIf no Model is specified, there is a blank Policy created\r\n\r\n```\r\nuse App\\Models\\Comment;\r\nuse App\\Models\\User;\r\nuse Illuminate\\Auth\\Access\\HandlesAuthorization;\r\n```",
"created_at": "2022-01-11T17:43:28Z"
},
{
"body": "hmm i try it on php 8.0 - i'm currently on 8.1.1\r\n",
"created_at": "2022-01-11T17:44:03Z"
},
{
"body": "Results on PHP8.0 and PHP7.4 are same as at PHP8.1.1\r\n\r\nMaybe anyone else can reproduce your issue?",
"created_at": "2022-01-11T17:47:06Z"
},
{
"body": "@slavicd command back ;-) Can now confirm your issue also on PHP 8.1.1 - had the config cached...\r\n\r\nDid you mean the following Output?\r\n\r\n```\r\nnamespace App\\Policies;\r\n\r\nuse App\\Models\\Comment;\r\nuse Illuminate\\Auth\\Access\\HandlesAuthorization;\r\nuse ;\r\n\r\nclass CommentPolicy\r\n{\r\n use HandlesAuthorization;\r\n\r\n /**\r\n * Determine whether the user can view any models.\r\n *\r\n * @param \\ $\r\n * @return \\Illuminate\\Auth\\Access\\Response|bool\r\n */\r\n public function viewAny( $)\r\n {\r\n //\r\n }\r\n```",
"created_at": "2022-01-11T17:51:54Z"
},
{
"body": "You're changing the guard to one that doesn't have a model. Then it's normal that you'll get an error. A policy always requires a model.",
"created_at": "2022-01-11T19:00:42Z"
},
{
"body": "@driesvints the command is generating invalid code. The problem is that **I am not getting an error**. The fact that I have a custom user provider is not documented anywhere as related to this, and even if it were, spitting out an error or warning or an explanatory message all seem more appropriate than generating a half-stub that is really hard to decode.",
"created_at": "2022-01-11T19:27:22Z"
},
{
"body": "@slavicd ah I see what you mean. What would need to happen here is that the `if (! $model) {` throws an exception I think instead of the stub. Because a model is clearly required here.",
"created_at": "2022-01-11T19:35:02Z"
},
{
"body": "Precisely. I'll try to write a PR now. ",
"created_at": "2022-01-11T19:44:53Z"
}
],
"number": 40345,
"title": "Artisan command make:policy generates invalid policy code with a non-default user provider configuration"
} | {
"body": "As issued in #40345 this is a first idea to solve this Problem by return the default value of model Key in auth.php['providers']['users']['model'] using database instead of eloquent.",
"number": 40346,
"review_comments": [],
"title": "[8.x] Return Default User::class FQCN if no model key is defined in config"
} | {
"commits": [
{
"message": "Return Default User::class FQCN if no model key is defined in auth.providers.{$guardProvider}.model as issued in https://github.com/laravel/framework/issues/40345"
},
{
"message": "Style CI"
},
{
"message": "Merge branch 'laravel:8.x' into issues/add-default-model-if-no-model-is-defined"
},
{
"message": "Return Default User::class FQCN if no model key is defined in auth.providers.{$guardProvider}.model as issued in https://github.com/laravel/framework/issues/40345"
},
{
"message": "Style CI"
},
{
"message": "Merge remote-tracking branch 'origin/issues/add-default-model-if-no-model-is-defined' into issues/add-default-model-if-no-model-is-defined"
}
],
"files": [
{
"diff": "@@ -87,7 +87,7 @@ protected function userProviderModel()\n \n return $config->get(\n 'auth.providers.'.$guardProvider.'.model'\n- );\n+ ) ?? 'App\\\\Models\\\\User';\n }\n \n /**",
"filename": "src/Illuminate/Foundation/Console/PolicyMakeCommand.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.78.1\r\n- PHP Version: 8.1.0\r\n- Database Driver & Version: MySQL 8\r\n\r\n### Description:\r\n\r\n#40119 introduced an improvement for handling custom Doctrine types. But for some people it broke the test suites. (https://github.com/laravel/framework/pull/40119#issuecomment-1005854737 and https://github.com/laravel/framework/pull/40119#issuecomment-1006906061)\r\n\r\nFor sequential test runs issue happens when there is only the `dbal` array in `config/database.php` And the issue is gone when adding `DB::registerDoctrineType call` to `AppServiceProvider`. Which is not a good solution because it causes the application to make DB connection while the app is booting.\r\n\r\nFor parallel test runs issue happens in both cases.\r\n\r\n### Steps To Reproduce:\r\n\r\n[This](https://github.com/canvural/doctrine-type-bug) repo shows the bug. \r\n",
"comments": [
{
"body": "@canvural Thank you for creating an issue out of our previous discussion!\r\n\r\n> And the issue is gone when adding DB::registerDoctrineType call to AppServiceProvider.\r\n\r\nThis only works for sequential test runners. As soon as you run `php artisan test --parallel` both ways of custom DBAL type registration are broken.",
"created_at": "2022-01-07T13:52:37Z"
},
{
"body": "@bakerkretzmar @TomHAnderson if we can't find a solution right now it might be best that we revert the PR.",
"created_at": "2022-01-07T13:56:10Z"
},
{
"body": "@canvural thanks a lot for reproducing it in a repo, I'll dig into this right now. @driesvints agreed, I can do that later today if we can't figure this out.",
"created_at": "2022-01-07T14:44:20Z"
},
{
"body": "I've been working with @bakerkretzmar all day. I think his PR #40303 addresses 1) problems with running unit tests in series and 2) accounts for unit tests in parallel and makes concessions for them.\r\n\r\nI'm not certain parallel testing is 100% because I've been unable to run such tests locally. I don't feel reverting PR #40119 is the right move.",
"created_at": "2022-01-07T21:34:45Z"
}
],
"number": 40297,
"title": "#40119 broke how `dbal` array in `config/database.php` is handled."
} | {
"body": "**TLDR:** this PR closes #40297 by only registering custom Doctrine type mappings on a Doctrine connection after that connection is created (as opposed to creating one to register them).\r\n\r\n### Context\r\n\r\nMy and @TomHAnderson's original PR, #40119, created an issue with tests where way too many database connections would be created. We were manually creating a database connection to register the custom type mappings, which caused database connections to be created every time the app boots, and dozens of unnecessary connections to be created when tests are run in parallel.\r\n\r\nI'm still not entirely sure why all those connections stick around, I tried manually closing/destroying them through Doctrine and that didn't seem to work.",
"number": 40303,
"review_comments": [
{
"body": "I've kept this whole `registerDoctrineType` method for backwards compatibility but it can be removed in Laravel 9 because the same method on the DatabaseManager class replaces it. I'll PR that today too.",
"created_at": "2022-01-07T19:28:21Z"
}
],
"title": "[8.x] Fix Doctrine type mappings creating too many connections"
} | {
"commits": [
{
"message": "Only register type mappings after Doctrine connection is created"
},
{
"message": "Fix type mapping"
},
{
"message": "Fix"
},
{
"message": "Fix Builder"
},
{
"message": "Remove import"
},
{
"message": "Pass type through to connection"
},
{
"message": "Update DatabaseManager.php"
}
],
"files": [
{
"diff": "@@ -177,6 +177,13 @@ class Connection implements ConnectionInterface\n */\n protected $doctrineConnection;\n \n+ /**\n+ * Type mappings that should be registered with new Doctrine connections.\n+ *\n+ * @var array\n+ */\n+ protected $doctrineTypeMappings = [];\n+\n /**\n * The connection resolvers.\n *\n@@ -1007,6 +1014,12 @@ public function getDoctrineConnection()\n 'driver' => method_exists($driver, 'getName') ? $driver->getName() : null,\n 'serverVersion' => $this->getConfig('server_version'),\n ]), $driver);\n+\n+ foreach ($this->doctrineTypeMappings as $name => $type) {\n+ $this->doctrineConnection\n+ ->getDatabasePlatform()\n+ ->registerDoctrineTypeMapping($type, $name);\n+ }\n }\n \n return $this->doctrineConnection;\n@@ -1035,9 +1048,7 @@ public function registerDoctrineType(string $class, string $name, string $type):\n Type::addType($name, $class);\n }\n \n- $this->getDoctrineSchemaManager()\n- ->getDatabasePlatform()\n- ->registerDoctrineTypeMapping($type, $name);\n+ $this->doctrineTypeMappings[$name] = $type;\n }\n \n /**",
"filename": "src/Illuminate/Database/Connection.php",
"status": "modified"
},
{
"diff": "@@ -2,12 +2,14 @@\n \n namespace Illuminate\\Database;\n \n+use Doctrine\\DBAL\\Types\\Type;\n use Illuminate\\Database\\Connectors\\ConnectionFactory;\n use Illuminate\\Support\\Arr;\n use Illuminate\\Support\\ConfigurationUrlParser;\n use Illuminate\\Support\\Str;\n use InvalidArgumentException;\n use PDO;\n+use RuntimeException;\n \n /**\n * @mixin \\Illuminate\\Database\\Connection\n@@ -49,6 +51,13 @@ class DatabaseManager implements ConnectionResolverInterface\n */\n protected $reconnector;\n \n+ /**\n+ * The custom Doctrine column types.\n+ *\n+ * @var array\n+ */\n+ protected $doctrineTypes = [];\n+\n /**\n * Create a new database manager instance.\n *\n@@ -207,16 +216,46 @@ protected function setPdoForType(Connection $connection, $type = null)\n }\n \n /**\n- * Register custom Doctrine types from the configuration with the connection.\n+ * Register custom Doctrine types with the connection.\n *\n * @param \\Illuminate\\Database\\Connection $connection\n * @return void\n */\n protected function registerConfiguredDoctrineTypes(Connection $connection): void\n {\n foreach ($this->app['config']->get('database.dbal.types', []) as $name => $class) {\n- $connection->registerDoctrineType($class, $name, $name);\n+ $this->registerDoctrineType($class, $name, $name);\n+ }\n+\n+ foreach ($this->doctrineTypes as $name => [$type, $class]) {\n+ $connection->registerDoctrineType($class, $name, $type);\n+ }\n+ }\n+\n+ /**\n+ * Register a custom Doctrine type.\n+ *\n+ * @param string $class\n+ * @param string $name\n+ * @param string $type\n+ * @return void\n+ *\n+ * @throws \\Doctrine\\DBAL\\DBALException\n+ * @throws \\RuntimeException\n+ */\n+ public function registerDoctrineType(string $class, string $name, string $type): void\n+ {\n+ if (! class_exists('Doctrine\\DBAL\\Connection')) {\n+ throw new RuntimeException(\n+ 'Registering a custom Doctrine type requires Doctrine DBAL (doctrine/dbal).'\n+ );\n }\n+\n+ if (! Type::hasType($name)) {\n+ Type::addType($name, $class);\n+ }\n+\n+ $this->doctrineTypes[$name] = [$type, $class];\n }\n \n /**",
"filename": "src/Illuminate/Database/DatabaseManager.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 8.78.1\r\n- PHP Version: 8.0.13\r\n- Database Driver & Version: MySQL 8.0.27\r\n\r\n### Description:\r\n\r\nI noticed wrong data being returned from the database when using cursor pagination on a hasManyThrough relationship.\r\n\r\nBy default (without cursor pagination), `hasManyThrough` generates this query:\r\n\r\n\r\nBut when using cursor pagination, it uses `SELECT *` (instead of `SELECT table.*`) along with `INNER JOIN` which ends up mixing up values from both tables:\r\n\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Create a hasManyThrough relationship. (I used the example on [this page](https://laravel.com/docs/8.x/eloquent-relationships#has-many-through)).\r\n2. Make sure the intermediate and final tables have a column with the same name (like `uuid`). \r\n3. Run `cursorPaginate` on the `hasManyThrough` relationship and dump the model's uuid (cursorPaginate()->first()->uuid), and you'll see that it put a value from the intermediate table instead of the value in the final table.",
"comments": [
{
"body": "Heya, thanks for reporting.\r\n\r\nWe'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue as separate commits on the main/master branch and share the repository here? Please make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com) properly set up.\r\n\r\n```bash\r\nlaravel new bug-report --github=\"--public\"\r\n```\r\n\r\nPlease do not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.\r\n\r\nThanks!\r\n\r\nPS. I realise you have created the repo already but because you've committed all your changes in the initial commit it's hard for me to debug this. Please recreate the repo with the above command.",
"created_at": "2022-01-07T11:47:26Z"
},
{
"body": "Done: https://github.com/paulandroshchuk/bug-report\r\n\r\n@driesvints ",
"created_at": "2022-01-07T12:41:15Z"
},
{
"body": "Hey @paulandroshchuk, thanks for that. I sent in a PR that should fix this: https://github.com/laravel/framework/pull/40300",
"created_at": "2022-01-07T15:01:22Z"
}
],
"number": 40270,
"title": "Cursor pagination does not work properly on a hasManyThrough relationship."
} | {
"body": "Fixes #40270\n",
"number": 40300,
"review_comments": [],
"title": "[8.x] Fix cursor pagination with HasManyThrough"
} | {
"commits": [
{
"message": "Fix cursor pagination with HasManyThrough"
}
],
"files": [
{
"diff": "@@ -431,6 +431,22 @@ public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'p\n return $this->query->simplePaginate($perPage, $columns, $pageName, $page);\n }\n \n+ /**\n+ * Paginate the given query into a cursor paginator.\n+ *\n+ * @param int|null $perPage\n+ * @param array $columns\n+ * @param string $cursorName\n+ * @param string|null $cursor\n+ * @return \\Illuminate\\Contracts\\Pagination\\CursorPaginator\n+ */\n+ public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null)\n+ {\n+ $this->query->addSelect($this->shouldSelect($columns));\n+\n+ return $this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor);\n+ }\n+\n /**\n * Set the select clause for the relation query.\n *",
"filename": "src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 5.2 and later\r\n\r\n### Description:\r\nI believe that the fix on this [issue](https://github.com/laravel/framework/issues/14647) should not have been approved. The rules now only supports integer values. And this does not match the description in the documentation: \"The field under validation **must be numeric** and must have an exact length of value.\"\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n<?php\r\n\r\n$validator = Validator::make(\r\n ['fractional_value' => 1.2],\r\n ['fractional_value' => 'digits_between:1,10']\r\n);\r\n$validator->errors()->first(); // The fractional value must be between 1 and 10 digits.\r\n",
"comments": [
{
"body": "Thanks. I've attempted a PR here: https://github.com/laravel/framework/pull/40278",
"created_at": "2022-01-06T14:20:29Z"
},
{
"body": "We've merged this and it'll be released next Tuesday. Thanks for reporting.",
"created_at": "2022-01-06T14:40:01Z"
}
],
"number": 40264,
"title": "Rules digits and digits_between don't work with fractional numbers"
} | {
"body": "At the moment the `digits_between` validation rule didn't validate digits with fractions properly. #14650 already added support for special numbers with scientific notation but fractions weren't supported until now. I believe it's expected to also accommodate for digits with fractions and not just integers.\r\n\r\nFixes #40264",
"number": 40278,
"review_comments": [],
"title": "[6.x] Fix digits_between with fractions"
} | {
"commits": [
{
"message": "Fix digits_between with fractions"
}
],
"files": [
{
"diff": "@@ -486,7 +486,7 @@ public function validateDigitsBetween($attribute, $value, $parameters)\n \n $length = strlen((string) $value);\n \n- return ! preg_match('/[^0-9]/', $value)\n+ return ! preg_match('/[^0-9.]/', $value)\n && $length >= $parameters[0] && $length <= $parameters[1];\n }\n ",
"filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php",
"status": "modified"
},
{
"diff": "@@ -1767,6 +1767,12 @@ public function testValidateDigits()\n \n $v = new Validator($trans, ['foo' => '+12.3'], ['foo' => 'digits_between:1,6']);\n $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, ['foo' => '1.2'], ['foo' => 'digits_between:1,10']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['foo' => '0.9876'], ['foo' => 'digits_between:1,5']);\n+ $this->assertTrue($v->fails());\n }\n \n public function testValidateSize()",
"filename": "tests/Validation/ValidationValidatorTest.php",
"status": "modified"
}
]
} |
{
"body": "I'm using the new version of `Attribute Cast` in the Laravel version: 8.77 but showed this error when logged in authorization with guard admin \n\r\n- Laravel Version: 8.77.1\r\n- PHP Version: 8.0\r\n\r\n### Error:\r\n\r\n\r\n### Model Admin:\r\n```php\r\n<?php\r\n\r\nnamespace App\\Models\\Tenant;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Casts\\Attribute;\r\n\r\nclass Admin extends Authenticatable\r\n{\r\n use Notifiable, HasRoles, SoftDeletes;\r\n\r\n /**\r\n * The authentication guard name.\r\n *\r\n * @var string\r\n */\r\n public $guard = 'admin';\r\n\r\n /**\r\n * The attributes that are mass assignable.\r\n *\r\n * @var array\r\n */\r\n protected $fillable = [\r\n 'name',\r\n 'email',\r\n 'password',\r\n ];\r\n\r\n /**\r\n * The attributes that should be hidden for arrays.\r\n *\r\n * @var array\r\n */\r\n protected $hidden = [\r\n 'password',\r\n 'remember_token',\r\n ];\r\n\r\n /**\r\n * The attributes that should be cast to native types.\r\n *\r\n * @var array\r\n */\r\n protected $casts = [\r\n 'email_verified_at' => 'datetime',\r\n ];\r\n \r\n /**\r\n * Set the admin's Hash password.\r\n *\r\n * @return Attribute\r\n */\r\n protected function password(): Attribute\r\n {\r\n return new Attribute(\r\n set: fn($value) => Hash::make($value),\r\n );\r\n }\r\n}\r\n",
"comments": [
{
"body": "Hi there,\r\n\r\nThanks for reporting but it looks like this is a question which can be asked on a support channel. Please only use this issue tracker for reporting bugs with the library itself. If you have a question on how to use functionality provided by this repo you can try one of the following channels:\r\n\r\n- [Laracasts Forums](https://laracasts.com/discuss)\r\n- [Laravel.io Forums](https://laravel.io/forum)\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/laravel)\r\n- [Discord](https://discordapp.com/invite/KxwQuKb)\r\n- [Larachat](https://larachat.co)\r\n- [IRC](https://web.libera.chat/?nick=laravelnewbie&channels=#laravel)\r\n\r\nHowever, this issue will not be locked and everyone is still free to discuss solutions to your problem!\r\n\r\nThanks.",
"created_at": "2022-01-03T08:18:06Z"
},
{
"body": "Hi there,\nIt's not a question but it seems to be a bug\nNow, I'm asking how to report this bug correctly",
"created_at": "2022-01-03T08:32:38Z"
},
{
"body": "@michaelnabil230 @driesvints I believe this is a legitimate bug. All the tests that Taylor wrote tests the attribute when there is a value set. But if you don't set a value, the model is blank, and there is no `getter` on the attribute you get this error:\r\n\r\n\r\n\r\nThis only applies when you have a 'setter' only. This works:\r\n\r\n```\r\n return new Attribute(\r\n\t\t\tfn ($value) => $value,\r\n\t\t\tfn ($value) => Hash::make($value)\r\n\t\t);\r\n```\r\n\r\nThis doesn't:\r\n\r\n```\r\n return new Attribute(\r\n\t\t\tnull,\r\n\t\t\tfn ($value) => Hash::make($value)\r\n\t\t);\r\n```",
"created_at": "2022-01-03T15:29:11Z"
},
{
"body": "Thanks @BrandonSurowiec. I'll check into that.",
"created_at": "2022-01-03T15:37:01Z"
},
{
"body": "@driesvints \nAnd thanks to me because i reported this bug also 😄",
"created_at": "2022-01-03T16:36:15Z"
},
{
"body": "Thanks @driesvints @BrandonSurowiec ♥️ ",
"created_at": "2022-01-03T16:36:58Z"
},
{
"body": "I did an attempt at fixing this but think there's still a caveat to work around before we can merge it. I've put up the PR for Taylor to review: https://github.com/laravel/framework/pull/40245",
"created_at": "2022-01-04T12:54:22Z"
}
],
"number": 40230,
"title": "The issue is a new pattern of Attribute Cast"
} | {
"body": "Fixes an oversight in https://github.com/laravel/framework/pull/40022.\r\n\r\nAt the moment when you omit a get cast with the new attribute casting, the attribute call will propagate through the getAttribute method and end up to getRelationValue which will throw an exception that the attribute isn't a relationship instance. This is because the way attribute calls work is to fallback on relationships when they're not available. So the way the checks are done on get/set callables with the new attribute casting isn't entirely correct. We should omit the callable checks and just check if the method that corresponds with the requested attribute is returning an Attribute cast instance. If that's the case we can assume the user wanted to use attribute casting, regardless of a getter/setter being available or not. \r\n\r\nA cavaet of this is that this will prevent the call to continue to class casts and the old date casting. I do not know how to solve this and would appreciate any insights you have @taylorotwell.\r\n\r\nFixes #40230\r\n",
"number": 40245,
"review_comments": [
{
"body": "Can use `$this->assertNull($model->password);`",
"created_at": "2022-01-04T13:23:04Z"
},
{
"body": "Thanks!",
"created_at": "2022-01-04T13:26:35Z"
}
],
"title": "[8.x] Fix attribute casting"
} | {
"commits": [
{
"message": "Add failing test"
},
{
"message": "Fix attribute casting issue"
},
{
"message": "Update DatabaseEloquentModelAttributeCastingTest.php"
}
],
"files": [
{
"diff": "@@ -571,8 +571,7 @@ public function hasAttributeGetMutator($key)\n \n return static::$attributeMutatorCache[get_class($this)][$key] = $returnType &&\n $returnType instanceof ReflectionNamedType &&\n- $returnType->getName() === Attribute::class &&\n- is_callable($this->{$method}()->get);\n+ $returnType->getName() === Attribute::class;\n }\n \n /**\n@@ -949,8 +948,7 @@ public function hasAttributeSetMutator($key)\n \n return static::$setAttributeMutatorCache[$class][$key] = $returnType &&\n $returnType instanceof ReflectionNamedType &&\n- $returnType->getName() === Attribute::class &&\n- is_callable($this->{$method}()->set);\n+ $returnType->getName() === Attribute::class;\n }\n \n /**",
"filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
"status": "modified"
},
{
"diff": "@@ -142,6 +142,8 @@ public function testOneWayCasting()\n {\n $model = new TestEloquentModelWithAttributeCast;\n \n+ $this->assertNull($model->password);\n+\n $model->password = 'secret';\n \n $this->assertEquals(hash('sha256', 'secret'), $model->password);",
"filename": "tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php",
"status": "modified"
}
]
} |
{
"body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n",
"comments": [
{
"body": "OK, Thanks. We'll get it fixed.\n",
"created_at": "2013-01-11T16:29:55Z"
},
{
"body": "Fixed.\n",
"created_at": "2013-01-11T19:46:56Z"
},
{
"body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n",
"created_at": "2013-03-06T20:38:47Z"
}
],
"number": 3,
"title": "Migration doesn't account for prefix when checking if migration table exists [bug]"
} | {
"body": "## Why\r\n\r\nValidation rule `In` throws `TypeError` when we pass Enum cases from PHP 8.1:\r\n\r\n`Rule::in(SomeEnumObject::cases())`\r\n\r\n## Error\r\n\r\n`TypeError: str_replace(): Argument #3 ($subject) must be of type array|string, \\App\\Enums\\SomeEnumObject given in /vendor/laravel/framework/src/Illuminate/Validation/Rules/In.php:43`\r\n",
"number": 40146,
"review_comments": [
{
"body": "You should use FQN here",
"created_at": "2021-12-23T13:24:11Z"
}
],
"title": "[8.x] Fix Rule::in() to work with Enum values"
} | {
"commits": [
{
"message": "[8.x] Fix Rule::in() to work with Enum values\n\n## Why\r\n\r\nValidation rule `In` throws `TypeError` when we pass Enum cases from PHP 8.1:\r\n\r\n`Rule::in(SomeEnumObject::cases())`\r\n\r\n## Error\r\n\r\n`TypeError: str_replace(): Argument #3 ($subject) must be of type array|string, \\App\\Enums\\SomeEnumObject given in /vendor/laravel/framework/src/Illuminate/Validation/Rules/In.php:43`"
},
{
"message": "Update In.php"
},
{
"message": "Style changes"
},
{
"message": "Style changes"
},
{
"message": "Update In.php"
},
{
"message": "Update In.php"
}
],
"files": [
{
"diff": "@@ -2,6 +2,8 @@\n \n namespace Illuminate\\Validation\\Rules;\n \n+use UnitEnum;\n+\n class In\n {\n /**\n@@ -37,6 +39,10 @@ public function __construct(array $values)\n public function __toString()\n {\n $values = array_map(function ($value) {\n+ if ($value instanceof UnitEnum) {\n+ $value = $value->value;\n+ }\n+\n return '\"'.str_replace('\"', '\"\"', $value).'\"';\n }, $this->values);\n ",
"filename": "src/Illuminate/Validation/Rules/In.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.71.0\r\n- PHP Version: 8.0.2\r\n- Database Driver & Version: MySQL 8.0\r\n\r\n### Description:\r\nThe testing helpers `assertSoftDeleted()` and `assertNotSoftDeleted()` both accept either a table name provided as a string, or a model that implements the `SoftDeletes` trait. When a model is provided these functions automatically filter the query to the table for the model, as well as looking for the record with the provided primary key.\r\n\r\nHowever, when a model is provided any values provided in the second argument, `$data`, are discarded when the function recursively calls itself. As a result, what appears to be a valid test case is actually not executed with the expected behavior:\r\n\r\n```\r\n// Assume a database table (example_table) has the following record:\r\nid | col_a | col_b | deleted_at\r\n1 | foo | null | 2021-11-16 00:00:00\r\n\r\n// Assume we have a \"$model\" variable that exists for this record.\r\n// Now, in a test we add the following assertion:\r\n\r\n$this->assertSoftDeleted($model, ['col_b' => 'bar']);\r\n```\r\n\r\nThe example above will pass, even though the database does _not_ contain a record for that model where `col_b` is equal to `bar`. However, if you give that assertion the following code, it _does_ fail as expected:\r\n\r\n```\r\n$this->assertSoftDeleted('example_table', ['id' => 1, 'col_b' => 'bar']);\r\n```\r\n\r\nThe code responsible for these functions is here:\r\nhttps://github.com/laravel/framework/blob/8.x/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php#L90-L132\r\n\r\nThe specific chunk responsible for dropping the `$data` parameter is here:\r\nhttps://github.com/laravel/framework/blob/8.x/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php#L123-L125",
"comments": [
{
"body": "Thank you for reporting. I've sent in a fix for this to https://github.com/laravel/framework/pull/39673",
"created_at": "2021-11-18T08:39:46Z"
},
{
"body": "Will be in the next release.",
"created_at": "2021-11-18T15:00:50Z"
}
],
"number": 39667,
"title": "assertSoftDeleted() and assertNotSoftDeleted() discard $data argument value when first argument is a model"
} | {
"body": "This PR fixes an issue where `$data` wasn't passed along properly as a where clause for the `assertSoftDeleted` & `assertNotSoftDeleted` methods. By passing the data properly, more granular assertions can be made.\r\n\r\nFixes #39667\r\n",
"number": 39673,
"review_comments": [],
"title": "[8.x] Fix assertSoftDeleted & assertNotSoftDeleted"
} | {
"commits": [
{
"message": "Fix assertNotSoftDeleted"
},
{
"message": "wip"
}
],
"files": [
{
"diff": "@@ -99,7 +99,12 @@ protected function assertDeleted($table, array $data = [], $connection = null)\n protected function assertSoftDeleted($table, array $data = [], $connection = null, $deletedAtColumn = 'deleted_at')\n {\n if ($this->isSoftDeletableModel($table)) {\n- return $this->assertSoftDeleted($table->getTable(), [$table->getKeyName() => $table->getKey()], $table->getConnectionName(), $table->getDeletedAtColumn());\n+ return $this->assertSoftDeleted(\n+ $table->getTable(),\n+ array_merge($data, [$table->getKeyName() => $table->getKey()]),\n+ $table->getConnectionName(),\n+ $table->getDeletedAtColumn()\n+ );\n }\n \n $this->assertThat(\n@@ -121,7 +126,12 @@ protected function assertSoftDeleted($table, array $data = [], $connection = nul\n protected function assertNotSoftDeleted($table, array $data = [], $connection = null, $deletedAtColumn = 'deleted_at')\n {\n if ($this->isSoftDeletableModel($table)) {\n- return $this->assertNotSoftDeleted($table->getTable(), [$table->getKeyName() => $table->getKey()], $table->getConnectionName(), $table->getDeletedAtColumn());\n+ return $this->assertNotSoftDeleted(\n+ $table->getTable(),\n+ array_merge($data, [$table->getKeyName() => $table->getKey()]),\n+ $table->getConnectionName(),\n+ $table->getDeletedAtColumn()\n+ );\n }\n \n $this->assertThat(",
"filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php",
"status": "modified"
},
{
"diff": "@@ -241,18 +241,19 @@ public function testAssertSoftDeletedInDatabaseDoesNotFindModelWithCustomColumnR\n $this->expectException(ExpectationFailedException::class);\n $this->expectExceptionMessage('The table is empty.');\n \n- $this->data = ['id' => 1];\n+ $model = new CustomProductStub(['id' => 1, 'name' => 'Laravel']);\n+ $this->data = ['id' => 1, 'name' => 'Tailwind'];\n \n $builder = $this->mockCountBuilder(0, 'trashed_at');\n \n $builder->shouldReceive('get')->andReturn(collect());\n \n- $this->assertSoftDeleted(new CustomProductStub($this->data));\n+ $this->assertSoftDeleted($model, ['name' => 'Tailwind']);\n }\n \n public function testAssertNotSoftDeletedInDatabaseFindsResults()\n {\n- $builder = $this->mockCountBuilder(1);\n+ $this->mockCountBuilder(1);\n \n $this->assertNotSoftDeleted($this->table, $this->data);\n }\n@@ -307,13 +308,14 @@ public function testAssertNotSoftDeletedInDatabaseDoesNotFindModelWithCustomColu\n $this->expectException(ExpectationFailedException::class);\n $this->expectExceptionMessage('The table is empty.');\n \n- $this->data = ['id' => 1];\n+ $model = new CustomProductStub(['id' => 1, 'name' => 'Laravel']);\n+ $this->data = ['id' => 1, 'name' => 'Tailwind'];\n \n $builder = $this->mockCountBuilder(0, 'trashed_at');\n \n $builder->shouldReceive('get')->andReturn(collect());\n \n- $this->assertNotSoftDeleted(new CustomProductStub($this->data));\n+ $this->assertNotSoftDeleted($model, ['name' => 'Tailwind']);\n }\n \n public function testAssertExistsPassesWhenFindsResults()",
"filename": "tests/Foundation/FoundationInteractsWithDatabaseTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.67.0\r\n- PHP Version: 7.4\r\n- Database Driver & Version: MS SQL Server 2019\r\n\r\n### Description:\r\n\r\nI have the following relationship:\r\n\r\n```\r\nreturn $this->hasOne(AssignmentMark::class, 'enrolment_id', 'EnrolmentID')\r\n ->ofMany([\r\n 'assignment_id' => 'max'\r\n ],\r\n function ($query) {\r\n $query->join('assignments AS a', 'a.id', 'assignment_marks.assignment_id')\r\n ->where('due_date', '<=', now())\r\n ->whereNotNull('assignment_marks.grade')\r\n ->whereIn('assignment_type_id', [1, 2]);\r\n },\r\n 'am'\r\n )->withDefault();\r\n```\r\n\r\nComparing the generated SQL between 8.64 and 8.67, I notice that it is quite different. The problem seems to stem from the new version adding an additional join to the assignments table, which causes the ambiguous column:\r\n\r\nOld (working) SQL:\r\n\r\n```\r\nSELECT TOP 1 *\r\nFROM [focus].[dbo].[assignment_marks]\r\n INNER JOIN (SELECT Max([id]) AS [id],\r\n [focus].[dbo].[assignment_marks].[enrolment_id]\r\n FROM [focus].[dbo].[assignment_marks]\r\n INNER JOIN (....\r\n```\r\n\r\nNew (failing) SQL:\r\n\r\n```\r\nSELECT TOP 1\r\n [focus].[dbo].[assignment_marks].*\r\nFROM [focus].[dbo].[assignment_marks]\r\nINNER JOIN\r\n (\r\n SELECT Max([id]) AS [id_aggregate],\r\n [focus].[dbo].[assignment_marks].[enrolment_id]\r\n FROM [focus].[dbo].[assignment_marks]\r\n INNER JOIN [assignments] AS [a] ON [a].[id] = [assignment_marks].[assignment_id] /*This join causes the problem /*\r\n INNER JOIN\r\n (....\r\n```\r\n\r\nThere are a number of other changes to the generated SQL that appear to me to be a lot more messy than in the original version (happy to reply with a side-by-side comparison if useful).\r\n\r\nFor the moment I've reverted to Laravel 8.64.\r\n\r\nCheers,\r\nMartin. \r\n",
"comments": [
{
"body": "Can you provide the full error and the full query ?",
"created_at": "2021-10-26T20:48:09Z"
},
{
"body": "Sure thing (this from the log file):\r\n\r\n`local.ERROR: SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Ambiguous column name 'id'. (SQL: select top 1 [focus].[dbo].[assignment_marks].* from [focus].[dbo].[assignment_marks] inner join (select MAX([id]) as [id_aggregate], [focus].[dbo].[assignment_marks].[enrolment_id] from [focus].[dbo].[assignment_marks] inner join [assignments] as [a] on [a].[id] = [assignment_marks].[assignment_id] inner join (select max([assignment_id]) as [assignment_id_aggregate], [focus].[dbo].[assignment_marks].[enrolment_id] from [focus].[dbo].[assignment_marks] inner join [assignments] as [a] on [a].[id] = [assignment_marks].[assignment_id] where [due_date] <= 2021-10-26 13:36:34.768 and [assignment_marks].[grade] is not null and [assignment_type_id] in (1, 2) and [focus].[dbo].[assignment_marks].[enrolment_id] = 225334 and [focus].[dbo].[assignment_marks].[enrolment_id] is not null group by [focus].[dbo].[assignment_marks].[enrolment_id]) as [am] on [am].[assignment_id_aggregate] = [focus].[dbo].[assignment_marks].[assignment_id] and [am].[enrolment_id] = [focus].[dbo].[assignment_marks].[enrolment_id] where [due_date] <= 2021-10-26 13:36:34.768 and [assignment_marks].[grade] is not null and [assignment_type_id] in (1, 2) group by [focus].[dbo].[assignment_marks].[enrolment_id]) as [am] on [am].[id_aggregate] = [focus].[dbo].[assignment_marks].[id] and [am].[enrolment_id] = [focus].[dbo].[assignment_marks].[enrolment_id] where [focus].[dbo].[assignment_marks].[enrolment_id] = 225334 and [focus].[dbo].[assignment_marks].[enrolment_id] is not null) `\r\n\r\nAnd for completeness, here's what the query looks like in the previous working state:\r\n\r\n`select top 1 * from [focus].[dbo].[assignment_marks] inner join (select MAX([id]) as [id], [focus].[dbo].[assignment_marks].[enrolment_id] from [focus].[dbo].[assignment_marks] inner join (select max([assignment_id]) as [assignment_id], [focus].[dbo].[assignment_marks].[enrolment_id] from [focus].[dbo].[assignment_marks] inner join [assignments] as [a] on [a].[id] = [assignment_marks].[assignment_id] where [due_date] <= '2021-10-26 16:18:33.640' and [assignment_marks].[grade] is not null and [assignment_type_id] in (1, 2) and [focus].[dbo].[assignment_marks].[enrolment_id] = 225334 and [focus].[dbo].[assignment_marks].[enrolment_id] is not null group by [focus].[dbo].[assignment_marks].[enrolment_id]) as [am] on [am].[assignment_id] = [focus].[dbo].[assignment_marks].[assignment_id] and [am].[enrolment_id] = [focus].[dbo].[assignment_marks].[enrolment_id] group by [focus].[dbo].[assignment_marks].[enrolment_id]) as [am] on [am].[id] = [focus].[dbo].[assignment_marks].[id] and [am].[enrolment_id] = [focus].[dbo].[assignment_marks].[enrolment_id] where [focus].[dbo].[assignment_marks].[enrolment_id] = 225334 and [focus].[dbo].[assignment_marks].[enrolment_id] is not null`",
"created_at": "2021-10-27T07:48:30Z"
},
{
"body": "I'll try to take a look on this.\r\n\r\nI guess ` SELECT Max([id]) AS [id_aggregate],` should be ` SELECT Max([focus].[dbo].[assignment_marks].[id]) AS [id_aggregate],`",
"created_at": "2021-10-27T10:13:54Z"
},
{
"body": "@MartinHughes-BPC Can you test the fix ? It should solve the issue",
"created_at": "2021-10-27T12:30:50Z"
},
{
"body": "Hi @bastien-phi \r\n\r\nTested and working - yes, it was the need to qualify the aggregated column. I'm still a bit intrigued as to why the new version added the additional join (and duplicated the where conditions) when the original only put these in the very inner select?\r\n\r\nAnyway, thanks for looking at this and providing a fix.\r\n\r\nCheers,\r\nMartin.",
"created_at": "2021-10-27T13:16:04Z"
},
{
"body": "@MartinHughes-BPC you will find more information on why we need to duplicate the where conditions in https://github.com/laravel/framework/pull/39187\r\n\r\nNo problem, I'm happy to help !",
"created_at": "2021-10-27T13:23:47Z"
}
],
"number": 39369,
"title": "hasOne()->ofMany() failing in SQL Server with Ambiguous Column Name error since update to 8.67.0"
} | {
"body": "Aggregated column is currently not qualify and causes ambiguous column name error when subquery joins another column\r\n\r\nFixes #39369",
"number": 39387,
"review_comments": [],
"title": "[8.x] Qualify aggragated column in OneOfMany subqueries"
} | {
"commits": [
{
"message": "Qualify aggragated column in OneOfMany subqueries"
},
{
"message": "Cleanup global scope after test"
},
{
"message": "Fix cs"
}
],
"files": [
{
"diff": "@@ -195,7 +195,7 @@ protected function newOneOfManySubQuery($groupBy, $column = null, $aggregate = n\n }\n \n if (! is_null($column)) {\n- $subQuery->selectRaw($aggregate.'('.$subQuery->getQuery()->grammar->wrap($column).') as '.$subQuery->getQuery()->grammar->wrap($column.'_aggregate'));\n+ $subQuery->selectRaw($aggregate.'('.$subQuery->getQuery()->grammar->wrap($subQuery->qualifyColumn($column)).') as '.$subQuery->getQuery()->grammar->wrap($column.'_aggregate'));\n }\n \n $this->addOneOfManySubQueryConstraints($subQuery, $groupBy, $column, $aggregate);",
"filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php",
"status": "modified"
},
{
"diff": "@@ -107,30 +107,36 @@ public function testEagerLoadingAppliesConstraintsToInnerJoinSubQuery()\n $user = HasOneOfManyTestUser::create();\n $relation = $user->latest_login();\n $relation->addEagerConstraints([$user]);\n- $this->assertSame('select MAX(\"id\") as \"id_aggregate\", \"logins\".\"user_id\" from \"logins\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null and \"logins\".\"user_id\" in (1) group by \"logins\".\"user_id\"', $relation->getOneOfManySubQuery()->toSql());\n+ $this->assertSame('select MAX(\"logins\".\"id\") as \"id_aggregate\", \"logins\".\"user_id\" from \"logins\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null and \"logins\".\"user_id\" in (1) group by \"logins\".\"user_id\"', $relation->getOneOfManySubQuery()->toSql());\n }\n \n public function testGlobalScopeIsNotAppliedWhenRelationIsDefinedWithoutGlobalScope()\n {\n- HasOneOfManyTestLogin::addGlobalScope(function ($query) {\n+ HasOneOfManyTestLogin::addGlobalScope('test', function ($query) {\n $query->orderBy('id');\n });\n \n $user = HasOneOfManyTestUser::create();\n $relation = $user->latest_login_without_global_scope();\n $relation->addEagerConstraints([$user]);\n- $this->assertSame('select \"logins\".* from \"logins\" inner join (select MAX(\"id\") as \"id_aggregate\", \"logins\".\"user_id\" from \"logins\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null and \"logins\".\"user_id\" in (1) group by \"logins\".\"user_id\") as \"latestOfMany\" on \"latestOfMany\".\"id_aggregate\" = \"logins\".\"id\" and \"latestOfMany\".\"user_id\" = \"logins\".\"user_id\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null', $relation->getQuery()->toSql());\n+ $this->assertSame('select \"logins\".* from \"logins\" inner join (select MAX(\"logins\".\"id\") as \"id_aggregate\", \"logins\".\"user_id\" from \"logins\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null and \"logins\".\"user_id\" in (1) group by \"logins\".\"user_id\") as \"latestOfMany\" on \"latestOfMany\".\"id_aggregate\" = \"logins\".\"id\" and \"latestOfMany\".\"user_id\" = \"logins\".\"user_id\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null', $relation->getQuery()->toSql());\n+\n+ HasOneOfManyTestLogin::addGlobalScope('test', function ($query) {\n+ });\n }\n \n public function testGlobalScopeIsNotAppliedWhenRelationIsDefinedWithoutGlobalScopeWithComplexQuery()\n {\n- HasOneOfManyTestPrice::addGlobalScope(function ($query) {\n+ HasOneOfManyTestPrice::addGlobalScope('test', function ($query) {\n $query->orderBy('id');\n });\n \n $user = HasOneOfManyTestUser::create();\n $relation = $user->price_without_global_scope();\n- $this->assertSame('select \"prices\".* from \"prices\" inner join (select max(\"id\") as \"id_aggregate\", \"prices\".\"user_id\" from \"prices\" inner join (select max(\"published_at\") as \"published_at_aggregate\", \"prices\".\"user_id\" from \"prices\" where \"published_at\" < ? and \"prices\".\"user_id\" = ? and \"prices\".\"user_id\" is not null group by \"prices\".\"user_id\") as \"price_without_global_scope\" on \"price_without_global_scope\".\"published_at_aggregate\" = \"prices\".\"published_at\" and \"price_without_global_scope\".\"user_id\" = \"prices\".\"user_id\" where \"published_at\" < ? group by \"prices\".\"user_id\") as \"price_without_global_scope\" on \"price_without_global_scope\".\"id_aggregate\" = \"prices\".\"id\" and \"price_without_global_scope\".\"user_id\" = \"prices\".\"user_id\" where \"prices\".\"user_id\" = ? and \"prices\".\"user_id\" is not null', $relation->getQuery()->toSql());\n+ $this->assertSame('select \"prices\".* from \"prices\" inner join (select max(\"prices\".\"id\") as \"id_aggregate\", \"prices\".\"user_id\" from \"prices\" inner join (select max(\"prices\".\"published_at\") as \"published_at_aggregate\", \"prices\".\"user_id\" from \"prices\" where \"published_at\" < ? and \"prices\".\"user_id\" = ? and \"prices\".\"user_id\" is not null group by \"prices\".\"user_id\") as \"price_without_global_scope\" on \"price_without_global_scope\".\"published_at_aggregate\" = \"prices\".\"published_at\" and \"price_without_global_scope\".\"user_id\" = \"prices\".\"user_id\" where \"published_at\" < ? group by \"prices\".\"user_id\") as \"price_without_global_scope\" on \"price_without_global_scope\".\"id_aggregate\" = \"prices\".\"id\" and \"price_without_global_scope\".\"user_id\" = \"prices\".\"user_id\" where \"prices\".\"user_id\" = ? and \"prices\".\"user_id\" is not null', $relation->getQuery()->toSql());\n+\n+ HasOneOfManyTestPrice::addGlobalScope('test', function ($query) {\n+ });\n }\n \n public function testQualifyingSubSelectColumn()\n@@ -231,6 +237,22 @@ public function testItEagerLoadsCorrectModels()\n $this->assertSame($latestLogin->id, $user->latest_login->id);\n }\n \n+ public function testItJoinsOtherTableInSubQuery()\n+ {\n+ $user = HasOneOfManyTestUser::create();\n+ $user->logins()->create();\n+\n+ $this->assertNull($user->latest_login_with_foo_state);\n+\n+ $user->unsetRelation('latest_login_with_foo_state');\n+ $user->states()->create([\n+ 'type' => 'foo',\n+ 'state' => 'draft',\n+ ]);\n+\n+ $this->assertNotNull($user->latest_login_with_foo_state);\n+ }\n+\n public function testHasNested()\n {\n $user = HasOneOfManyTestUser::create();\n@@ -511,6 +533,17 @@ public function first_login()\n return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany('id', 'min');\n }\n \n+ public function latest_login_with_foo_state()\n+ {\n+ return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany(\n+ ['id' => 'max'],\n+ function ($query) {\n+ $query->join('states', 'states.user_id', 'logins.user_id')\n+ ->where('states.type', 'foo');\n+ }\n+ );\n+ }\n+\n public function states()\n {\n return $this->hasMany(HasOneOfManyTestState::class, 'user_id');",
"filename": "tests/Database/DatabaseEloquentHasOneOfManyTest.php",
"status": "modified"
},
{
"diff": "@@ -61,7 +61,7 @@ public function testEagerLoadingAppliesConstraintsToInnerJoinSubQuery()\n $product = MorphOneOfManyTestProduct::create();\n $relation = $product->current_state();\n $relation->addEagerConstraints([$product]);\n- $this->assertSame('select MAX(\"id\") as \"id_aggregate\", \"states\".\"stateful_id\", \"states\".\"stateful_type\" from \"states\" where \"states\".\"stateful_id\" = ? and \"states\".\"stateful_id\" is not null and \"states\".\"stateful_type\" = ? and \"states\".\"stateful_id\" in (1) and \"states\".\"stateful_type\" = ? group by \"states\".\"stateful_id\", \"states\".\"stateful_type\"', $relation->getOneOfManySubQuery()->toSql());\n+ $this->assertSame('select MAX(\"states\".\"id\") as \"id_aggregate\", \"states\".\"stateful_id\", \"states\".\"stateful_type\" from \"states\" where \"states\".\"stateful_id\" = ? and \"states\".\"stateful_id\" is not null and \"states\".\"stateful_type\" = ? and \"states\".\"stateful_id\" in (1) and \"states\".\"stateful_type\" = ? group by \"states\".\"stateful_id\", \"states\".\"stateful_type\"', $relation->getOneOfManySubQuery()->toSql());\n }\n \n public function testReceivingModel()",
"filename": "tests/Database/DatabaseEloquentMorphOneOfManyTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.65.0\r\n- PHP Version: 8.0.11\r\n- Database Driver & Version: mysql 8.0.22\r\n\r\n### Description:\r\n\r\n#39187 might have introduced a regression vs 8.64.0 in the generated SQL for `latestOfMany` relationships. The error is:\r\n\r\n`SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'MY_DATABASE.bids.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by`\r\n\r\nAll tables are using standard Laravel id/foreign key conventions.\r\n\r\nThe relationship is this: Lot->hasMany(Bid) where `bids.lot_id = lots.id`\r\n\r\nThe code is referencing a winningBid which is defined as:\r\n\r\n```\r\n// Lot.php\r\npublic function winningBid(): HasOne\r\n{\r\n return $this->hasOne(Bid::class)->withoutGlobalScopes()->latestOfMany()->withDefault();\r\n}\r\n```\r\n\r\nin 8.64, the query generated for the code `Lot::with('winningBid')->find(1234)`:\r\n\r\n```\r\nselect *\r\nfrom `bids`\r\n inner join (select MAX(`id`) as `id`, `bids`.`lot_id`\r\n from `bids`\r\n where `bids`.`lot_id` = 1234\r\n group by `bids`.`lot_id`\r\n order by `id` desc) as `latestOfMany`\r\n on `latestOfMany`.`id` = `bids`.`id` and `latestOfMany`.`lot_id` = `bids`.`lot_id`;\r\n```\r\n\r\nand in 8.65:\r\n\r\n```\r\nselect *\r\nfrom `bids`\r\n inner join (select MAX(`id`) as `id_aggregate`, `bids`.`lot_id`\r\n from `bids`\r\n where `bids`.`lot_id` = 1234\r\n group by `bids`.`lot_id`\r\n order by `id` desc) as `latestOfMany`\r\n on `latestOfMany`.`id_aggregate` = `bids`.`id` and `latestOfMany`.`lot_id` = `bids`.`lot_id`;\r\n```\r\n\r\nChanging ```order by `id` desc``` to ```order by `id_aggregate` desc``` causes it to not error and return the same results for both queries when run through a db console.\r\n\r\n### Steps To Reproduce:\r\n\r\nPrivate repo, let me know if more details are required.\r\n",
"comments": [
{
"body": "I've sent in a PR to revert this. Thanks for reporting.",
"created_at": "2021-10-21T07:29:32Z"
},
{
"body": "@ransompate I can't find any way to reproduce this bug. I don't see the `order` clause added to the query.\r\n\r\nCan you give me more information ?",
"created_at": "2021-10-21T09:05:23Z"
},
{
"body": "@ransompate My guess is you have somewhere in your code \r\n\r\n```php\r\nBid::addGlobalScope(function($query) {\r\n $query->orderByDesc('id');\r\n});\r\n```\r\n\r\nThe relation \r\n```php\r\npublic function winningBid(): HasOne\r\n{\r\n return $this->hasOne(Bid::class)->withoutGlobalScopes()->latestOfMany()->withDefault();\r\n}\r\n```\r\n\r\nThe problem here is that the global scope is not removed here...\r\n",
"created_at": "2021-10-21T10:49:33Z"
},
{
"body": "@ransompate Can you try the fix in #39295 ?",
"created_at": "2021-10-21T12:19:27Z"
},
{
"body": "> \r\n> \r\n> @ransompate My guess is you have somewhere in your code\r\n> \r\n\r\n\r\nYes, exactly. \r\n\r\n> \r\n> \r\n> @ransompate Can you try the fix in #39295 ?\r\n\r\nThis is working perfectly now:\r\n```\r\nselect * from `bids` inner join (select MAX(`id`) as `id_aggregate`, `bids`.`lot_id` from `bids` where `bids`.`lot_id` in (LOT_IDS_ARRAY) group by `bids`.`lot_id`) as `latestOfMany` on `latestOfMany`.`id_aggregate` = `bids`.`id` and `latestOfMany`.`lot_id` = `bids`.`lot_id`\r\n```",
"created_at": "2021-10-21T13:07:29Z"
}
],
"number": 39266,
"title": "LatestOfMany ORDER BY clause is not in GROUP BY"
} | {
"body": "Fixes #39266\r\n\r\nThe problem is that`->withoutGlobalScope()` called on the relation is not respected.",
"number": 39295,
"review_comments": [],
"title": "[8.x] Apply withoutGlobalScope in CanBeOneOfMany subqueries"
} | {
"commits": [
{
"message": "Apply withoutGlobalScope in CanBeOneOfMany subqueries"
}
],
"files": [
{
"diff": "@@ -181,7 +181,8 @@ protected function getDefaultOneOfManyJoinAlias($relation)\n protected function newOneOfManySubQuery($groupBy, $column = null, $aggregate = null)\n {\n $subQuery = $this->query->getModel()\n- ->newQuery();\n+ ->newQuery()\n+ ->withoutGlobalScopes($this->removedScopes());\n \n foreach (Arr::wrap($groupBy) as $group) {\n $subQuery->groupBy($this->qualifyRelatedColumn($group));",
"filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/CanBeOneOfMany.php",
"status": "modified"
},
{
"diff": "@@ -110,6 +110,29 @@ public function testEagerLoadingAppliesConstraintsToInnerJoinSubQuery()\n $this->assertSame('select MAX(\"id\") as \"id_aggregate\", \"logins\".\"user_id\" from \"logins\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null and \"logins\".\"user_id\" in (1) group by \"logins\".\"user_id\"', $relation->getOneOfManySubQuery()->toSql());\n }\n \n+ public function testGlobalScopeIsNotAppliedWhenRelationIsDefinedWithoutGlobalScope()\n+ {\n+ HasOneOfManyTestLogin::addGlobalScope(function ($query) {\n+ $query->orderBy('id');\n+ });\n+\n+ $user = HasOneOfManyTestUser::create();\n+ $relation = $user->latest_login_without_global_scope();\n+ $relation->addEagerConstraints([$user]);\n+ $this->assertSame('select * from \"logins\" inner join (select MAX(\"id\") as \"id_aggregate\", \"logins\".\"user_id\" from \"logins\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null and \"logins\".\"user_id\" in (1) group by \"logins\".\"user_id\") as \"latestOfMany\" on \"latestOfMany\".\"id_aggregate\" = \"logins\".\"id\" and \"latestOfMany\".\"user_id\" = \"logins\".\"user_id\" where \"logins\".\"user_id\" = ? and \"logins\".\"user_id\" is not null', $relation->getQuery()->toSql());\n+ }\n+\n+ public function testGlobalScopeIsNotAppliedWhenRelationIsDefinedWithoutGlobalScopeWithComplexQuery()\n+ {\n+ HasOneOfManyTestPrice::addGlobalScope(function ($query) {\n+ $query->orderBy('id');\n+ });\n+\n+ $user = HasOneOfManyTestUser::create();\n+ $relation = $user->price_without_global_scope();\n+ $this->assertSame('select * from \"prices\" inner join (select max(\"id\") as \"id_aggregate\", \"prices\".\"user_id\" from \"prices\" inner join (select max(\"published_at\") as \"published_at_aggregate\", \"prices\".\"user_id\" from \"prices\" where \"published_at\" < ? and \"prices\".\"user_id\" = ? and \"prices\".\"user_id\" is not null group by \"prices\".\"user_id\") as \"price_without_global_scope\" on \"price_without_global_scope\".\"published_at_aggregate\" = \"prices\".\"published_at\" and \"price_without_global_scope\".\"user_id\" = \"prices\".\"user_id\" where \"published_at\" < ? group by \"prices\".\"user_id\") as \"price_without_global_scope\" on \"price_without_global_scope\".\"id_aggregate\" = \"prices\".\"id\" and \"price_without_global_scope\".\"user_id\" = \"prices\".\"user_id\" where \"prices\".\"user_id\" = ? and \"prices\".\"user_id\" is not null', $relation->getQuery()->toSql());\n+ }\n+\n public function testQualifyingSubSelectColumn()\n {\n $user = HasOneOfManyTestUser::create();\n@@ -468,6 +491,11 @@ public function latest_login_with_invalid_aggregate()\n return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany('id', 'count');\n }\n \n+ public function latest_login_without_global_scope()\n+ {\n+ return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->withoutGlobalScopes()->latestOfMany();\n+ }\n+\n public function first_login()\n {\n return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany('id', 'min');\n@@ -522,6 +550,16 @@ public function price_with_shortcut()\n {\n return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->latestOfMany(['published_at', 'id']);\n }\n+\n+ public function price_without_global_scope()\n+ {\n+ return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->withoutGlobalScopes()->ofMany([\n+ 'published_at' => 'max',\n+ 'id' => 'max',\n+ ], function ($q) {\n+ $q->where('published_at', '<', now());\n+ });\n+ }\n }\n \n class HasOneOfManyTestModel extends Eloquent",
"filename": "tests/Database/DatabaseEloquentHasOneOfManyTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 6.0.0\r\n- PHP Version: 7.4.4\r\n- Database Driver & Version: PostgreSQL 10\r\n\r\n### Description:\r\n\r\nIt seems that this commit: 3495ebd7c830ed37b737003d58d991038b479616 removed support for `update ... from ...` statement with the PostgreSQL.\r\n\r\nThe following code:\r\n```php\r\n$db->table('users')\r\n\t->joinSub(function ($query) use ($strat_date, $end_date, $db) {\r\n\t\t$query->from('invoices')\r\n\t\t\t->whereBetween('created_at', $start_date, $end_date)\r\n\t\t\t->groupBy('user_id')\r\n\t\t\t->select('user_id', $db->raw('SUM(amount) as amount, COUNT(*) as c, MAX(created_at) as created_at'));\r\n\t}, 'sq', 'users.id', '=', 'sq.user_id')\r\n\t->update([\r\n\t\t'total_amount' => $db->raw('total_amount + sq.amount'),\r\n\t\t'nb_invoices' => $db->raw('nb_invoices + sq.c'),\r\n\t\t'last_invoice_date' => $db->raw('sq.created_at')\r\n\t]);\r\n```\r\ngave the following statement, in version 5.8 (i added line breaks and indentation for lisibility):\r\n\r\n```sql\r\nupdate \"users\"\r\nset \"total_amount\" = total_amount + sq.amount, \"nb_invoices\" = nb_invoices + sq.c, \"last_invoice_date\" = sq.created_at\r\nfrom (select \"user_id\", MAX(created_at) as created_at, SUM(amount) as amount, COUNT(*) as c\r\n\tfrom \"invoices\" where \"created_at\" between ? AND ? group by \"user_id\"\r\n) as \"sq\"\r\nwhere \"users\".\"id\" = \"sq\".\"user_id\"\r\n```\r\nFrom version 6.0.0, it gives the request below which results in an SQL error:\r\n```sql\r\nupdate \"users\"\r\nset \"total_amount\" = total_amount + sq.amount,\r\n\t\"nb_invoices\" = nb_invoices + sq.c,\r\n\t\"last_invoice_date\" = sq.created_at\r\nwhere \"ctid\" in (\r\n\tselect \"users\".\"ctid\"\r\n\tfrom \"users\"\r\n\tinner join (\r\n\t\tselect \"user_id\", MAX(created_at) as created_at, SUM(amount) as amount, COUNT(*) as c\r\n\t\tfrom \"invoices\"\r\n\t\twhere \"created_at\" between ? AND ?\r\n\t\tgroup by \"user_id\"\r\n\t) as \"sq\" on \"users\".\"id\" = \"sq\".\"user_id\")\r\n```\r\nWhich results in the following sql error:\r\n\r\n> SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table \"sq\"\r\n",
"comments": [
{
"body": "Ping @staudenmeir ",
"created_at": "2020-06-18T13:40:58Z"
},
{
"body": "I've just got the same problem during the upgrade to Laravel 6.\r\n\r\nUnfortunately, I can't provide the example from the real codebase.\r\n\r\n_But for instance_: I need to update some rows in a table using data from a subquery.\r\n\r\n```php\r\n$aggregationQuery = CollectionItems::query()\r\n ->select([\r\n 'collection_id',\r\n 'total_amount' => DB::raw('sum(amount)'),\r\n 'avg_something_else' => DB::raw('avg(something_else)'),\r\n ])\r\n ->groupBy('collection_id');\r\n```\r\n\r\nSo to update target table I'm using Postgresql update ... from clause: \r\n\r\n```php\r\nCollections::joinSub($aggregationQuery, 'calculated_results', 'id', 'calculated_results.collection_id')\r\n ->whereIn('id', [1, 5, 7])\r\n ->update([\r\n 'total_amount' => DB::raw('calculated_results.total_amount'),\r\n 'avg_something_else ' => DB::raw('calculated_results.avg_something_else')\r\n ]);\r\n```\r\n\r\nIn Laravel 5.8 it used to generate such query as below:\r\n\r\n```sql\r\nupdate collections\r\nset\r\n total_amount = calculated_results.total_amount,\r\n avg_something_else = calculated_results.avg_something_else\r\nfrom (\r\n select \r\n collection_id, sum(amount) as total_amount, avg(something_else) as avg_something_else \r\n from collection_items \r\n group by collection_id\r\n) as calculated_results where id = calculated_results.collection_id and id in (1, 5, 7)\r\n```\r\n\r\nnow it generates \r\n\r\n```sql\r\nupdate \"collections\"\r\nset\r\n total_amount = calculated_results.total_amount,\r\n avg_something_else = calculated_results.avg_something_else\r\nwhere \"ctid\" in (\r\n\tselect \"collection_items\".\"ctid\"\r\n\tfrom \"collection_items\"\r\n\tinner join (\r\n\t\tselect collection_id, sum(amount) as total_amount, avg(something_else) as avg_something_else \r\n\t\tfrom \"collection_items\"\r\n\t\tgroup by collection_id\r\n\t) as \"calculated_results\" where \"id\" in (1, 5, 7) and \"id\" = \"calculated_results\".\"collection_id\")\r\n```\r\n\r\nand the following sql error:\r\n\r\n> SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table \"calculated_results\"",
"created_at": "2020-06-26T14:02:39Z"
},
{
"body": "It looks like we have to revert the commit, I don't see a way to fix the issue.\r\n\r\nWhich versions do we target? The revert is also kind of a breaking change, people can be relying on the features that the commit added (support for outer joins and `LIMIT` clauses).",
"created_at": "2020-06-28T21:00:31Z"
},
{
"body": "This will re-introduce https://github.com/laravel/framework/issues/18694 then?",
"created_at": "2020-06-29T15:26:06Z"
},
{
"body": "@driesvints Yes.\r\n\r\nIn theory, we could restore the previous implementation and only use it for the queries that don't work with the current one. The issue is that we can't reliably detect those queries.",
"created_at": "2020-07-01T21:29:40Z"
},
{
"body": "@staudenmeir is there any way we can re-introduce support for `update ... from ...` in another way?",
"created_at": "2020-07-02T09:08:42Z"
},
{
"body": "Also: how much is `update ... from ...` actually used? I'm not that familiar with PostgreSQL.",
"created_at": "2020-07-02T09:09:38Z"
},
{
"body": "> is there any way we can re-introduce support for update ... from ... in another way?\r\n\r\nDo you mean as a separate method?",
"created_at": "2020-07-05T18:36:09Z"
},
{
"body": "Yes",
"created_at": "2020-07-06T09:55:41Z"
},
{
"body": "I had an idea for a different approach (the opposite of https://github.com/laravel/framework/issues/33265#issuecomment-652656188): We could restore the previous implementation as the default behavior and only use the code from 3495ebd when necessary (queries with outer joins or `LIMIT` clauses).\r\n\r\nI'll look into that.",
"created_at": "2020-07-12T11:18:46Z"
},
{
"body": "I need to make this kind of query quite a bit, it's actually preventing me from upgrading past laravel 5.8. \r\nIt seems like a real tricky issue to solve. The old way can't do outer joins, but can reference joined values... while the new way is the opposite, allowing outer joins, but can't reference joined values.\r\n\r\nIn my particular situation, I need to update the values in `table_1` to be an aggregate of values from `table_2`, but some rows in `table_2` are filtered out, and I'd like the update query to set the `table_1` values for those rows to null. This seems to require an outer join, otherwise the rows in `table_1` are removed by the inner join, and not updated at all.\r\n \r\nHow I'm currently handling this on 5.8 is using sub-queries. I perform the outer join between `table_1` and `table_2` in a sub-query, and then inner join `table_1` with a duplicate of itself in the update statement. It looks something like this\r\n```\r\n$subQuery2 = DB::table('table2')->where('column', $filter);\r\n\r\n$subQuery1 = DB::table('table1')->leftJoinSub($subQuery2, 'sub2', 'sub2.primary_key, '=', 'sub1.foreign_key`);\r\n\r\n$update = DB:table('table1')->joinSub($subQuery1, 'sub1', 'sub1.primary_key, '=', 'table1.primary_key`)\r\n ->update(['table1.value' => DB::raw('table2.value')]);\r\n```\r\n I'm not sure if this helps anyone, but figured I'd mention it just in case.",
"created_at": "2020-08-10T15:59:57Z"
},
{
"body": "I really don't know the best way to solve this. @staudenmeir really knows the most about this situation since he wrote the code to change this behavior.",
"created_at": "2020-09-23T19:58:01Z"
},
{
"body": "> I need to make this kind of query quite a bit, it's actually preventing me from upgrading past laravel 5.8.\r\n> It seems like a real tricky issue to solve. The old way can't do outer joins, but can reference joined values... while the new way is the opposite, allowing outer joins, but can't reference joined values.\r\n> \r\n> In my particular situation, I need to update the values in `table_1` to be an aggregate of values from `table_2`, but some rows in `table_2` are filtered out, and I'd like the update query to set the `table_1` values for those rows to null. This seems to require an outer join, otherwise the rows in `table_1` are removed by the inner join, and not updated at all.\r\n> \r\n> How I'm currently handling this on 5.8 is using sub-queries. I perform the outer join between `table_1` and `table_2` in a sub-query, and then inner join `table_1` with a duplicate of itself in the update statement. It looks something like this\r\n> \r\n> ```\r\n> $subQuery2 = DB::table('table2')->where('column', $filter);\r\n> \r\n> $subQuery1 = DB::table('table1')->leftJoinSub($subQuery2, 'sub2', 'sub2.primary_key, '=', 'sub1.foreign_key`);\r\n> \r\n> $update = DB:table('table1')->joinSub($subQuery1, 'sub1', 'sub1.primary_key, '=', 'table1.primary_key`)\r\n> ->update(['table1.value' => DB::raw('table2.value')]);\r\n> ```\r\n> \r\n> I'm not sure if this helps anyone, but figured I'd mention it just in case.\r\n\r\nI've recently cleaned this up as an extension of PostgresGrammar.php (still on laravel v5.8). I've written it as a method which takes all left joins, and nests them inside a dummy table that uses a normal inner join. I call it at the beginning of the `compileUpdate()` method using `$query = $this->setUpdateLeftJoins($query);`\r\n\r\n```\r\n\t/**\r\n\t * Transform left joins into a functional postgres query\r\n\t *\r\n\t * @param \\Illuminate\\Database\\Query\\Builder $query\r\n\t * @return \\Illuminate\\Database\\Query\\Builder $query\r\n\t */\r\n\tprotected function setUpdateLeftJoins($query)\r\n\t{\r\n\t\t// remove left joins from query\r\n\t\t$leftJoins = collect($query->joins)->where('type', 'left');\r\n\t\t$query->joins = collect($query->joins)->where('type', '!=', 'left')->all();\r\n\r\n\t\t// join a duplicate of the base table\r\n\t\t// move left joins, nesting them within the duplicate table join\r\n\t\tif ($leftJoins->count())\r\n\t\t{\r\n\t\t\t$table = $query->from;\r\n\t\t\t$tableDuplicate = $query->from . '_duplicate';\r\n\r\n\t\t\t$primaryKey = 'id';\r\n\t\t\t$query->join(\"{$table} as {$tableDuplicate}\", \"{$table}.{$primaryKey}\", '=', \"{$tableDuplicate}.{$primaryKey}\");\r\n\r\n\t\t\tforeach ($leftJoins as $i => $leftJoin)\r\n\t\t\t{\r\n\t\t\t\tforeach ($leftJoin->wheres as $j => $where)\r\n\t\t\t\t{\r\n\t\t\t\t\t$leftJoins[$i]->wheres[$j]['first'] = preg_replace(\"/^({$table})\\./\", \"{$tableDuplicate}.\", $where['first']);\r\n\t\t\t\t\t$leftJoins[$i]->wheres[$j]['second'] = preg_replace(\"/^({$table})\\./\", \"{$tableDuplicate}.\", $where['second']);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t$query->joins[array_key_last($query->joins)]->joins = $leftJoins;\r\n\t\t}\r\n\r\n\t\treturn $query;\r\n\t}\r\n```\r\n\r\n\r\nThis is definitely not a perfect solution, but hopefully it's some help in resolving this issue properly.\r\n\r\nIn case anyone would like to improve on this, here's some of the current issues I'm dealing with...\r\n- get the base tables primary key dynamically and handle composite primary keys (used to join the duplicate table). Currently I have it hardcoded as `id` (which works fine for my own personal use)\r\n- The `preg_replace` on the leftJoin's where statements is kinda hacky. I'm trying to find a cleaner way of doing this.\r\n- Advice on if manually setting a query's `joins` attribute is safe to do. Should I instead be re-adding each leftJoin using querybuilder's `->join()` method?\r\n- Advice on a safe non-conflicting naming convention for the duplicate table's alias\r\n- General testing with more complicated update statements. So far it's working properly for all my app's queries... but they're all relatively simple.\r\n\r\n\r\n\r\n\r\n\r\n**EDIT**\r\nRe-wrote it again, inspired by the `runPaginationCountQuery()` method of `Illuminate\\Database\\Query\\Builder`. I feel this is a MUCH cleaner implementation.\r\n```\r\n\t/**\r\n\t * Transform left joins into a functional postgres query\r\n\t *\r\n\t * @param \\Illuminate\\Database\\Query\\Builder $query\r\n\t * @return \\Illuminate\\Database\\Query\\Builder $query\r\n\t */\r\n\tprotected function setUpdateLeftJoins($query)\r\n\t{\r\n\t\t// check for left joins, skip if none exist\r\n\t\t$hasLeftJoins = collect($query->joins)->contains(function ($item) { return $item->type == 'left'; });\r\n\r\n\t\tif ($hasLeftJoins)\r\n\t\t{\r\n\t\t\t// set table params\r\n\t\t\t$tableName = $query->from;\r\n\t\t\t$tableAlias = $query->from . '_duplicate';\r\n\t\t\t$primaryKey = 'id';\r\n\r\n\t\t\t// duplicate the query, to be used as the new main query\r\n\t\t\t$without = ['columns', 'orders', 'limit', 'offset', 'wheres', 'where'];\r\n\t\t\t$dupeQuery = $query->cloneWithout($without)\r\n\t\t\t\t->cloneWithoutBindings($without);\r\n\r\n\t\t\t// give the duplicate(parent) query an alias, so the original(child) query can remain unaltered\r\n\t\t\t$dupeQuery->from = \"{$tableName} as {$tableAlias}\";\r\n\r\n\t\t\t// manually attach the parent and child queries, mimicking the logic performed by `$query->join()`\r\n\t\t\t$query->table = $query->from;\r\n\t\t\t$query->type = 'inner';\r\n\t\t\t$query->whereColumn(\"{$tableName}.{$primaryKey}\", '=', \"{$tableAlias}.{$primaryKey}\");\r\n\t\t\t$dupeQuery->joins = [$query];\r\n\r\n\t\t\t// #TODO - write a function to properly convert `Illuminate\\Database\\Query\\Builder` to `Illuminate\\Database\\Query\\JoinClause`\r\n\t\t\t//\tand replace the above logic with a `$dupeQuery->join($query, ...)`\r\n\r\n\t\t\t$query = $dupeQuery;\r\n\t\t}\r\n\r\n\t\treturn $query;\r\n\t}\r\n```",
"created_at": "2020-12-21T21:42:01Z"
},
{
"body": "Hey all, I managed to get a draft PR up that should solve this issue. It's not the most ideal solution but it would solve the broken queries here: https://github.com/laravel/framework/pull/39151\r\n\r\nI'd appreciate a review from everyone in this thread, especially @staudenmeir @hyde1 @vitsw & @peanutsmcgee. Please reply on the PR if you can.",
"created_at": "2021-10-08T10:51:56Z"
},
{
"body": "Hey all, since no one has replied so far, I'm submitting the PR as-is for Taylor to review.",
"created_at": "2021-10-12T07:26:54Z"
},
{
"body": "Looks good to me. It doesn't handle left joins, but that's really a\nseparate issue.\n\nOn Tue, Oct 12, 2021, 3:27 AM Dries Vints ***@***.***> wrote:\n\n> Hey all, since no one has replied so far, I'm submitting the PR as-is for\n> Taylor to review.\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/laravel/framework/issues/33265#issuecomment-940739624>,\n> or unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AQL3BH3SZQGJQZKWSPJE3MTUGPPMTANCNFSM4OBS6CDA>\n> .\n> Triage notifications on the go with GitHub Mobile for iOS\n> <https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>\n> or Android\n> <https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.\n>\n>\n",
"created_at": "2021-10-12T14:22:05Z"
}
],
"number": 33265,
"title": "Postgresql update: removed support for \"update ... from ...\" statement in 6.x and 7.x"
} | {
"body": "This PR re-introduces \"update ... from ...\" support for the PostgreSQL grammar. Since there wasn't a good option or straight way to re-implement the behavior after the refactor in #29393 I opted to add a new dedicated `updateFrom` method specifically for the PostgreSQL grammar.\r\n\r\nThis implementation is a bit cumbersome and crude as people will need to specifically use `updateFrom` instead of `update` if they want the correct behavior. Ideally this would be done automatically.\r\n\r\nI've tested this with the queries from #33265 and got them back working with this. I also re-added the original tests that were removed.\r\n\r\nBefore merging this I'd like to:\r\n\r\n- Get a review from @staudenmeir\r\n- Get feedback from people who reported #33265\r\n- Maybe clean up the code in the PostgreSQL grammar\r\n\r\nIf we get feedback from someone who can think of a better way to solve this then gladly. Otherwise I think this is the only solution for the problem at hand.\r\n\r\nFixes #33265\r\n",
"number": 39151,
"review_comments": [],
"title": "[8.x] Re-add update from support for PostgreSQL"
} | {
"commits": [
{
"message": "Re-add update from"
},
{
"message": "Apply fixes from StyleCI"
},
{
"message": "Update Builder.php"
}
],
"files": [
{
"diff": "@@ -20,6 +20,7 @@\n use Illuminate\\Support\\Traits\\ForwardsCalls;\n use Illuminate\\Support\\Traits\\Macroable;\n use InvalidArgumentException;\n+use LogicException;\n use RuntimeException;\n \n class Builder\n@@ -3000,6 +3001,27 @@ public function update(array $values)\n ));\n }\n \n+ /**\n+ * Update records in a PostgreSQL database using the update from syntax.\n+ *\n+ * @param array $values\n+ * @return int\n+ */\n+ public function updateFrom(array $values)\n+ {\n+ if (! method_exists($this->grammar, 'compileUpdateFrom')) {\n+ throw new LogicException('This database engine does not support the updateFrom method.');\n+ }\n+\n+ $this->applyBeforeQueryCallbacks();\n+\n+ $sql = $this->grammar->compileUpdateFrom($this, $values);\n+\n+ return $this->connection->update($sql, $this->cleanBindings(\n+ $this->grammar->prepareBindingsForUpdateFrom($this->bindings, $values)\n+ ));\n+ }\n+\n /**\n * Insert or update a record matching the attributes, and fill it with values.\n *",
"filename": "src/Illuminate/Database/Query/Builder.php",
"status": "modified"
},
{
"diff": "@@ -260,6 +260,114 @@ protected function compileJsonUpdateColumn($key, $value)\n return \"{$field} = jsonb_set({$field}::jsonb, {$path}, {$this->parameter($value)})\";\n }\n \n+ /**\n+ * Compile an update from statement into SQL.\n+ *\n+ * @param \\Illuminate\\Database\\Query\\Builder $query\n+ * @param array $values\n+ * @return string\n+ */\n+ public function compileUpdateFrom(Builder $query, $values)\n+ {\n+ $table = $this->wrapTable($query->from);\n+\n+ // Each one of the columns in the update statements needs to be wrapped in the\n+ // keyword identifiers, also a place-holder needs to be created for each of\n+ // the values in the list of bindings so we can make the sets statements.\n+ $columns = $this->compileUpdateColumns($query, $values);\n+\n+ $from = '';\n+\n+ if (isset($query->joins)) {\n+ // When using Postgres, updates with joins list the joined tables in the from\n+ // clause, which is different than other systems like MySQL. Here, we will\n+ // compile out the tables that are joined and add them to a from clause.\n+ $froms = collect($query->joins)->map(function ($join) {\n+ return $this->wrapTable($join->table);\n+ })->all();\n+\n+ if (count($froms) > 0) {\n+ $from = ' from '.implode(', ', $froms);\n+ }\n+ }\n+\n+ $where = $this->compileUpdateWheres($query);\n+\n+ return trim(\"update {$table} set {$columns}{$from} {$where}\");\n+ }\n+\n+ /**\n+ * Compile the additional where clauses for updates with joins.\n+ *\n+ * @param \\Illuminate\\Database\\Query\\Builder $query\n+ * @return string\n+ */\n+ protected function compileUpdateWheres(Builder $query)\n+ {\n+ $baseWheres = $this->compileWheres($query);\n+\n+ if (! isset($query->joins)) {\n+ return $baseWheres;\n+ }\n+\n+ // Once we compile the join constraints, we will either use them as the where\n+ // clause or append them to the existing base where clauses. If we need to\n+ // strip the leading boolean we will do so when using as the only where.\n+ $joinWheres = $this->compileUpdateJoinWheres($query);\n+\n+ if (trim($baseWheres) == '') {\n+ return 'where '.$this->removeLeadingBoolean($joinWheres);\n+ }\n+\n+ return $baseWheres.' '.$joinWheres;\n+ }\n+\n+ /**\n+ * Compile the \"join\" clause where clauses for an update.\n+ *\n+ * @param \\Illuminate\\Database\\Query\\Builder $query\n+ * @return string\n+ */\n+ protected function compileUpdateJoinWheres(Builder $query)\n+ {\n+ $joinWheres = [];\n+\n+ // Here we will just loop through all of the join constraints and compile them\n+ // all out then implode them. This should give us \"where\" like syntax after\n+ // everything has been built and then we will join it to the real wheres.\n+ foreach ($query->joins as $join) {\n+ foreach ($join->wheres as $where) {\n+ $method = \"where{$where['type']}\";\n+\n+ $joinWheres[] = $where['boolean'].' '.$this->$method($query, $where);\n+ }\n+ }\n+\n+ return implode(' ', $joinWheres);\n+ }\n+\n+ /**\n+ * Prepare the bindings for an update statement.\n+ *\n+ * @param array $bindings\n+ * @param array $values\n+ * @return array\n+ */\n+ public function prepareBindingsForUpdateFrom(array $bindings, array $values)\n+ {\n+ $values = collect($values)->map(function ($value, $column) {\n+ return is_array($value) || ($this->isJsonSelector($column) && ! $this->isExpression($value))\n+ ? json_encode($value)\n+ : $value;\n+ })->all();\n+\n+ $bindingsWithoutWhere = Arr::except($bindings, ['select', 'where']);\n+\n+ return array_values(\n+ array_merge($values, $bindings['where'], Arr::flatten($bindingsWithoutWhere))\n+ );\n+ }\n+\n /**\n * Compile an update statement with joins or limit into SQL.\n *",
"filename": "src/Illuminate/Database/Query/Grammars/PostgresGrammar.php",
"status": "modified"
},
{
"diff": "@@ -2437,6 +2437,32 @@ public function testUpdateMethodWithJoinsOnPostgres()\n $this->assertEquals(1, $result);\n }\n \n+ public function testUpdateFromMethodWithJoinsOnPostgres()\n+ {\n+ $builder = $this->getPostgresBuilder();\n+ $builder->getConnection()->shouldReceive('update')->once()->with('update \"users\" set \"email\" = ?, \"name\" = ? from \"orders\" where \"users\".\"id\" = ? and \"users\".\"id\" = \"orders\".\"user_id\"', ['foo', 'bar', 1])->andReturn(1);\n+ $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->updateFrom(['email' => 'foo', 'name' => 'bar']);\n+ $this->assertEquals(1, $result);\n+\n+ $builder = $this->getPostgresBuilder();\n+ $builder->getConnection()->shouldReceive('update')->once()->with('update \"users\" set \"email\" = ?, \"name\" = ? from \"orders\" where \"users\".\"id\" = \"orders\".\"user_id\" and \"users\".\"id\" = ?', ['foo', 'bar', 1])->andReturn(1);\n+ $result = $builder->from('users')->join('orders', function ($join) {\n+ $join->on('users.id', '=', 'orders.user_id')\n+ ->where('users.id', '=', 1);\n+ })->updateFrom(['email' => 'foo', 'name' => 'bar']);\n+ $this->assertEquals(1, $result);\n+\n+ $builder = $this->getPostgresBuilder();\n+ $builder->getConnection()->shouldReceive('update')->once()->with('update \"users\" set \"email\" = ?, \"name\" = ? from \"orders\" where \"name\" = ? and \"users\".\"id\" = \"orders\".\"user_id\" and \"users\".\"id\" = ?', ['foo', 'bar', 'baz', 1])->andReturn(1);\n+ $result = $builder->from('users')\n+ ->join('orders', function ($join) {\n+ $join->on('users.id', '=', 'orders.user_id')\n+ ->where('users.id', '=', 1);\n+ })->where('name', 'baz')\n+ ->updateFrom(['email' => 'foo', 'name' => 'bar']);\n+ $this->assertEquals(1, $result);\n+ }\n+\n public function testUpdateMethodRespectsRaw()\n {\n $builder = $this->getBuilder();",
"filename": "tests/Database/DatabaseQueryBuilderTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 6.20.34\r\n- PHP Version: 7.4.2\r\n- Database Driver & Version:\r\nmysql 5.7.34-log\r\n\r\n### Description:\r\nAfter LazyCollection calls the unique method and then calls the isEmpty method, a piece of data will be lost.\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n```php\r\n// The offending code snippet:\r\n$items = \\Illuminate\\Support\\LazyCollection::make(fn () => yield from [['id' => '1'], ['id' => '2'], ['id' => '4']]);\r\ndump($items->toArray()); // Output: [['id' => '1'], ['id' => '2'], ['id' => '4']]\r\n$unique_items = $items->unique('id');\r\n// If the output is here, there is no problem, but `LazyCollection::isEmpty()` will return true.\r\n// dump($unique_items->toArray()); // Output: [['id' => '1'], ['id' => '2'], ['id' => '4']]\r\nif (!$unique_items->isEmpty()) {\r\n // When I judge whether it is a null value, I lost a value.\r\n dump($unique_items->toArray()); // Output: [['id' => '2'], ['id' => '4']]\r\n}\r\n\r\n// Everything is normal for this part of the code.\r\n$items = \\Illuminate\\Support\\Collection::make([['id' => '1'], ['id' => '2'], ['id' => '4']]);\r\ndump($items->toArray());\r\n$items = $items->unique('id');\r\nif (!$items ->isEmpty()) {\r\n dump($items ->toArray());\r\n}\r\n```",
"comments": [
{
"body": "@JosephSilber I guess this works as expected but wanted to confirm with you.",
"created_at": "2021-09-28T11:33:19Z"
},
{
"body": "> I guess this works as expected\r\n\r\nIt does not. It's broken.\r\n\r\nYou can see the problem more easily with this piece of code:\r\n\r\n```php\r\n$items = LazyCollection::make(function () {\r\n yield 1;\r\n yield 2;\r\n yield 3;\r\n});\r\n\r\n$items\r\n ->unique()\r\n ->tap(fn ($collection) => $collection->take(2)->eager())\r\n ->dd(); // [3]\r\n```\r\n\r\nThat call to `take(2)->eager()` consumed the first 2 items, so the subsequent enumeration is missing that.\r\n\r\nThat's not expected. Separate enumerations should never affect each other.\r\n\r\n---\r\n\r\nI'll work on a fix.",
"created_at": "2021-09-30T05:36:04Z"
},
{
"body": "Thanks @JosephSilber ",
"created_at": "2021-09-30T09:33:55Z"
}
],
"number": 38817,
"title": "After LazyCollection calls the unique method and then calls the isEmpty method, a piece of data will be lost."
} | {
"body": "Fixes #38817",
"number": 39041,
"review_comments": [
{
"body": "Just to explain why this didn't work:\r\n\r\nThe call to `$this->reject` returned a new `LazyCollection` instance. Every time the collection is enumerated, the callback (that was passed to `reject`) gets called again, but it's reusing the same `$exists` cache of found items, so anything that was previously enumerated is treated as a duplicate :frowning: \r\n\r\nThe solution is to have a separate implementation of the `unique()` method for the `LazyCollection` class. In that implementation, we can move the `$exists` cache into the `Generator` function passed to the constructor, so that each enumeration has its own cache :+1: ",
"created_at": "2021-09-30T05:58:17Z"
},
{
"body": "I would consider this a breaking change.\r\n\r\nMaybe you can only add the unique Method to the Lazy Collection and let the normal Collection stay the same with using the EnumeratesValues Trait.",
"created_at": "2021-09-30T09:22:34Z"
},
{
"body": "The `EnumeratesValues` trait was never meant to be consumed by the public. It's an internal trait that's only there to house the shared code between the two collection classes. I can't really believe anyone is using this trait in the wild.\r\n\r\nI'll let Taylor decide whether he considers this a breaking change.",
"created_at": "2021-09-30T14:52:15Z"
},
{
"body": "Laravel Nova global search is not working anymore because of this fix...\r\n\r\n`Class Illuminate\\Support\\LazyCollection contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Illuminate\\Support\\Enumerable::unique)`",
"created_at": "2021-10-07T18:49:47Z"
},
{
"body": "@RomanNebesnuyGC is your comment intentionally in this thread, or you meant to comment generally on the PR?\r\n\r\nCan you paste the actual stack trace?",
"created_at": "2021-10-07T20:21:39Z"
},
{
"body": "@JosephSilber \r\nYes my comment only for this thread, because if I will back this part of code all is working fine.\r\n\r\n```\r\nSymfony\\Component\\ErrorHandler\\Error\\FatalError\r\nClass Illuminate\\Support\\LazyCollection contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Illuminate\\Support\\Enumerable::unique)\r\n```\r\n\r\nit's FatalError\r\nLaravel Nova use ```->cursor()``` in global search (vendor/laravel/nova/src/GlobalSearch.php@60)\r\n<img width=\"890\" alt=\"Снимок экрана 2021-10-08 в 19 54 37\" src=\"https://user-images.githubusercontent.com/77343542/136594585-6c4f7cf7-0dde-4573-9efc-b2882482b1ee.png\">\r\n.\r\n\r\nSo it's globally broken. Everywhere when you want to use ```->cursor()``` in Eloquent it will be this FatalError.\r\n\r\nLaravel: 8.63.0 (on 8.62.0 all is ok)\r\nPHP: 7.4.23 & 8.0.10\r\nLaravel Nova: 3.29.0\r\n",
"created_at": "2021-10-08T16:59:53Z"
},
{
"body": "I created [a sample repository](https://github.com/JosephSilber/laravel-test-cursor) (with a readme) showing that the `cursor()` method is not broken.\r\n\r\n@RomanNebesnuyGC Can you please create a PR to that repository that shows how it's broken?",
"created_at": "2021-10-10T03:44:42Z"
},
{
"body": "@JosephSilber sorry all is ok. It's my fault. All is working perfectly.\r\nIn our project we use a lot of extensions (something like https://github.com/nWidart/laravel-modules) and they have in composer required illuminate/support that required illuminate/collections and I need only to update all extensions. Problem was that core composer was with illuminate/support 8.63, but extensions on 8.62.. )",
"created_at": "2021-10-10T08:03:16Z"
}
],
"title": "[8.x] Fix LazyCollection#unique() double enumeration"
} | {
"commits": [
{
"message": "Fix LazyCollection#unique() double enumeration\n\nFixes #38817"
}
],
"files": [
{
"diff": "@@ -1411,6 +1411,28 @@ public function transform(callable $callback)\n return $this;\n }\n \n+ /**\n+ * Return only unique items from the collection array.\n+ *\n+ * @param string|callable|null $key\n+ * @param bool $strict\n+ * @return static\n+ */\n+ public function unique($key = null, $strict = false)\n+ {\n+ $callback = $this->valueRetriever($key);\n+\n+ $exists = [];\n+\n+ return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {\n+ if (in_array($id = $callback($item, $key), $exists, $strict)) {\n+ return true;\n+ }\n+\n+ $exists[] = $id;\n+ });\n+ }\n+\n /**\n * Reset the keys on the underlying array.\n *",
"filename": "src/Illuminate/Collections/Collection.php",
"status": "modified"
},
{
"diff": "@@ -1352,6 +1352,30 @@ public function tapEach(callable $callback)\n });\n }\n \n+ /**\n+ * Return only unique items from the collection array.\n+ *\n+ * @param string|callable|null $key\n+ * @param bool $strict\n+ * @return static\n+ */\n+ public function unique($key = null, $strict = false)\n+ {\n+ $callback = $this->valueRetriever($key);\n+\n+ return new static(function () use ($callback, $strict) {\n+ $exists = [];\n+\n+ foreach ($this as $key => $item) {\n+ if (! in_array($id = $callback($item, $key), $exists, $strict)) {\n+ yield $key => $item;\n+\n+ $exists[] = $id;\n+ }\n+ }\n+ });\n+ }\n+\n /**\n * Reset the keys on the underlying array.\n *",
"filename": "src/Illuminate/Collections/LazyCollection.php",
"status": "modified"
},
{
"diff": "@@ -773,28 +773,6 @@ public function reject($callback = true)\n });\n }\n \n- /**\n- * Return only unique items from the collection array.\n- *\n- * @param string|callable|null $key\n- * @param bool $strict\n- * @return static\n- */\n- public function unique($key = null, $strict = false)\n- {\n- $callback = $this->valueRetriever($key);\n-\n- $exists = [];\n-\n- return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {\n- if (in_array($id = $callback($item, $key), $exists, $strict)) {\n- return true;\n- }\n-\n- $exists[] = $id;\n- });\n- }\n-\n /**\n * Return only unique items from the collection array using strict comparison.\n *",
"filename": "src/Illuminate/Collections/Traits/EnumeratesValues.php",
"status": "modified"
},
{
"diff": "@@ -203,4 +203,13 @@ public function testTapEach()\n $this->assertSame([1, 2, 3, 4, 5], $data);\n $this->assertSame([1, 2, 3, 4, 5], $tapped);\n }\n+\n+ public function testUniqueDoubleEnumeration()\n+ {\n+ $data = LazyCollection::times(2)->unique();\n+\n+ $data->all();\n+\n+ $this->assertSame([1, 2], $data->all());\n+ }\n }",
"filename": "tests/Support/SupportLazyCollectionTest.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.61.0\r\n- PHP Version: 8.0.3\r\n- Database Driver & Version: MYSQL\r\n\r\n### Description:\r\n\r\nAnonymous cast class is not invoked during serialization although `serialize` method is implemented.\r\n\r\nRelated docs:\r\n\r\n- https://laravel.com/docs/8.x/eloquent-mutators#anonymous-cast-classes\r\n- https://laravel.com/docs/8.x/eloquent-mutators#array-json-serialization\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\nclass Product extends Model\r\n{\r\n public $timestamps = false;\r\n\r\n protected $casts = [\r\n 'sku' => Sku::class,\r\n ];\r\n}\r\n\r\nclass Sku implements Castable\r\n{\r\n private string $sku;\r\n\r\n public function __construct(string $sku)\r\n {\r\n $this->sku = $sku;\r\n }\r\n\r\n public function getValue()\r\n {\r\n return $this->sku;\r\n }\r\n\r\n public static function castUsing(array $arguments)\r\n {\r\n return new class implements CastsAttributes, SerializesCastableAttributes\r\n {\r\n public function get($model, string $key, $value, array $attributes)\r\n {\r\n return new Sku($value);\r\n }\r\n\r\n public function set($model, string $key, $value, array $attributes)\r\n {\r\n return $value->getValue();\r\n }\r\n\r\n public function serialize($model, string $key, $value, array $attributes)\r\n {\r\n return $value->getValue();\r\n }\r\n };\r\n }\r\n}\r\n\r\n$product = new Product();\r\n$product->sku = new Sku('UGG-BB-PUR-06');\r\n$product->save();\r\n\r\ndump(Product::all()->toArray()); \r\n```\r\n\r\nThis is what i'm getting:\r\n\r\n```\r\n^ array:1 [\r\n 0 => array:2 [\r\n \"id\" => 1\r\n \"sku\" => Sku^ {#19\r\n -sku: \"UGG-BB-PUR-06\"\r\n }\r\n ]\r\n]\r\n```\r\n\r\nThis is what i should be getting:\r\n\r\n```\r\n^ array:1 [\r\n 0 => array:2 [\r\n \"id\" => 1\r\n \"sku\" => \"UGG-BB-PUR-06\"\r\n ]\r\n]\r\n```\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Thanks, I've sent in a PR to the docs to clarify this: https://github.com/laravel/docs/pull/7322",
"created_at": "2021-09-28T11:52:38Z"
},
{
"body": "We're going to treat this as a bug instead.",
"created_at": "2021-09-28T13:55:31Z"
}
],
"number": 38811,
"title": "Castable value object is not serialized correctly"
} | {
"body": "Fixes #38811",
"number": 39020,
"review_comments": [],
"title": "Fix castable value object not serialized correctly"
} | {
"commits": [
{
"message": "Fix castable value object not serialized correctly"
}
],
"files": [
{
"diff": "@@ -1308,7 +1308,7 @@ protected function isClassDeviable($key)\n protected function isClassSerializable($key)\n {\n return $this->isClassCastable($key) &&\n- method_exists($this->parseCasterClass($this->getCasts()[$key]), 'serialize');\n+ method_exists($this->resolveCasterClass($key), 'serialize');\n }\n \n /**",
"filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php",
"status": "modified"
},
{
"diff": "@@ -230,6 +230,7 @@ public function testWithCastableInterface()\n ]);\n \n $this->assertInstanceOf(ValueObject::class, $model->value_object_with_caster);\n+ $this->assertSame(serialize(new ValueObject('hello')), $model->toArray()['value_object_with_caster']);\n \n $model->setRawAttributes([\n 'value_object_caster_with_argument' => null,\n@@ -418,7 +419,7 @@ public function __construct(string $name)\n \n public static function castUsing(array $arguments)\n {\n- return new class(...$arguments) implements CastsAttributes\n+ return new class(...$arguments) implements CastsAttributes, SerializesCastableAttributes\n {\n private $argument;\n \n@@ -440,6 +441,11 @@ public function set($model, $key, $value, $attributes)\n {\n return serialize($value);\n }\n+\n+ public function serialize($model, $key, $value, $attributes)\n+ {\n+ return serialize($value);\n+ }\n };\n }\n }",
"filename": "tests/Integration/Database/DatabaseEloquentModelCustomCastingTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 6.13.1\r\n- PHP Version: 7.2.27\r\n- Database Driver & Version: Redis\r\n\r\n### Description:\r\n`RedisStore::serialize()` and `unserialize()` don't do right when it comes to caching numbers. I think the code has some considerations that Redis stores strings that are integers more efficient than normal integers. But the implementation is wrong.\r\nFrom https://redis.io/commands/INCR:\r\n> Redis stores integers in their integer representation, so for string values that actually hold an integer, there is no overhead for storing the string representation of the integer.\r\n\r\n### Steps To Reproduce:\r\nSet cache driver to redis and try the followings:\r\n```php\r\nCache::put('test', '1');\r\nCache::get('test');; // expected = actual = \"1\"\r\nCache::put('test', 1);\r\nCache::get('test'); // expected: 1, actual \"1\"\r\nCache::put('test', 1.0);\r\nCache::get('test'); // expected: 1.0, actual \"1\"\r\nCache::put('test', INF)\r\nCache::get('test'); // expected INF, actual: PHP Notice: unserialize(): Error at offset 0 of 3 bytes\r\nCache::put('test', -INF)\r\nCache::get('test'); // expected -INF, actual: PHP Notice: unserialize(): Error at offset 0 of 4 bytes\r\nCache::put('test', NAN);\r\nCache::get('test');// expected: NAN, actual: PHP Notice: unserialize(): Error at offset 0 of 3 bytes \r\n```\r\nI don't know if other drivers have similar issues.\r\n",
"comments": [
{
"body": "Managed to reproduce this. Sending in a fix. Also not really sure about other stores.",
"created_at": "2020-02-04T13:04:07Z"
},
{
"body": "Should the complete fix be for the next major release, as considering returning 1 instead of \"1\" be a possible breaking change?",
"created_at": "2020-02-04T13:10:38Z"
},
{
"body": "@halaei I guess this is now completely broken atm and never worked? I sent in a fix here: https://github.com/laravel/framework/pull/31348\r\n\r\nLet me know what you think.",
"created_at": "2020-02-04T13:21:50Z"
},
{
"body": "Came across this today when we tried switching to redis. Some of the stuff in our cache is type sensitive, so when some of the cache keys went from `1` to `\"1\"` the `===` checks failed.\r\n\r\nIt seems this is sort of broken for all numeric strings, since `is_numeric()` is being used, and then skips serializing it. Why not just consistently serialize everything before storing it, like in the file and memcached stores? A quick test shows me that the outcome of `Cache::put('test', 123)` with the cache drivers `file`, `array`, `database`, `apc` and `memcached` all return an integer, but for `redis` I get a string.",
"created_at": "2020-05-16T17:50:58Z"
},
{
"body": "@carestad I agree. These are some reasons for the inconsistency, although I don't think they are good enough:\r\n1. Storing integers without serialization makes it possible to use incr, decr, incrby, and decrby Redis commands to implement Cache::increment() and Cache::decrement() functions.\r\n2. Storing float without serialization makes use of incrbyfloat command possible, altough it is not used in Laravel. So floating point increment is not yet support.\r\n3. (Less important) Storing integers as integer in Redis causes some considerable memory reduction when storing a lot of integers, something near 10x I guess.\r\n\r\nI suggest to update Redis driver to only skip serialization if the data type is int, but not when the data is float or a numeric string. This change probably is a breaking change for some other applications.\r\nSome configuration options may be helpful to make things BC and let users to store floats without serialization as well.",
"created_at": "2020-05-16T19:42:06Z"
},
{
"body": "@halaei Tough one. It all boils down to the fact that redis don't have its own numerical type I suppose.\r\n\r\nBut I was not really aware of this before trying it out. I feel like this should be mentioned in the documentation somewhere, that integers and float types will not be preserved when using redis? Especially since all the other cache providers does this (haven't tried dynamodb and apc yet though so I can't say 100% for that one, but I have tested `file`, `array`, `database` and `memcached`). So switching from anyone of the other cache providers to redis could easily cause problems in type-aware applications.\r\n\r\nWhat about a `force_numeric_serialization` config option that defaults to false, but can be overridden? Either always force-run the value through `serialize()` when setting and `unserialize()` when getting, or force-cast numeric strings to int/float (only when getting). And when that option is set, the increment/decrement functions will need to compute this in PHP instead of using redis' own `INCR`/`DECR`. But I'd much rather have consistency between caching providers than how it is right now.",
"created_at": "2020-05-17T22:38:35Z"
},
{
"body": "Just got burned by this as we switched our cache store from database to redis - suddenly this throws an error on the second call:\r\n\r\n```php\r\nfunction foo(): int\r\n{\r\n return Cache::remember('foo', 60, function() {\r\n return 1;\r\n });\r\n}\r\n```\r\n=> `expected int but got string instead`\r\n\r\nIs there any fix other than manually casting to int everywhere that's the expected type? The fix that closes this issue (#31348) deals with storing `INF` values, but that's not the whole problem here.",
"created_at": "2021-05-24T13:51:45Z"
},
{
"body": "@robin-vendredi\r\n\r\nyou can use PHP’s serialize/unserialize to store type info",
"created_at": "2021-05-24T13:59:12Z"
},
{
"body": "@lptn Thanks for your reply. \r\n\r\nIf I understand it correctly, this would look something like `return serialize(1);`? I would be afraid it might lead to double serialization (esp. if I switch cache driver in future), and I'd hope for a more global solution where I don't have to remember that \"integer needs to be manually serialized each time\" and my code breaks if I forget.\r\n\r\nI could write a custom driver extending the [RedisStore](https://github.com/laravel/framework/blob/8.x/src/Illuminate/Cache/RedisStore.php) to not skip the integer serialization they are doing here: https://github.com/laravel/framework/blob/6718ae61acac3bfb7f88a9769ed74c1e39240861/src/Illuminate/Cache/RedisStore.php#L332-L335\r\n\r\nBut that would have an impact on the `increment`/`decrement` functions too and I'd like to avoid writing my own store. Are there any other solutions?",
"created_at": "2021-05-24T14:09:13Z"
},
{
"body": "Can this be reopened? This inconsistency bug is still present in laravel 8",
"created_at": "2021-09-23T08:09:24Z"
},
{
"body": "Running into this whilst profiling/memory tuning redis, if this is fixed, it would provide a big memory saving:\r\n\r\n> Sets that contain only integers are extremely efficient memory wise. If your set contains strings, try to use integers by mapping string identifiers to integers.\r\n> You can either use enums in your programming language, or you can use a redis hash data structure to map values to integers. Once you switch to integers, Redis will use the IntSet encoding internally.",
"created_at": "2021-12-14T00:59:07Z"
},
{
"body": "Why this is closed when it's not fixed or resolved anyhow? @taylorotwell your PR closed this, not sure if this was mistake or what.",
"created_at": "2022-04-05T11:45:54Z"
}
],
"number": 31345,
"title": "Redis cache store issues on numeric values"
} | {
"body": "In order to optimize memory consumption and make `RedisStore::increment()` and `RedisStore::decrement()` work using the built-in Redis `incrby` and `decrby` commands, numeric values are stored as their base 10 string representation. Sadly, it causes a type inconsistency issue. If we get a numeric string from Redis, we can't know if the original value was string or int/float. Currently Laraval returns all numeric values as string:\r\n```php\r\nCache::put('k', 1);\r\ndump(is_int(Cache::get('k'))); // Must be true, but it is false.\r\ndump(is_string(Cache::get('k'))); // Must be false, but it is true. \r\n```\r\nThis PR tries to fix this type inconsistency by adding a \"strict\" mode option to Redis cache configuration, with the default value being true. It may be a breaking change. If the non-strict behavior is more appropriate for an existing application, strict should be set to false.\r\n\r\nAlternative choices regarding backward compatibility and the default behavior:\r\n1. Don't give any config option to disable the strict mode. Basically it was a bug to not preserve types, so why giving option to stick with the bug? Besides, other cache drivers don't have such option.\r\n2. Make sure by default strict mode is disabled so it doesn't cause an extra pain during the major upgrade. In case you choose this option you may consider sending a PR to 8.x as well. But be aware of the optional parameter to the constructor of `RedisStore`.\r\n\r\nLet me know if you prefer an alternative choice or the current PR. I can add some relevant tests later.\r\n\r\nNote: `incrby` and `decrby` Redis commands doesn't work with float values. Also Redis doesn't store non-integer numbers in a compressed way.\r\n\r\nFixes #31345\r\n",
"number": 38933,
"review_comments": [
{
"body": "I think this needs to be:\r\n\r\n```php\r\nif ($this->strict && filter_var($value, FILTER_VALIDATE_INT) !== false) {\r\n```\r\n\r\n`filter_var('0', FILTER_VALIDATE_INT)` evaluates to `0` which is PHP falsy so the string `'0'` is unexpectedly returned.",
"created_at": "2021-09-24T03:28:40Z"
},
{
"body": "Thanks @derekmd Fixed",
"created_at": "2021-09-24T07:46:48Z"
}
],
"title": "[9.x] Strict mode for RedisStore: preserve type of numeric values"
} | {
"commits": [
{
"message": "Strict mode for RedisStore: preserve type of numeric values"
},
{
"message": "Fix integer validation for 0"
}
],
"files": [
{
"diff": "@@ -199,7 +199,9 @@ protected function createRedisDriver(array $config)\n \n $connection = $config['connection'] ?? 'default';\n \n- $store = new RedisStore($redis, $this->getPrefix($config), $connection);\n+ $strict = $config['strict'] ?? true;\n+\n+ $store = new RedisStore($redis, $this->getPrefix($config), $connection, $strict);\n \n return $this->repository(\n $store->setLockConnection($config['lock_connection'] ?? $connection)",
"filename": "src/Illuminate/Cache/CacheManager.php",
"status": "modified"
},
{
"diff": "@@ -36,19 +36,28 @@ class RedisStore extends TaggableStore implements LockProvider\n */\n protected $lockConnection;\n \n+ /**\n+ * Whether to preserve type of numbers.\n+ *\n+ * @var bool\n+ */\n+ protected $strict;\n+\n /**\n * Create a new Redis store.\n *\n * @param \\Illuminate\\Contracts\\Redis\\Factory $redis\n * @param string $prefix\n * @param string $connection\n+ * @param bool $strict\n * @return void\n */\n- public function __construct(Redis $redis, $prefix = '', $connection = 'default')\n+ public function __construct(Redis $redis, $prefix = '', $connection = 'default', $strict = true)\n {\n $this->redis = $redis;\n $this->setPrefix($prefix);\n $this->setConnection($connection);\n+ $this->strict = $strict;\n }\n \n /**\n@@ -331,6 +340,10 @@ public function setPrefix($prefix)\n */\n protected function serialize($value)\n {\n+ if ($this->strict) {\n+ return is_int($value) ? $value : serialize($value);\n+ }\n+\n return is_numeric($value) && ! in_array($value, [INF, -INF]) && ! is_nan($value) ? $value : serialize($value);\n }\n \n@@ -342,6 +355,10 @@ protected function serialize($value)\n */\n protected function unserialize($value)\n {\n+ if ($this->strict && filter_var($value, FILTER_VALIDATE_INT) !== false) {\n+ return (int) $value;\n+ }\n+\n return is_numeric($value) ? $value : unserialize($value);\n }\n }",
"filename": "src/Illuminate/Cache/RedisStore.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 5.8.32\r\n- PHP Version: 7.3\r\n- Database Driver & Version: n/a\r\n\r\n### Description:\r\n\r\nWhen retrieving models through Eloquent, it emits the `retrieved` event prior to retrieving the eager loaded relations, if any. \r\n\r\nThe retrieval of the eager loaded relations are to be considered part of the retrieval process, otherwise you loose the benefit of eager loading anything if you are listening to the `retrieved` event to work with the related items.\r\n\r\n### Analysis:\r\n\r\nThis is what is being executed when [fetching models](https://github.com/illuminate/database/blob/341a3743d4dc97c54912dc1623dbebaeb772f70c/Eloquent/Model.php#L412):\r\n\r\n```php\r\npublic function get($columns = ['*'])\r\n{\r\n $builder = $this->applyScopes();\r\n // If we actually found models we will also eager load any relationships that\r\n // have been specified as needing to be eager loaded, which will solve the\r\n // n+1 query issue for the developers to avoid running a lot of queries.\r\n if (count($models = $builder->getModels($columns)) > 0) {\r\n $models = $builder->eagerLoadRelations($models);\r\n }\r\n return $builder->getModel()->newCollection($models);\r\n}\r\n```\r\n\r\nIf you dive into the `$builder->getModels($columns)` bit, you will see that the models are being instantiated in [this method](https://github.com/illuminate/database/blob/06144d5504b58972f4f1f1ce42bb62ca731ab7cb/Eloquent/Builder.php#L498):\r\n\r\n```php\r\npublic function newFromBuilder($attributes = [], $connection = null)\r\n{\r\n $model = $this->newInstance([], true);\r\n $model->setRawAttributes((array) $attributes, true);\r\n $model->setConnection($connection ?: $this->getConnectionName());\r\n $model->fireModelEvent('retrieved', false);\r\n return $model;\r\n}\r\n```\r\n\r\nAs you can see, the `retrieved` event is being fired here. However, the eager loading of the events is done *after*.\r\n\r\nIn an ideal world, the `retrieved` event should only be thrown _after_ the relations have been eager loaded, as you can now not approach any related model in your listener for the `retrieved` event without causing for an N+1 query issue. Now - for me - the retrieval is still ongoing (it still has to fetch the related models from the database) when the `retrieved` event is being thrown.\r\n\r\nPlease let me know if you need anything else.",
"comments": [
{
"body": "Bit torn about this being a bug or a potential improvement. I'll mark this as a bug for now. I don't have time to deep dive into this atm so any help is appreciated.",
"created_at": "2019-08-20T13:29:42Z"
},
{
"body": "I don't think we should change the current behavior:\r\n- I would argue that it's *technically* correct.\r\n- It would be a significant breaking change.\r\n\r\nWhat if we add a new event that fires *after* the eager loading?",
"created_at": "2019-08-20T13:41:23Z"
},
{
"body": "That might be a solution, but will that also work when retrieving ONE model?",
"created_at": "2019-08-20T13:46:56Z"
},
{
"body": "If we fire the event `Eloquent\\Builder::get()`, it will also work for `User::first()`.",
"created_at": "2019-08-20T13:55:09Z"
},
{
"body": "Yes but what with find()?",
"created_at": "2019-08-20T13:59:03Z"
},
{
"body": "Not sure of the implementation - can’t check as I’m in the car, but does that also pass through the same code there? The new event should be emitted for each retrieval, hence my question... And will you emit it also when there are no eager loaded relations?",
"created_at": "2019-08-20T14:01:22Z"
},
{
"body": "Yes, all these methods are handled by `get()`.\r\n\r\n> And will you emit it also when there are no eager loaded relations?\r\n\r\nYes, I think it should always fire.",
"created_at": "2019-08-20T14:07:29Z"
},
{
"body": "Then I agree this would definitely a viable solution. \r\nI don’t understand however why you feel it’s difficult to “move” the current event to after eager loading, but it’s possible for the new event?\r\n\r\nYour suggestion would - if I understand correctly - alwayshave the two events shortly after another? Any use case I’m missing where you would still want to listen to retrieved? ",
"created_at": "2019-08-20T14:11:23Z"
},
{
"body": "> I don’t understand however why you feel it’s difficult to “move” the current event to after eager loading, but it’s possible for the new event?\r\n\r\nIf we move the `retrieved` event out of `Model::newFromBuilder()`, it breaks other methods relying on it (e.g. `cursor()`, `pluck()`).\r\n\r\n> Your suggestion would - if I understand correctly - alwayshave the two events shortly after another? Any use case I’m missing where you would still want to listen to retrieved?\r\n\r\nIt's still relevant for methods without eager loading like `cursor()` and `pluck()`.",
"created_at": "2019-08-20T14:54:38Z"
},
{
"body": "Okay - that's clear to me.\r\n\r\nI think this would be really beneficial to be honest. Not sure how we could name the event though. Something like 'eagerloading.completed' sounds tempting, but since the event needs to be emitted even if there are no eager loaded relations, it sounds a bit strange to me.\r\n\r\nAgain, this is probably a lower prio issue, but especially for an optimistic locking trait where the version is stored in a related model not to clutter the base tables, this would seriously come in handy.",
"created_at": "2019-08-21T09:40:38Z"
},
{
"body": "Naming is hard... `loaded` would be short and simple, but it's a bit vague.",
"created_at": "2019-08-21T14:49:57Z"
},
{
"body": "After reading up a bit I'm gonna shift more to naming this an enhancement. It might indeed be better if we just add a new event. But I believe the better place to discuss this is the ideas repo. So feel free to open up an issue there. ",
"created_at": "2019-08-22T09:00:04Z"
}
],
"number": 29658,
"title": "Eloquent emits event retrieved prior to finishing the entire retrieval process of eager loaded relations"
} | {
"body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nI tried implementing my idea from #38705 which has been also an issue: #29658 and has been mentioned in the pull request that added the 'retrieved' event https://github.com/laravel/framework/pull/20852#issuecomment-406696499. \r\n\r\n# Why\r\nThere are situations we need to do things after relations are loaded. A use case I found myself using is conditionally appending an attribute. I don't know other ways other than returning null which isn't really great when you have a more complex site and of course the 'retrieved' event doesn't help as relations are not loaded by that point.\r\n\r\nIt makes developing applications easier because it basically allows us to better handle relations which I've seen are a huge part in Laravel applications. I tried before collecting permissions from every role to a nice list automatically, and it wasn't that great as I had to check if I already collected it and it just becomes a mess the more you do it. Having the ability to just do it automatically (when needed) with this feature helps in development.\r\n\r\nIt shouldn't break anything as it's only adding a feature which does nothing if you aren't using it.\r\n\r\n```php\r\nprotected static function booted() {\r\n static::relationsRetrieved(function (Model $mod)\r\n {\r\n if ($mod->relationLoaded('tags')) {\r\n $mod->append('tag_ids');\r\n }\r\n });\r\n}\r\n```\r\n\r\n# Need feedback\r\n* I tried to choose a less generic event name to avoid the issue mentioned in the comment here https://github.com/laravel/framework/pull/20852#issuecomment-326100695 Not sure if it's relevant, the name could by anything so if anyone has a better suggestion.\r\n* This change makes fireModelEvent in HasEvents trait public, I'm not sure if this was a necessary change and if anyone has a better idea of handling this that'd be great. I thought of making a single method to call this specifically, but haven't found such cases so I'm unsure if that's the right way of doing it.\r\n\r\nAnd in general, if you think this idea isn't good, I'd love to hear the reason, I think and believe this will be beneficial and is crucial if you want to do operations with your relations after they are loaded (I could really not find any better solution, and it seems like something people did ask for).\r\n\r\nAnd of course, I'd love to see this feature implemented regardless of the implementation, so if you think you can do this better I have no problem closing this pull request.",
"number": 38866,
"review_comments": [],
"title": "[8.x] Add 'relationsRetrieved' model event"
} | {
"commits": [
{
"message": "Added relationsRetrieved event"
},
{
"message": "Made Model->fireModelEvent public"
}
],
"files": [
{
"diff": "@@ -633,6 +633,12 @@ public function eagerLoadRelations(array $models)\n }\n }\n \n+ foreach ($models as $model) {\n+ if ($model instanceof Model) {\n+ $model->fireModelEvent('relationsRetrieved');\n+ }\n+ }\n+\n return $models;\n }\n ",
"filename": "src/Illuminate/Database/Eloquent/Builder.php",
"status": "modified"
},
{
"diff": "@@ -96,7 +96,7 @@ public function getObservableEvents()\n {\n return array_merge(\n [\n- 'retrieved', 'creating', 'created', 'updating', 'updated',\n+ 'relationsRetrieved', 'retrieved', 'creating', 'created', 'updating', 'updated',\n 'saving', 'saved', 'restoring', 'restored', 'replicating',\n 'deleting', 'deleted', 'forceDeleted',\n ],\n@@ -166,7 +166,7 @@ protected static function registerModelEvent($event, $callback)\n * @param bool $halt\n * @return mixed\n */\n- protected function fireModelEvent($event, $halt = true)\n+ public function fireModelEvent($event, $halt = true)\n {\n if (! isset(static::$dispatcher)) {\n return true;\n@@ -227,6 +227,17 @@ protected function filterModelEventResults($result)\n return $result;\n }\n \n+ /**\n+ * Register a relationsRetrieved model event with the dispatcher.\n+ *\n+ * @param \\Closure|string $callback\n+ * @return void\n+ */\n+ public static function relationsRetrieved($callback)\n+ {\n+ static::registerModelEvent('relationsRetrieved', $callback);\n+ }\n+\n /**\n * Register a retrieved model event with the dispatcher.\n *",
"filename": "src/Illuminate/Database/Eloquent/Concerns/HasEvents.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.53.1\r\n- PHP Version: 8.0.8\r\n- Database Driver & Version: MySQL 8.0.25\r\n\r\n### Description:\r\ncreateMany function of Illuminate\\Database\\Eloquent\\Factories\\Factory accepts any iterable variable as its first argument. It then tries to pass it to array_map which accepts only arrays.\r\n\r\n```\r\n /**\r\n * Create a collection of models and persist them to the database.\r\n *\r\n * @param iterable $records\r\n * @return \\Illuminate\\Database\\Eloquent\\Collection\r\n */\r\n public function createMany(iterable $records)\r\n {\r\n return new EloquentCollection(\r\n array_map(function ($record) {\r\n return $this->state($record)->create();\r\n }, $records)\r\n );\r\n }\r\n```\r\n\r\n### Steps To Reproduce:\r\n`$modelWithFactory::factory()->createMany(collect([['foo' => 'bar'],['foo' => 'baz']]));`\r\n\r\nThe model and factory is irrelevant, the code will produce the following PHP error before getting anywhere regardless\r\n\r\n`array_map(): Argument #2 ($array) must be of type array, Illuminate\\Support\\Collection given`\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Thank you. I've sent in a PR for this: https://github.com/laravel/framework/pull/38319",
"created_at": "2021-08-10T12:59:56Z"
}
],
"number": 38318,
"title": "Wrong type declaration in Illuminate\\Database\\Eloquent\\Factories\\Factory::createMany"
} | {
"body": "At the moment this method accepts any iterable but can only work with arrays.\n\nFixes #38318\n",
"number": 38319,
"review_comments": [],
"title": "[8.x] Fix Factory hasMany method"
} | {
"commits": [
{
"message": "Fix Factory hasMany method"
}
],
"files": [
{
"diff": "@@ -211,9 +211,9 @@ public function createOne($attributes = [])\n public function createMany(iterable $records)\n {\n return new EloquentCollection(\n- array_map(function ($record) {\n+ collect($records)->map(function ($record) {\n return $this->state($record)->create();\n- }, $records)\n+ })\n );\n }\n ",
"filename": "src/Illuminate/Database/Eloquent/Factories/Factory.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: ^8.40\r\n- PHP Version: 7.4.12\r\n- Database Driver & Version:\r\n\r\n### Description:\r\n\r\nhttps://github.com/laravel/framework/blob/cf26e13fa45ac5d9e64ddd0c830ed78e56e3fd4d/src/Illuminate/Database/Concerns/BuildsQueries.php#L308\r\n\r\nLine No. 315 from the link above uses `$this->getOriginalColumnNameForCursorPagination($this, $column),`, accordingly line No. 308 should also use `$this->getOriginalColumnNameForCursorPagination($this, $previousColumn),`. Otherwise an alias might be used that does not exist in the outer scope, for example.\r\n\r\n### Steps To Reproduce:\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Thanks, I've sent in a PR for this: https://github.com/laravel/framework/pull/38203",
"created_at": "2021-08-02T11:50:48Z"
}
],
"number": 38138,
"title": "`->cursorPaginate` and `getOriginalColumnNameForCursorPagination()`"
} | {
"body": "This fixes an issue where the newly added previous column in cursor pagination wasn't yet resolved to check for a select alias to retrieve its original column name.\n\nFixes #38138\n",
"number": 38203,
"review_comments": [],
"title": "[8.x] Fix previous column for cursor pagination"
} | {
"commits": [
{
"message": "Fix previous column for cursor pagination"
}
],
"files": [
{
"diff": "@@ -305,7 +305,11 @@ protected function paginateUsingCursor($perPage, $columns = ['*'], $cursorName =\n if (! is_null($cursor)) {\n $addCursorConditions = function (self $builder, $previousColumn, $i) use (&$addCursorConditions, $cursor, $orders) {\n if (! is_null($previousColumn)) {\n- $builder->where($previousColumn, '=', $cursor->parameter($previousColumn));\n+ $builder->where(\n+ $this->getOriginalColumnNameForCursorPagination($this, $previousColumn),\n+ '=',\n+ $cursor->parameter($previousColumn)\n+ );\n }\n \n $builder->where(function (self $builder) use ($addCursorConditions, $cursor, $orders, $i) {",
"filename": "src/Illuminate/Database/Concerns/BuildsQueries.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 8.12\r\n- PHP Version: 7.4\r\n- Database Driver & Version: MYSQL\r\n\r\n### Description:\r\n\r\n`Route::redirect` has a different priority after running `artisan route:cache`.\r\n\r\n### Steps To Reproduce:\r\n\r\nIn `web.php` I had routes set like this:\r\n```\r\nRoute::redirect('/organizations/{organization}', '/organizations/{organizations}/overview');\r\nRoute::patch('/organizations/{organization}', ...); \r\n```\r\n`get` and `patch` requests to these routes were working normally until I ran `artisan route:cache`. After the cache command all `patch` requests were intercepted by the redirect route.\r\n\r\nThe fix for me was to swap the ordering of these two routes, but I wonder, is there a code change that could be made to make this behavior more consistent? If not, maybe there can be more guidance around route order/priority in the documentation?\r\n",
"comments": [
{
"body": "Heya, thanks for reporting.\r\n\r\nI'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue and share the repository here? Please make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com) properly set up.\r\n\r\n```bash\r\nlaravel new framework-issue-37639 --github=\"--public\"\r\n```\r\n\r\nAfter you've posted the repository, I'll try to reproduce the issue.\r\n\r\nThanks!",
"created_at": "2021-06-10T16:06:43Z"
},
{
"body": "@driesvints here you go: https://github.com/imacrayon/framework-issue-37639\r\n\r\nClicking the submit button on the homepage will display \"Success\". But you get a different page on submit after running `artisan route:cache`.",
"created_at": "2021-06-10T19:25:59Z"
},
{
"body": "Thanks, that was very helpful. I see the same thing happening. I'm trying to recollect what the expected behavior is here as I remember we've been looking into something similar when we introduced the new Symfony compiled routes feature. I'll take a look at this when I find some time. Otherwise we're also welcoming PR's.",
"created_at": "2021-06-11T09:39:32Z"
},
{
"body": "Seems like this behavior has existed ever since we introduced route caching. I'm not sure on an easy way to solve this. Maybe we can re-order redirect routes.",
"created_at": "2021-06-15T13:58:41Z"
},
{
"body": "I can't find a decent solution for this. I've tried to rewrite the `toSymfonyRouteCollection` method to the following:\r\n\r\n```\r\n public function toSymfonyRouteCollection()\r\n {\r\n $symfonyRoutes = new SymfonyRouteCollection;\r\n\r\n $routes = $this->getRoutes();\r\n $controller = $route->action['controller'] ?? '';\r\n\r\n // Add redirect routes...\r\n foreach ($routes as $route) {\r\n if (! $route->isFallback && is_a($controller, RedirectController::class, true)) {\r\n $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);\r\n }\r\n }\r\n\r\n // Add regular routes...\r\n foreach ($routes as $route) {\r\n if (! $route->isFallback && ! is_a($controller, RedirectController::class, true)) {\r\n $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);\r\n }\r\n }\r\n\r\n // Add fallback routes...\r\n foreach ($routes as $route) {\r\n if ($route->isFallback && ! is_a($controller, RedirectController::class, true)) {\r\n $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);\r\n }\r\n }\r\n\r\n return $symfonyRoutes;\r\n }\r\n```\r\n\r\nBut that won't work because the conflicting route can also be above the redirect route. We can't just move all redirect routes to the bottom.",
"created_at": "2021-06-15T15:11:01Z"
},
{
"body": "It's not really redirect only problem, it's a problem in general:\r\n\r\n```php\r\nRoute::any('/test', function () {\r\n return '1';\r\n});\r\n\r\nRoute::get('/test', function () {\r\n return '2';\r\n});\r\n```\r\n\r\nOutputs the same problem - `2` is displayed without cache and `1` is displayed with cache.",
"created_at": "2021-06-15T17:27:01Z"
},
{
"body": "Why not cache the laravel route, but convert it into a symfony route for caching? @driesvints ",
"created_at": "2021-06-16T10:24:27Z"
},
{
"body": "> * Laravel Version: 8.12\r\n> * PHP Version: 7.4\r\n> * Database Driver & Version: MYSQL\r\n> \r\n> ### Description:\r\n> `Route::redirect` has a different priority after running `artisan route:cache`.\r\n> \r\n> ### Steps To Reproduce:\r\n> In `web.php` I had routes set like this:\r\n> \r\n> ```\r\n> Route::redirect('/organizations/{organization}', '/organizations/{organizations}/overview');\r\n> Route::patch('/organizations/{organization}', ...); \r\n> ```\r\n> \r\n> `get` and `patch` requests to these routes were working normally until I ran `artisan route:cache`. After the cache command all `patch` requests were intercepted by the redirect route.\r\n> \r\n> The fix for me was to swap the ordering of these two routes, but I wonder, is there a code change that could be made to make this behavior more consistent? If not, maybe there can be more guidance around route order/priority in the documentation?\r\n\r\nYes this is true. Because cached routes of method `Route::redirect` and `Route::patch` with same path `'/somepath'` has the same method `PATCH` so the first written route will be the one being called which is `Route::redirect`. \r\n\r\nIf you investigate the cached route file and in array of `'/somepath'` it will has array of methods like this:\r\n```php\r\n// redirect \r\narray (\r\n 'GET' => 0,\r\n 'HEAD' => 1,\r\n 'POST' => 2,\r\n 'PUT' => 3,\r\n 'PATCH' => 4, // this will match the method of request\r\n 'DELETE' => 5,\r\n 'OPTIONS' => 6,\r\n ),\r\n\r\n// patch\r\narray (\r\n 'PATCH' => 0,\r\n),\r\n```\r\nIf you remove or commented out the `'PATCH' => 4`, value then it's gonna work like you expected. So I was wondering why the `Route::redirect` method generate all the http methods instead of only `GET`? @driesvints ",
"created_at": "2021-06-22T08:40:10Z"
},
{
"body": "@aanfarhan this issue isn't specifically to PATCH. It's for all HTTP methods.",
"created_at": "2021-06-22T08:46:25Z"
},
{
"body": "well, if you do a redirect, it's for every method, not only get requests.",
"created_at": "2021-06-22T08:47:11Z"
},
{
"body": "What I'm trying to say is maybe it would be better if you can configure redirect route to work only on certain HTTP methods. Because logically if you call to the same endpoint with the same HTTP method it will only generate one result right? ",
"created_at": "2021-06-22T09:06:37Z"
},
{
"body": "@aanfarhan that's not really in the scope of this issue. Let's keep this issue focused on the issue at hand.",
"created_at": "2021-06-22T09:10:11Z"
},
{
"body": "@driesvints maybe just invert order in routes' list for cache file, like this:\r\n```\r\n protected function getFreshApplicationRoutes()\r\n {\r\n $collection = new Collection();\r\n $routes = new RouteCollection();\r\n foreach ($this->getFreshApplication()['router']->getRoutes() as $route) {\r\n $collection->prepend($route);\r\n }\r\n foreach ($collection as $route) {\r\n $routes->add($route);\r\n }\r\n return tap($routes, function ($routes) {\r\n $routes->refreshNameLookups();\r\n $routes->refreshActionLookups();\r\n });\r\n }\r\n```\r\n\r\nIn this case last routes override previous ones, but I don't know how to write it more beauty",
"created_at": "2021-07-02T21:57:50Z"
},
{
"body": "The root cause of this problem is that when the routes are cached we use \"symfony matcher\" to match a route based on request data and when the routes are not cached we use \"Laravel matcher\". So the implementations of the `->match(` method are very different and they behave differently when there are two candidate routes to choose from.\r\n1- `Illuminate\\Routing\\CompiledRouteCollection@match`\r\n2- `Illuminate\\Routing\\RouteCollection@match`\r\n\r\nYou can run this in case of cache being present and being deleted to see the output of dd.\r\n\r\n",
"created_at": "2021-07-21T14:06:41Z"
},
{
"body": "https://laravel.com/docs/8.x/routing The docs now have callout about ordering route definitions unambiguously. So if a non-breaking code change can't be agreed upon, this issue can be closed.\r\n\r\n\r\n",
"created_at": "2021-10-04T19:34:34Z"
},
{
"body": "@derekmd I agree that's the best solution to this really. It's a hard problem to solve otherwise.",
"created_at": "2021-10-04T19:43:13Z"
},
{
"body": "@driesvints @taylorotwell Laravel can provide an artisan command so that the users can scan their routes to see if there is any overriding is going on and resolve the situation for themselves.\r\nI have already implemented such a thing almost year ago on laravel-microscope for inspection purposes.\r\n`php artisan check:routes` will do the job and informs if routes are conflicting.\r\n\r\nI think if laravel give the users a free tool to avoid the breaking fix, it can give laravel a good excuse to fix it after a while.",
"created_at": "2021-10-04T21:26:48Z"
}
],
"number": 37639,
"title": "Route::redirect changes priority after running route:cache"
} | {
"body": "This PR fixes issue #37639 related to route priorities after caching.\r\n\r\nAlso, it provides a new approach to cache the routes into other cache drivers like `Redis`.\r\nI can do it in another PR if this one succeeds.\r\n\r\nThis is the test regarding the mentioned issue:\r\n```php\r\n public function testRedirectRoutes()\r\n {\r\n $this->routes(__DIR__.'/Fixtures/redirect_routes.php');\r\n\r\n $this->post('/foo/1')->assertRedirect('/foo/1/bar');\r\n $this->get('/foo/1/bar')->assertSee('Redirect response');\r\n $this->get('/foo/1')->assertSee('GET response'); // This line asserts the fix\r\n }\r\n```\r\n",
"number": 37968,
"review_comments": [],
"title": "[8.x] Fix the cached routes issue"
} | {
"commits": [
{
"message": "Fix the cached routes issue"
},
{
"message": "Update the test to include the route priorities"
},
{
"message": "Revert the name for cachedRoutesPath"
},
{
"message": "Overriding the requireApplicationCachedRoutes method to match new caching method"
}
],
"files": [
{
"diff": "@@ -102,8 +102,6 @@ protected function getFreshApplication()\n */\n protected function buildRouteCacheFile(RouteCollection $routes)\n {\n- $stub = $this->files->get(__DIR__.'/stubs/routes.stub');\n-\n- return str_replace('{{routes}}', var_export($routes->compile(), true), $stub);\n+ return serialize($routes);\n }\n }",
"filename": "src/Illuminate/Foundation/Console/RouteCacheCommand.php",
"status": "modified"
},
{
"diff": "@@ -105,7 +105,9 @@ protected function routesAreCached()\n protected function loadCachedRoutes()\n {\n $this->app->booted(function () {\n- require $this->app->getCachedRoutesPath();\n+ $cachesRoutes = $this->app['files']->get($this->app->getCachedRoutesPath());\n+\n+ $this->app['router']->setRoutes(unserialize($cachesRoutes));\n });\n }\n ",
"filename": "src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php",
"status": "modified"
},
{
"diff": "@@ -73,6 +73,18 @@ public function testWithRouteCachingEnabled()\n 'name' => $user->name,\n ]);\n }\n+\n+ /**\n+ * Require application cached routes.\n+ */\n+ protected function requireApplicationCachedRoutes(): void\n+ {\n+ $this->app->booted(function () {\n+ $cachesRoutes = $this->app['files']->get($this->app->getCachedRoutesPath());\n+\n+ $this->app['router']->setRoutes(unserialize($cachesRoutes));\n+ });\n+ }\n }\n \n class ImplicitBindingModel extends Model",
"filename": "tests/Integration/Routing/ImplicitRouteBindingTest.php",
"status": "modified"
},
{
"diff": "@@ -20,11 +20,23 @@ public function testRedirectRoutes()\n \n $this->post('/foo/1')->assertRedirect('/foo/1/bar');\n $this->get('/foo/1/bar')->assertSee('Redirect response');\n- $this->get('/foo/1')->assertRedirect('/foo/1/bar');\n+ $this->get('/foo/1')->assertSee('GET response');\n }\n \n protected function routes(string $file)\n {\n $this->defineCacheRoutes(file_get_contents($file));\n }\n+\n+ /**\n+ * Require application cached routes.\n+ */\n+ protected function requireApplicationCachedRoutes(): void\n+ {\n+ $this->app->booted(function () {\n+ $cachesRoutes = $this->app['files']->get($this->app->getCachedRoutesPath());\n+\n+ $this->app['router']->setRoutes(unserialize($cachesRoutes));\n+ });\n+ }\n }",
"filename": "tests/Integration/Routing/RouteCachingTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 7.27.0\r\n- PHP Version: 7.4.9\r\n- Database Driver & Version: MariaDB 10.5.5 MySQL\r\n\r\n### Description:\r\nFor aggregate selects it's forbidden to have a duplicated column names. \r\n\r\n`[2020-09-01 18:59:47] local.ERROR: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'description' (SQL: ... at /var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Database/Connection.php:671)`\r\n\r\n### Steps To Reproduce:\r\nExecute this query.\r\n\r\n```\r\n$count = DB::query()->fromSub(function ($query) {\r\n $query\r\n ->from('users')\r\n ->addSelect('email')\r\n ->addSelect('email')\r\n ->groupBy('email');\r\n}, 'a')->count();\r\n```\r\n\r\n### Motivation\r\nWhen using a repositories design patter, we are having criteria that build a query based on the data in the specific criteria,\r\nwe don't check on this level agains existing columns. I believe array_unique could be executed on the columns just before sending a query. It does not affect any column select aliases.\r\n\r\nhttps://github.com/laravel/framework/discussions/34097\r\n",
"comments": [
{
"body": "If you would like to submit a PR to run `array_unique` feel free.",
"created_at": "2020-09-02T19:01:25Z"
},
{
"body": "Can anyone please confirm that this was indeed resolved? I can't seem to find the changes in the production code. It seems that the changes went into a fork.",
"created_at": "2021-01-06T19:22:34Z"
}
],
"number": 34096,
"title": "Duplicate column name while aggregating"
} | {
"body": "## Description\r\n\r\nUsing `$query->addSelect('something')` multiple times introduces duplicated columns, causing `SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'something'`.\r\n\r\n## Steps to reproduce \r\n\r\nExecute the following query:\r\n\r\n```php\r\n// accounts() is a many-to-many relation, with an intermediate Eloquent Model\r\nApp\\User::find(1)->accounts()->groupBy('accounts.id')->select('accounts.*')->paginate();\r\n```\r\n\r\nThe resulting problematic SQL query will be:\r\n\r\n```mysql\r\nselect count(*) as aggregate\r\nfrom (select `accounts`.*,\r\n `accounts`.*,\r\n `membership`.`user_id` as `pivot_user_id`,\r\n `membership`.`account_id` as `pivot_account_id`,\r\n `membership`.`id` as `pivot_id`,\r\n `membership`.`created_at` as `pivot_created_at`,\r\n `membership`.`updated_at` as `pivot_updated_at`\r\n from `accounts`\r\n inner join `membership` on `accounts`.`id` = `membership`.`account_id`\r\n where `membership`.`user_id` = 1\r\n group by `accounts`.`id`) as `aggregate_table`\r\n```\r\n\r\nThe second `accounts`.* is introduced by `paginate()` here:\r\n\r\nhttps://github.com/laravel/framework/blob/361813c431adf7d0beb01c078197878fba1211b7/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php#L434-L447\r\n\r\nRelated to #34096 #34097",
"number": 37936,
"review_comments": [],
"title": "[8.x] Fix duplicated columns on select"
} | {
"commits": [
{
"message": "Fix duplicated columns on select"
}
],
"files": [
{
"diff": "@@ -403,6 +403,8 @@ public function addSelect($column)\n }\n }\n \n+ $this->columns = array_unique($this->columns);\n+\n return $this;\n }\n ",
"filename": "src/Illuminate/Database/Query/Builder.php",
"status": "modified"
},
{
"diff": "@@ -104,7 +104,7 @@ public function testAliasWrappingWithSpacesInDatabaseName()\n public function testAddingSelects()\n {\n $builder = $this->getBuilder();\n- $builder->select('foo')->addSelect('bar')->addSelect(['baz', 'boom'])->from('users');\n+ $builder->select('foo')->addSelect('bar')->addSelect(['baz', 'boom'])->addSelect('foo')->from('users');\n $this->assertSame('select \"foo\", \"bar\", \"baz\", \"boom\" from \"users\"', $builder->toSql());\n }\n ",
"filename": "tests/Database/DatabaseQueryBuilderTest.php",
"status": "modified"
}
]
} |
{
"body": "The `Illuminate\\Http\\Request` class extends the `Symfony\\Component\\HttpFoundation\\Request`. But the SymfonyRequest does not fill the property `->request` (which should hold the [POST parameters](https://github.com/symfony/HttpFoundation/blob/2.5/Request.php#L210)), except when the `Content-Type` header is equal to `application/x-www-form-urlencoded` (see [source](https://github.com/symfony/HttpFoundation/blob/2.5/Request.php#L286-L287)).\n\n`IlluminateRequest` parses the request body if the `Content-Type` header is set to `application/json`, but only when the `getInputSource()` method is called. In Laravel you can request the `IlluminateRequest` and pass it on, but when the `IlluminateRequest` is used using the `SymfonyRequest` interface, and they access the `->request` `ParameterBag`, it will not be loaded with the request body data if it's json formatted.\n",
"comments": [
{
"body": "Can you describe the bug?\n",
"created_at": "2015-01-20T15:15:58Z"
},
{
"body": "Also a test would be nice. Thanks :)\n",
"created_at": "2015-01-20T15:16:08Z"
},
{
"body": "The bug is described in the description. I'll add a test later today.\n",
"created_at": "2015-01-20T15:28:38Z"
},
{
"body": "Updated.\n",
"created_at": "2015-01-21T13:39:24Z"
},
{
"body": "Can you describe how this actually effects applications? What could you not do before that this fixes?\n",
"created_at": "2015-01-22T22:46:51Z"
},
{
"body": "In our case: we pass on the SymfonyRequest object to the OAuth2 server from The PHP League with [this method](https://github.com/thephpleague/oauth2-server/blob/master/src/AbstractServer.php#L148-L153). It then uses the `$request` object to get the request body, which should been parsed (with a parsing method defined by the Content-Type header or application/x-www-form-urlencoded) by default. The $request->request ParameterBag is used [here](https://github.com/thephpleague/oauth2-server/blob/master/src/AuthorizationServer.php#L264) and [here](https://github.com/thephpleague/oauth2-server/blob/master/src/ResourceServer.php#L142). It only works for `application/x-www-form-urlencoded` unless we manually create the $request->request ParameterBag before we set the request with `setRequest()` method from the `AbstractServer` class.\n\nThere are several people and issues with the request to support `application/json` like thephpleague/oauth2-server#292.\n",
"created_at": "2015-01-23T08:59:06Z"
}
],
"number": 7052,
"title": "[4.2] Correctly fill the $request->request parameter bag on creation"
} | {
"body": "This fixes a 6 year old bug introduced in #7052 where GET requests would have GET data populated in the POST body property leading to issues around `Request::post()` and `$request->getParsedBody()` returning GET values when called on GET requests.\r\n\r\nThis is a resubmit of #17087 & #36708, and fixes #22805. Credit to @dan-har for the initial solution and @mixlion for updating it for >=6.x.\r\n\r\nThe original PR was meant to support POST requests where their `content-type` was set to `application/json` (instead of the typical `application/x-www-form-urlencoded`), but it introduced a subtle and dangerous bug because while `$request->getInputSource()` does return the JSON data for JSON requests, it also returns the GET data for GET requests. This commit solves the underlying issue without breaking compatibility with the original functionality.\r\n\r\nThis PR is submitted as a direct result from a security issue reported to me by users of @wintercms & @octobercms and was submitted after a discussion with @taylorotwell via email.\r\n\r\nI request that this fix also be backported to 6.x @driesvints ",
"number": 37921,
"review_comments": [],
"title": "[9.x] Manually populate POST request body with JSON data only when required"
} | {
"commits": [
{
"message": "Manually populate POST request body with JSON data only when required\n\nThis fixes a 6 year old bug introduced in #7026 where GET requests would have GET data populated in the POST body property leading to issues around Request::post() and $request->getParsedBody() returning GET values when called on GET requests.\r\n\r\nThis is a resubmit of #17087 & #36708, and fixes #22805. Credit to @dan-har for the initial solution and @mixlion for updating it for >=6.x.\r\n\r\nThe original PR was meant to support POST requests where their Content-type was set to application/json (instead of the typical application/x-www-form-urlencoded), but it introduced a subtle and dangerous bug because while $request->getInputSource() does return the JSON data for JSON requests, it also returns the GET data for GET requests. This commit solves the underlying issue without breaking compatibility with the original functionality."
},
{
"message": "Add test for non-JSON GET requests"
},
{
"message": "Style fixes"
},
{
"message": "Extra space removal"
},
{
"message": "GitHub's editor needs some work"
}
],
"files": [
{
"diff": "@@ -432,7 +432,9 @@ public static function createFromBase(SymfonyRequest $request)\n \n $newRequest->content = $request->content;\n \n- $newRequest->request = $newRequest->getInputSource();\n+ if ($newRequest->isJson()) {\n+ $newRequest->request = $newRequest->json();\n+ }\n \n return $newRequest;\n }",
"filename": "src/Illuminate/Http/Request.php",
"status": "modified"
},
{
"diff": "@@ -993,7 +993,12 @@ public function testFingerprintWithoutRoute()\n $request->fingerprint();\n }\n \n- public function testCreateFromBase()\n+ /**\n+ * Ensure JSON GET requests populate $request->request with the JSON content.\n+ *\n+ * @link https://github.com/laravel/framework/pull/7052 Correctly fill the $request->request parameter bag on creation.\n+ */\n+ public function testJsonRequestFillsRequestBodyParams()\n {\n $body = [\n 'foo' => 'bar',\n@@ -1011,6 +1016,24 @@ public function testCreateFromBase()\n $this->assertEquals($request->request->all(), $body);\n }\n \n+ /**\n+ * Ensure non-JSON GET requests don't pollute $request->request with the GET parameters.\n+ *\n+ * @link https://github.com/laravel/framework/pull/37921 Manually populate POST request body with JSON data only when required.\n+ */\n+ public function testNonJsonRequestDoesntFillRequestBodyParams()\n+ {\n+ $params = ['foo' => 'bar'];\n+\n+ $getRequest = Request::create('/', 'GET', $params, [], [], []);\n+ $this->assertEquals($getRequest->request->all(), []);\n+ $this->assertEquals($getRequest->query->all(), $params);\n+\n+ $postRequest = Request::create('/', 'POST', $params, [], [], []);\n+ $this->assertEquals($postRequest->request->all(), $params);\n+ $this->assertEquals($postRequest->query->all(), []);\n+ }\n+\n /**\n * Tests for Http\\Request magic methods `__get()` and `__isset()`.\n *",
"filename": "tests/Http/HttpRequestTest.php",
"status": "modified"
}
]
} |
{
"body": "- Laravel Version: 8.48.1\r\n- PHP Version: 8.0.7\r\n- Database Driver & Version: MySQL (Percona server) 8.0.23-14\r\n\r\n### Description:\r\n\r\nSome old migrations have suddenly broken with a recent Laravel update.\r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a new Laravel project:\r\n\r\n composer create-project laravel/laravel laravel-example\r\n\r\nAdd this migration:\r\n\r\n```php\r\n<?php\r\n\r\nuse Illuminate\\Database\\Migrations\\Migration;\r\nuse Illuminate\\Database\\Schema\\Blueprint;\r\nuse Illuminate\\Support\\Facades\\DB;\r\nuse Illuminate\\Support\\Facades\\Schema;\r\n\r\nclass CreateSystemTable extends Migration\r\n{\r\n /**\r\n * Run the migrations.\r\n *\r\n * @return void\r\n */\r\n public function up(): void\r\n {\r\n Schema::create(\r\n 'system',\r\n static function (Blueprint $table) {\r\n $table->string('key')\r\n ->charset('ascii')\r\n ->collation('ascii_bin')\r\n ->primary();\r\n $table->string('value');\r\n }\r\n );\r\n }\r\n\r\n /**\r\n * Reverse the migrations.\r\n *\r\n * @return void\r\n */\r\n public function down(): void\r\n {\r\n Schema::dropIfExists('system');\r\n }\r\n}\r\n```\r\n\r\nrun `php artisan migrate`.\r\n\r\nIt fails with this error:\r\n\r\n```sh\r\nMigration table created successfully.\r\nMigrating: 2014_10_12_000000_create_users_table\r\nMigrated: 2014_10_12_000000_create_users_table (19.89ms)\r\nMigrating: 2014_10_12_100000_create_password_resets_table\r\nMigrated: 2014_10_12_100000_create_password_resets_table (13.41ms)\r\nMigrating: 2019_08_19_000000_create_failed_jobs_table\r\nMigrated: 2019_08_19_000000_create_failed_jobs_table (16.19ms)\r\nMigrating: 2020_02_09_111130_create_system_table\r\n\r\n Illuminate\\Database\\QueryException\r\n\r\n SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'character set ascii collate 'ascii_bin' not null, `value` varchar(255) not null)' at line 1 (SQL: create table `system` (`key` varchar(255) primary key character set ascii collate 'ascii_bin' not null, `value` varchar(255) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')\r\n\r\n at vendor/laravel/framework/src/Illuminate/Database/Connection.php:692\r\n 688▕ // If an exception occurs when attempting to run a query, we'll format the error\r\n 689▕ // message to include the bindings with SQL, which will make this exception a\r\n 690▕ // lot more helpful to the developer instead of just the database's errors.\r\n 691▕ catch (Exception $e) {\r\n ➜ 692▕ throw new QueryException(\r\n 693▕ $query, $this->prepareBindings($bindings), $e\r\n 694▕ );\r\n 695▕ }\r\n 696▕\r\n\r\n +9 vendor frames\r\n 10 database/migrations/2020_02_09_111130_create_system_table.php:25\r\n Illuminate\\Support\\Facades\\Facade::__callStatic(\"create\")\r\n\r\n +21 vendor frames\r\n 32 artisan:37\r\n Illuminate\\Foundation\\Console\\Kernel::handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n```\r\n\r\nThe SQL it generates is incorrect:\r\n\r\n```sql\r\ncreate table `system` (`key` varchar(255) primary key character set ascii collate 'ascii_bin' not null, `value` varchar(255) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci'\r\n```\r\n\r\nI think the problem is that the clauses are in the wrong order, in particular the position of the `primary key` phrase. This query works fine:\r\n\r\n```sql\r\ncreate table `system` (`key` varchar(255) character set ascii collate 'ascii_bin' primary key not null, `value` varchar(255) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci'\r\n```\r\n\r\nThis issue seems to have introduced after Laravel 8.47, presumably in 8.48 or 8.48.1.\r\n\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Hm. I just saw [this issue](https://github.com/laravel/framework/pull/37782) – but I am running 8.48.1 which supposedly contains the fix.\r\n\r\nI just double-checked this and I'm definitely getting this on a newly-generated project with 8.48.1. From my composer.lock:\r\n\r\n \"name\": \"laravel/framework\",\r\n \"version\": \"v8.48.1\",",
"created_at": "2021-06-24T22:18:42Z"
},
{
"body": "From the looks of the code in ca23daf2343171c2082d05b69b717dbb17f61415, I guess `Primary` needs to go after `Collate`, though this ordering doesn't seem to agree with [MySQL docs](https://dev.mysql.com/doc/refman/8.0/en/create-table.html). But I've tried it and it works 🤷",
"created_at": "2021-06-25T06:55:34Z"
},
{
"body": "@Synchro Could it be that there is a difference between mysql 5.x and 8.x? Just throwing an idea out there..",
"created_at": "2021-06-25T10:04:32Z"
},
{
"body": "You can compare the docs on [5.7](https://dev.mysql.com/doc/refman/5.7/en/create-table.html) and [8.0](https://dev.mysql.com/doc/refman/8.0/en/create-table.html). 8.0 has more elements, but the ones that are in common are at least in the same order. That said, both of them show `primary key` before `collate`, yet that order evidently doesn't work.",
"created_at": "2021-06-25T10:09:32Z"
}
],
"number": 37811,
"title": "MySQL custom primary key creation still broken in 8.48.1"
} | {
"body": "This simply changes the clause order in the MySQL grammar, and appears to fix #37811 in a similar way to the fix that resulted in the 8.48.1 release (which failed for me). I don't know what the definitive order of clauses should be, but this change fixes the issue I found.",
"number": 37815,
"review_comments": [],
"title": "[8.x] Move primary after collate"
} | {
"commits": [
{
"message": "Move primary after collate, fixes #37811"
},
{
"message": "Move primary after charset"
}
],
"files": [
{
"diff": "@@ -15,7 +15,7 @@ class MySqlGrammar extends Grammar\n * @var string[]\n */\n protected $modifiers = [\n- 'Unsigned', 'Primary', 'Charset', 'Collate', 'VirtualAs', 'StoredAs', 'Nullable',\n+ 'Unsigned', 'Charset', 'Primary', 'Collate', 'VirtualAs', 'StoredAs', 'Nullable',\n 'Srid', 'Default', 'Increment', 'Comment', 'After', 'First',\n ];\n ",
"filename": "src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php",
"status": "modified"
}
]
} |
{
"body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.44.0\r\n- PHP Version: 8.0.2\r\n- Database Driver & Version: MySQL 8.0\r\n\r\n### Description:\r\n\r\nWhen resolving an object with constructor parameters using the service container, it seems that subsequently trying to mock that object fails.\r\n\r\n### Steps To Reproduce:\r\n\r\nSay I've got an interface `FooContract`, with a `bar` method:\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App;\r\n\r\ninterface FooContract\r\n{\r\n public function bar(): string;\r\n}\r\n```\r\n\r\nAnd a class `Foo` implementing that interface, with a constructor expecting a `$baz` string, and the `bar` method returning 'qux':\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App;\r\n\r\nclass Foo implements FooContract\r\n{\r\n public function __construct(public string $baz)\r\n {\r\n }\r\n\r\n public function bar(): string\r\n {\r\n return 'qux';\r\n }\r\n}\r\n```\r\n\r\nAnd I bind `FooContract` to `Foo` in `AppServiceProvider`:\r\n\r\n```php\r\npublic function register()\r\n{\r\n $this->app->bind(FooContract::class, Foo::class);\r\n}\r\n```\r\n\r\nSay I write a simple test.\r\n\r\nUsing the service container to resolve `FooContract` works as expected:\r\n\r\n```php\r\npublic function testFoo()\r\n{\r\n resolve(FooContract::class, ['baz' => 'baz'])->bar(); // \"qux\"\r\n}\r\n```\r\n\r\nBut then if I create a mock and bind it to `FooContract`, the mock seems to be ignored:\r\n\r\n```php\r\npublic function testFoo()\r\n{\r\n $this->mock(FooContract::class, function (MockInterface $mock) {\r\n $mock->shouldReceive('bar')->once()->andReturn('corge');\r\n });\r\n\r\n resolve(FooContract::class, ['baz' => 'baz'])->bar(); // still \"qux\"\r\n}\r\n```\r\n\r\nWithout changing the test, and simply by removing the arguments when resolving `FooContract` using the service container, the mock is not ignored anymore:\r\n\r\n```php\r\npublic function testFoo()\r\n{\r\n $this->mock(FooContract::class, function (MockInterface $mock) {\r\n $mock->shouldReceive('bar')->once()->andReturn('corge');\r\n });\r\n\r\n //resolve(FooContract::class, ['baz' => 'baz'])->bar();\r\n resolve(FooContract::class)->bar(); // \"corge\"\r\n}\r\n```\r\n\r\nI would expect the bind to work whether there are constructor parameters or not.\r\n\r\n<!-- If possible, please provide a GitHub repository to demonstrate your issue -->\r\n<!-- laravel new bug-report --github=\"--public\" -->\r\n",
"comments": [
{
"body": "Heya, thanks for reporting.\r\n\r\nI'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue and share the repository here? Please make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com) properly set up.\r\n\r\n```bash\r\nlaravel new bug-report --github=\"--public\"\r\n```\r\n\r\nAfter you've posted the repository, I'll try to reproduce the issue.\r\n\r\nThanks!",
"created_at": "2021-06-17T08:12:00Z"
},
{
"body": "Hi @driesvints, I'm having trouble with the bug-report codebase for some reason (e.g. the `$this->mock()` method doesn't seem to be recognised from test classes, and binding resolution seems to fail) but here is [the repository](https://github.com/osteel/laravel-mock-bug-report), with a couple of instructions in the README file.\r\n\r\nLet me know if you need anything else.",
"created_at": "2021-06-17T09:35:50Z"
},
{
"body": "Hey @osteel. It seems you committed all your code as a single commit. I need a separate commit with your custom changes to see what you've modified.\r\n\r\nEdit: normally when you use the above command I gave it'll create the setup fresh laravel app separately. Did you amend your changes? (please don't do that)",
"created_at": "2021-06-17T09:42:01Z"
},
{
"body": "@driesvints yeah I did, my bad. Also found the issue, now fixed. Let me just redo this, one sec",
"created_at": "2021-06-17T09:43:51Z"
},
{
"body": "@driesvints [there you go](https://github.com/osteel/laravel-mock-bug-report)",
"created_at": "2021-06-17T09:51:18Z"
},
{
"body": "I have to throw in the towel here. I just can't figure it out. When I debug the container it returns the correct mocked instance but it arrives as the actual concrete implementation in the test somehow? No idea why that happens...",
"created_at": "2021-06-17T16:22:55Z"
},
{
"body": "@driesvints well, in a way it's comforting that I wasn't just doing something stupid 😄 \r\n\r\nThanks for looking into this – hopefully some reinforcements will help crack the case",
"created_at": "2021-06-17T16:33:43Z"
},
{
"body": "Container.php:740\r\n```php\r\nif (isset($this->instances[$abstract]) && ! $needsContextualBuild) {\r\n return $this->instances[$abstract];\r\n}\r\n```\r\n\r\nMy 2 cents here, it is determined as `$needsContextualBuild` so it skips returning the registered instance (which is the mock) and builds it again, thus receiving the original concrete instead of the mocked one. I'm not sure what the purpose of the contextual build is so can't really tell what the correct way to fix this should be.",
"created_at": "2021-06-18T05:59:39Z"
},
{
"body": "@donnysim I checked into that piece of code and it did return the mocked instance for me. It just comes out as the concrete implementation. I have no idea why that is.",
"created_at": "2021-06-18T09:34:53Z"
},
{
"body": "@driesvints interesting, for me it didn't - `$needsContextualBuild` is true and it skips that part, if I remove the context check, the mocked instance is returned in the test and it passes.",
"created_at": "2021-06-18T09:44:50Z"
},
{
"body": "```php\r\n if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {\r\n if ($abstract === \\App\\FooContract::class) dd($this->instances[$abstract]);\r\n\r\n return $this->instances[$abstract];\r\n }\r\n```\r\n\r\nGives\r\n\r\n```bash\r\n$ phpunit tests/Unit ~/Sites/test-mocking\r\nPHPUnit 9.5.5 by Sebastian Bergmann and contributors.\r\n\r\nMockery_0_App_FooContract {#432\r\n #_mockery_expectations: array:1 [\r\n \"bar\" => Mockery\\ExpectationDirector {#433\r\n #_name: \"bar\"\r\n #_mock: Mockery_0_App_FooContract {#432}\r\n\r\n...\r\n```",
"created_at": "2021-06-18T09:55:03Z"
},
{
"body": "But that is triggered on\r\n```php\r\n// Would expect to get \"corge\"...\r\n$this->mock(FooContract::class, function (MockInterface $mock) {\r\n $mock->shouldReceive('bar')->once()->andReturn('corge');\r\n});\r\n```\r\n\r\nwhen it calls \r\n```php\r\n$result = resolve(FooContract::class, ['baz' => 'baz'])->bar(); // ... but still getting \"qux\"\r\n```\r\nit does not trigger that code, I presume because `['baz' => 'baz']` was passed and it assumes it needs to create a separate instance?",
"created_at": "2021-06-18T10:01:52Z"
},
{
"body": "Thanks @donnysim, that was helpful. I didn't realize the container also resolved the mocked dependency immediately.\r\n\r\nI currently got it working with:\r\n\r\n```php\r\n if (isset($this->instances[$abstract]) &&\r\n ($this->instances[$abstract] instanceof MockInterface || ! $needsContextualBuild)) {\r\n return $this->instances[$abstract];\r\n }\r\n```\r\n\r\nBut that wires the `MockInterface` to the container and I'm not sure that's wanted.",
"created_at": "2021-06-18T10:30:21Z"
},
{
"body": "[replicating the issue in the service provider (no mock)](https://github.com/Nacoma/laravel-mock-bug-report/commit/baff0a70e4d7cbaf8a6ee9d40e623136e6a592a3)\r\n\r\nIn the non-working version - a concrete `FooContract` is registered as an instance in the container. This action does not replace the original binding. \r\n\r\nThe documentation does state that:\r\n\r\n> The given instance will always be returned on subsequent calls into the container\r\n\r\nbut instances are not registered as actual singletons. A new instance will be returned if it's explicitly requested (eg telling it to use new constructor arguments).\r\n\r\n[working version](https://github.com/Nacoma/laravel-mock-bug-report/blob/main/app/Providers/AppServiceProvider.php#L25)\r\n\r\nReplacing the call to `instance` with an explicit `singleton` binding [here](https://github.com/laravel/framework/blob/952f84a3a5449a5f80190479240fce15bdaad558/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php#L53) should fix this.\r\n\r\nIf we do expect a mocked instance to be bound as a singleton then we simply need to register it as one.",
"created_at": "2021-06-19T20:37:24Z"
},
{
"body": "We're reverting the PR that fixed this because it's breaking other people's test suites. We'll need to look at an alternative approach.\r\n\r\n@donnysim can you please try out my approach from above?",
"created_at": "2021-07-02T16:50:29Z"
},
{
"body": "@driesvints can't vouch for other use cases but it does work for us - both the contract and the concrete, including aliases is received as mocked instance despite the provided parameters.",
"created_at": "2021-07-02T18:17:11Z"
},
{
"body": "For some reason I just can't stop the feeling that mocking all instances is just wrong, like this will lead yet again to other issues like resolving multiples of the same contract but with different parameters leave you with the same mock. This would result `once` restrictions to fail even though they might be instantiated in 2 different methods. Somehow I'd want to say that an instance resolve callback should be the way to go to decide if you want to return a mocked instance or a real one, maybe something in the line of:\r\n\r\n```php\r\n$this->mockInstance(FooContract::class, function (FooContract $instance, MockInterface $mock) {\r\n if ($something) {\r\n return $instance;\r\n }\r\n \r\n return $mock->shouldReceive('bar')->once()->andReturn('corge');\r\n});\r\n```\r\n\r\nbut not sure if I'm way off the target or not and if it's even feasable.",
"created_at": "2021-07-02T18:39:25Z"
},
{
"body": "I have had the same issue - reverted back to `\"laravel/framework\": \"8.49.0\"` and the mocking works again.",
"created_at": "2021-07-04T15:25:09Z"
},
{
"body": "@donnysim I'm going to close this now. Feel free to reply when you've found time to test that out.",
"created_at": "2021-07-05T09:54:29Z"
},
{
"body": "Hey,\r\n\r\nI couldn't find a way to solve this without changing `Container.php` so I went for an approach inspired by @Nacoma's comments and PR. Registering the mock as a singleton solves the issue so I opened a [PR](https://github.com/laravel/framework/pull/38453) adding a method to the `InteractsWithContainer` trait to make that easier.\r\n\r\nIt's all new code so won't affect existing test suites.",
"created_at": "2021-08-19T16:16:42Z"
},
{
"body": "PR was closed 🤷 ",
"created_at": "2021-08-19T16:27:57Z"
},
{
"body": "Still have this issue on Laravel 9.14.1. @osteel Found any workarounds?\r\n\r\nEdit: I found a solution [here](https://github.com/laravel/framework/issues/19450#issuecomment-451549582). But, it would be nice if $this->mock could be used.",
"created_at": "2022-07-02T22:23:07Z"
},
{
"body": "same issue laravel 9 @osteel ",
"created_at": "2022-10-02T06:04:32Z"
}
],
"number": 37706,
"title": "Can't mock an object resolved with some constructor arguments"
} | {
"body": "Addresses #37706 \r\n\r\nMocked instances are bound to the container as a singleton so that attempts to resolve them using `resolve($abstract, $withParams)` does not create a new instance and ignore the mocked instance.",
"number": 37746,
"review_comments": [],
"title": "[8.x] bind mock instances as singletons so they are not overwritten"
} | {
"commits": [
{
"message": "[8.x] bind mock instances as singletons so they are not overwritten"
},
{
"message": "add tests for singletonInstance"
}
],
"files": [
{
"diff": "@@ -41,6 +41,22 @@ protected function instance($abstract, $instance)\n return $instance;\n }\n \n+ /**\n+ * Register an instance of an object as a singleton in the container.\n+ *\n+ * @param $abstract\n+ * @param $instance\n+ * @return \\Mockery\\MockInterface\n+ */\n+ protected function singletonInstance($abstract, $instance)\n+ {\n+ $this->app->singleton($abstract, function () use ($instance) {\n+ return $instance;\n+ });\n+\n+ return $instance;\n+ }\n+\n /**\n * Mock an instance of an object in the container.\n *\n@@ -50,7 +66,7 @@ protected function instance($abstract, $instance)\n */\n protected function mock($abstract, Closure $mock = null)\n {\n- return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args())));\n+ return $this->singletonInstance($abstract, Mockery::mock(...array_filter(func_get_args())));\n }\n \n /**\n@@ -62,7 +78,7 @@ protected function mock($abstract, Closure $mock = null)\n */\n protected function partialMock($abstract, Closure $mock = null)\n {\n- return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))->makePartial());\n+ return $this->singletonInstance($abstract, Mockery::mock(...array_filter(func_get_args()))->makePartial());\n }\n \n /**\n@@ -74,7 +90,7 @@ protected function partialMock($abstract, Closure $mock = null)\n */\n protected function spy($abstract, Closure $mock = null)\n {\n- return $this->instance($abstract, Mockery::spy(...array_filter(func_get_args())));\n+ return $this->singletonInstance($abstract, Mockery::spy(...array_filter(func_get_args())));\n }\n \n /**",
"filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php",
"status": "modified"
},
{
"diff": "@@ -27,4 +27,12 @@ public function testWithMixRestoresOriginalHandlerAndReturnsInstance()\n $this->assertSame($handler, resolve(Mix::class));\n $this->assertSame($this, $instance);\n }\n+\n+ public function testSingletonBoundInstancesCanBeResolved()\n+ {\n+ $this->singletonInstance('foo', 'bar');\n+\n+ $this->assertEquals('bar', $this->app->make('foo'));\n+ $this->assertEquals('bar', $this->app->make('foo', ['with' => 'params']));\n+ }\n }",
"filename": "tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php",
"status": "modified"
}
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.