Dataset Viewer
Auto-converted to Parquet
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![image](https://github.com/laravel/framework/assets/15892462/5e131cdd-4e0d-4e0c-a4a9-f401677704f4)\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![image](https://github.com/laravel/framework/assets/15892462/fe94ad39-162e-4626-94e1-9e0949f08eb2)\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![image](https://github.com/laravel/framework/assets/15892462/234b7df7-2dfa-4c57-b448-4f89b80e36d3)\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use tinker again.\r\n![image](https://github.com/laravel/framework/assets/15892462/95dc72af-eef2-4eb1-8694-f0478953a2fb)\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![image](https://github.com/laravel/framework/assets/15892462/5e131cdd-4e0d-4e0c-a4a9-f401677704f4)\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![image](https://github.com/laravel/framework/assets/15892462/fe94ad39-162e-4626-94e1-9e0949f08eb2)\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![image](https://github.com/laravel/framework/assets/15892462/234b7df7-2dfa-4c57-b448-4f89b80e36d3)\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use tinker again.\r\n![image](https://github.com/laravel/framework/assets/15892462/95dc72af-eef2-4eb1-8694-f0478953a2fb)\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![image](https://github.com/laravel/framework/assets/15892462/5e131cdd-4e0d-4e0c-a4a9-f401677704f4)\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![image](https://github.com/laravel/framework/assets/15892462/fe94ad39-162e-4626-94e1-9e0949f08eb2)\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![image](https://github.com/laravel/framework/assets/15892462/234b7df7-2dfa-4c57-b448-4f89b80e36d3)\r\n\r\nThen, we can cache the routes with `artisan route:cache` command and use tinker again.\r\n![image](https://github.com/laravel/framework/assets/15892462/95dc72af-eef2-4eb1-8694-f0478953a2fb)\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![image](https://github.com/laravel/framework/assets/36625222/bfc02c2a-01d0-4fec-8952-7d9d8bc8eeff)\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![image](https://github.com/laravel/framework/assets/6755282/448e4116-800b-45b2-baee-b7efcdc2c098)\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" } ] }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
32