issue
dict
pr
dict
pr_details
dict
{ "body": "- Laravel Version: 5.8.7\r\n- PHP Version: 7.2.5, 7.3.3\r\n- Database Driver & Version:\r\n\r\n### Description:\r\nBlade @includes are appending extra white space to the end\r\n\r\n### Steps To Reproduce:\r\n\r\ntest/include.blade.php\r\n```this is only a test```\r\n\r\nparent.blade.php\r\n```html\r\n<div>@include('test.include')</div>\r\n```\r\n\r\nexpected html output:\r\n```html\r\n<div>this is only a test</div>\r\n```\r\n\r\nactual html output:\r\n```html\r\n<div>this is only a test\r\n</div>\r\n```\r\n\r\nIn most circumstances, this isn't really an issue, but in cases where you need to prevent white-space between html elements, it becomes an issue as the extra whitespace creates a gap between them.\r\n\r\nIn Laravel 5.7.x, the same code returned the expected behavior. Potentially even within an earlier version of 5.8, but I'm not sure.", "comments": [ { "body": "Heya, I think this might be related to https://github.com/laravel/framework/pull/27544 which adds an extra linebreak at the end. This got fixed in https://github.com/laravel/framework/pull/27976 which will be released tomorrow. Feel free to report back if tomorrow's release doesn't fixes your problem.", "created_at": "2019-03-25T13:41:21Z" }, { "body": "I just updated to Laravel 5.8.8 and this issue does not appear to be resolved.", "created_at": "2019-03-27T19:24:04Z" }, { "body": "I'm getting the same. Here are some copy-and-paste steps to reproduce:\r\n\r\n```bash\r\ncomposer create-project --prefer-dist laravel/laravel=5.8.3 issue-27996\r\n\r\necho -n \"<div>@include('partial')</div>\" > issue-27996/resources/views/parent.blade.php\r\necho -n \"contents\" > issue-27996/resources/views/partial.blade.php\r\necho \"Artisan::command('issue-27996', function () {\r\n \\$this->comment(view('parent'));\r\n});\" >> issue-27996/routes/console.php\r\n\r\nphp issue-27996/artisan issue-27996\r\n```\r\n\r\nExpected vs Actual output:\r\n\r\n```diff\r\n- <div>contents</div>\r\n+ <div>contents\r\n+ </div>\r\n\r\n```", "created_at": "2019-03-27T21:06:01Z" }, { "body": "Okay, re-opening. ", "created_at": "2019-03-28T13:23:10Z" }, { "body": "Ping @bzixilu. Do you maybe have an idea if this is related to the changes you made?", "created_at": "2019-03-28T13:24:00Z" }, { "body": "It appears they may be related.\r\n\r\nThe cached view code for `parent.blade.php`:\r\n```php\r\n<div><?php echo $__env->make('partial', \\Illuminate\\Support\\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?></div>\r\n<?php /* /path/to/issue-27996/resources/views/parent.blade.php */ ?>\r\n```\r\n\r\nThe cached view code for `partial.blade.php`:\r\n```php\r\ncontents\r\n<?php /* /path/to/issue-27996/resources/views/partial.blade.php */ ?>\r\n```\r\n\r\nSo when `partial.blade.php` is included, it has that new line.", "created_at": "2019-03-28T13:58:05Z" }, { "body": "A fix may be to leave out the `\\n` when appending the path to the compiled view.\r\n\r\n```patch\r\ndiff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php\r\nindex 0f084b06f..c5a51c36f 100644\r\n--- a/src/Illuminate/View/Compilers/BladeCompiler.php\r\n+++ b/src/Illuminate/View/Compilers/BladeCompiler.php\r\n@@ -123,7 +123,7 @@ class BladeCompiler extends Compiler implements CompilerInterface\r\n );\r\n \r\n if (! empty($this->getPath())) {\r\n- $contents .= \"\\n<?php /* {$this->getPath()} */ ?>\";\r\n+ $contents .= \"<?php /* {$this->getPath()} */ ?>\";\r\n }\r\n \r\n $this->files->put(\r\n\r\n```", "created_at": "2019-03-28T14:28:15Z" }, { "body": "@fitztrev it's the base of the whole reason why the feature was added: so the path line would exist at the very last line so PHPStorm could pick it up.", "created_at": "2019-03-28T14:40:18Z" }, { "body": "Ok, I don't know the inner workings of PHPStorm. But maybe they would be able to parse it out when it's not on its own line.\r\n\r\nBut now that you mention that, I'm curious why this was added. https://github.com/laravel/framework/pull/27963#issuecomment-475618587 Maybe this should belong in a package too.", "created_at": "2019-03-28T15:03:36Z" }, { "body": "> But now that you mention that, I'm curious why this was added. #27963 (comment) Maybe this should belong in a package too.\r\n\r\n@fitztrev touché and you make an excellent point here. Ultimately this wasn't my call though for this feature. And I do believe that the impact of this particularly feature (the path in the view) is worth adding because it empowers such a useful debugging feature in PHPStorm.\r\n\r\nHowever, I fully agree that we should look at how we can look at a way to keep the feature while solving this bug.", "created_at": "2019-03-28T16:46:20Z" }, { "body": "Is this **only** a problem when you use an include between html tags? Or also in other ways/usages?", "created_at": "2019-03-28T16:50:13Z" }, { "body": "> However, I fully agree that we should look at how we can look at a way to keep the feature while solving this bug.\r\n\r\n👍 We'll wait to see what @bzixilu says, if there's another way PHPStorm could parse it.\r\n\r\n> Is this only a problem when you use an include between html tags? Or also in other ways/usages?\r\n\r\nOther ways/usages too. A blade `@include()` is always appending a newline when rendered. The surrounding `<div>` tag was only used in the example to better illustrate the problem.", "created_at": "2019-03-28T16:57:41Z" }, { "body": "This was touted online by JetBrains, Taylor, Laravel News, etc. Though not specifically mentioned, it seems like it would work out-of-the-box. So including it in the core makes sense. I think we should keep trying to make this work without going the third-party route. ", "created_at": "2019-03-28T16:59:24Z" }, { "body": "Hi all, sorry for one more breakage of Blade usage scenario. I'll start an investigation today and will do my best to come back soon with the possible solution. ", "created_at": "2019-03-29T11:23:21Z" }, { "body": "Closing this because we've decided to revert the feature for now. Please see https://github.com/laravel/framework/pull/28099#issuecomment-479900212 for more info.", "created_at": "2019-04-04T13:41:47Z" } ], "number": 27996, "title": "@include adding extra space/line break to content" }
{ "body": "The pull-request contains the fix for #27996\r\n\r\nThe main idea is to remove extra line break related to the added path comment during view rendering.\r\nThis fix should not affect any line breaks which doesn't relate to added path comment.\r\n\r\nI personally don't like the following things in the fix. \r\n\r\n1) If we change a form which is used to represent a path in compiled view, we should not forget to fix a rendering as well (I couldn't write a test for it, it looked quite complicated)\r\n\r\n2) Totally we pass through a view 2 times, the first time when including the compiled view, and the second time when checking if it ends with path comment, probably it could be optimized and done with a single pass.\r\n\r\nI appreciate if you could advise me how to improve it. ", "number": 28099, "review_comments": [], "title": "[5.8] Fix adding extra space/line that breaks content " }
{ "commits": [ { "message": "#27996 @include adding extra space/line break to content" }, { "message": "#27996 @include adding extra space/line break to content\n\nreplace exact \"\\n\"" }, { "message": "#27996 @include adding extra space/line break to content\n\nfix possible undefined offset problem" }, { "message": "@include adding extra space/line break to content #27996\n\ncode style fix" }, { "message": "@include adding extra space/line break to content #27996\n\nincorrect code style fix" } ], "files": [ { "diff": "@@ -4,6 +4,7 @@\n \n use Exception;\n use Throwable;\n+use Illuminate\\Support\\Str;\n use Illuminate\\Contracts\\View\\Engine;\n use Symfony\\Component\\Debug\\Exception\\FatalThrowableError;\n \n@@ -47,7 +48,17 @@ protected function evaluatePath($__path, $__data)\n $this->handleViewException(new FatalThrowableError($e), $obLevel);\n }\n \n- return ltrim(ob_get_clean());\n+ $lines = file($__path);\n+ $count = count($lines);\n+ $ob_get_clean = ob_get_clean();\n+ if ($count > 0) {\n+ $last_line = $lines[$count - 1];\n+ if (Str::startsWith($last_line, '<?php /*') && Str::endsWith($last_line, '*/ ?>')) {\n+ $ob_get_clean = Str::replaceLast(\"\\n\", '', $ob_get_clean);\n+ }\n+ }\n+\n+ return ltrim($ob_get_clean);\n }\n \n /**", "filename": "src/Illuminate/View/Engines/PhpEngine.php", "status": "modified" }, { "diff": "@@ -19,4 +19,25 @@ public function testViewsMayBeProperlyRendered()\n $this->assertEquals('Hello World\n ', $engine->get(__DIR__.'/fixtures/basic.php'));\n }\n+\n+ public function testTrimWhitespace()\n+ {\n+ $engine = new PhpEngine;\n+ $this->assertEquals('Hello World', $engine->get(__DIR__.'/fixtures/basicWithPath.php'));\n+ }\n+\n+ public function testTrimOnlyPathRelatedWhitespace()\n+ {\n+ $engine = new PhpEngine;\n+ $this->assertEquals('Hello World\n+\n+\n+', $engine->get(__DIR__.'/fixtures/basicWithManyWhiteSpacesBeforePath.php'));\n+ }\n+\n+ public function testEmpty()\n+ {\n+ $engine = new PhpEngine;\n+ $this->assertEquals('', $engine->get(__DIR__.'/fixtures/empty.php'));\n+ }\n }", "filename": "tests/View/ViewPhpEngineTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,6 @@\n+\n+Hello World\n+\n+\n+\n+<?php /* template path */ ?>\n\\ No newline at end of file", "filename": "tests/View/fixtures/basicWithManyWhiteSpacesBeforePath.php", "status": "added" }, { "diff": "@@ -0,0 +1,3 @@\n+\n+Hello World\n+<?php /* template path */ ?>\n\\ No newline at end of file", "filename": "tests/View/fixtures/basicWithPath.php", "status": "added" }, { "diff": "", "filename": "tests/View/fixtures/empty.php", "status": "added" } ] }
{ "body": "- Laravel Version: 5.8.4\r\n- PHP Version: 7.2.4\r\n- Database Driver & Version: MySql\r\n\r\n### Description:\r\nSoftDelete::runSoftDelete does not take into account overridden Model::setKeysForSaveQuery method.\r\nI use this for multi-tenancy purposes. Or for use composite primary keys.\r\n\r\nModel:\r\n```\r\n<?php\r\n\r\nnamespace App;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Database\\Eloquent\\SoftDeletes;\r\n\r\nclass Shop extends Model\r\n{\r\n use SoftDeletes;\r\n\r\n public $primaryKey= 'shop_id';\r\n\r\n protected function setKeysForSaveQuery(Builder $query) {\r\n $query\r\n ->where('user_id', '=', $this->getAttribute('user_id'))\r\n ->where('shop_id', '=', $this->getAttribute('shop_id'));\r\n\r\n return $query;\r\n }\r\n}\r\n```\r\nWhen running below code:\r\n\r\n```\r\n$shop = Shop::find(1);\r\n$shop->delete();\r\n```\r\n\r\nExpected query:\r\n`UPDATE shop SET deleted_at = ?, Shop.updated_at = ? WHERE shop_id = ? AND user_id = ?`\r\n\r\nActual query:\r\n`UPDATE shop SET deleted_at = ?, SHOP.updated_at = ? WHERE shop_id = ?`\r\n\r\nSolution is to replace below line\r\n\r\n```\r\n<?php\r\n\r\nnamespace Illuminate\\Database\\Eloquent;\r\n\r\ntrait SoftDeletes\r\n{\r\n ...\r\n protected function runSoftDelete()\r\n {\r\n $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());\r\n ...\r\n }\r\n ...\r\n}\r\n```\r\nTo\r\n\r\n`$query = $this->setKeysForSaveQuery($this->newModelQuery());`", "comments": [ { "body": "Why would `update Shop` be expected here?", "created_at": "2019-03-26T17:16:12Z" }, { "body": "@driesvints it was mistype. Corrected.", "created_at": "2019-03-26T19:39:53Z" }, { "body": "Heh, I'm not sure that `setKeysForSaveQuery` is meant to be used like this. Can't you just overwrite the `runSoftDelete` method if you want?", "created_at": "2019-03-28T12:46:28Z" }, { "body": "Yes you can overwrite `runSoftDelete` but I think if I am overwrite `Model::setKeysForSaveQuery` so `SoftDelete::runSoftDelete` should take it into account. \r\n\r\nPlease see below `setKeysForSaveQuery` and `runSoftDelete` methods below. The where part practically same.\r\n\r\n```\r\nprotected function setKeysForSaveQuery(Builder $query)\r\n {\r\n $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());\r\n\r\n return $query;\r\n }\r\n```\r\n\r\n```\r\nprotected function runSoftDelete()\r\n {\r\n $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());\r\n ...\r\n }\r\n ...\r\n```", "created_at": "2019-03-29T04:54:14Z" }, { "body": "The question is if this has side effects. @staudenmeir do you maybe see any from the changes above?", "created_at": "2019-03-29T14:16:54Z" }, { "body": "I agree that this should be changed. We should also use `setKeysForSaveQuery()` in `SoftDeletes::performDeleteOnModel()` to match `Model::performDeleteOnModel()`.\r\n\r\nAn example where the current behavior is incorrect:\r\n\r\n```php\r\n$user = User::find(1);\r\n$user->id = 2;\r\n$user->delete();\r\n```\r\n\r\nThis works without `SoftDeletes` but not with it.", "created_at": "2019-03-29T22:51:34Z" }, { "body": "So should I create new pull request ? And update both SoftDeletes::performDeleteOnModel() and SoftDelete::runSoftDelete ?", "created_at": "2019-03-30T09:02:19Z" }, { "body": "Yes, please create a PR.", "created_at": "2019-03-30T14:19:24Z" }, { "body": "@staudenmeir thanks for verifying! :)", "created_at": "2019-04-01T09:55:23Z" }, { "body": "PR was merged.", "created_at": "2019-04-01T13:23:23Z" } ], "number": 28022, "title": "SoftDelete::runSoftDelete does not take into account overridden Model::setKeysForSaveQuery " }
{ "body": "- Laravel Version: 5.8.4\r\n- PHP Version: 7.2.4\r\n- Database Driver & Version: MySql\r\n- Issue: #28022 \r\n\r\n### Description:\r\nSoftDelete::runSoftDelete and SoftDelete::performDeleteOnModel did not take into account overwrite Model::setKeysForSaveQuery.\r\nI use this for multi-tenancy purposes. Or for use composite primary keys.\r\n\r\nModel:\r\n```\r\n<?php\r\n\r\nnamespace App;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Database\\Eloquent\\SoftDeletes;\r\n\r\nclass Shop extends Model\r\n{\r\n use SoftDeletes;\r\n\r\n public $primaryKey= 'shop_id';\r\n\r\n protected function setKeysForSaveQuery(Builder $query) {\r\n $query\r\n ->where('user_id', '=', $this->getAttribute('user_id'))\r\n ->where('shop_id', '=', $this->getAttribute('shop_id'));\r\n\r\n return $query;\r\n }\r\n}\r\n```\r\nWhen running below code:\r\n\r\n```\r\n$shop = Shop::find(1);\r\n$shop->delete();\r\n```\r\n\r\nExpected query:\r\n`UPDATE shop SET deleted_at = ?, Shop.updated_at = ? WHERE shop_id = ? AND user_id = ?`\r\n\r\nActual query:\r\n`UPDATE shop SET deleted_at = ?, SHOP.updated_at = ? WHERE shop_id = ?`\r\n\r\nSolution is to replace below lines\r\n\r\n```\r\n<?php\r\n\r\nnamespace Illuminate\\Database\\Eloquent;\r\n\r\ntrait SoftDeletes\r\n{\r\n ...\r\n protected function performDeleteOnModel()\r\n {\r\n ...\r\n return $this->newModelQuery()->where($this->getKeyName(), $this->getKey())->forceDelete();\r\n }\r\n\r\n ...\r\n }\r\n ...\r\n protected function runSoftDelete()\r\n {\r\n $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());\r\n ...\r\n }\r\n ...\r\n}\r\n```\r\nTo\r\n`return $this->setKeysForSaveQuery($this->newModelQuery())->forceDelete();`\r\n`$query = $this->setKeysForSaveQuery($this->newModelQuery());`", "number": 28081, "review_comments": [], "title": "[5.8] Fixed: SoftDelete::runSoftDelete and SoftDelete::performDeleteOnModel did not take into account overwrite Model::setKeysForSaveQuery" }
{ "commits": [ { "message": "Fixed: SoftDelete::runSoftDelete and SoftDelete::performDeleteOnModel did not take into account overwrite Model::setKeysForSaveQuery" }, { "message": "Adding DatabaseSoftDeletingTraitStub::setKeysForSaveQuery method to DatabaseSoftDeletingTraitTest" }, { "message": "missed equal sign" } ], "files": [ { "diff": "@@ -59,7 +59,7 @@ protected function performDeleteOnModel()\n if ($this->forceDeleting) {\n $this->exists = false;\n \n- return $this->newModelQuery()->where($this->getKeyName(), $this->getKey())->forceDelete();\n+ return $this->setKeysForSaveQuery($this->newModelQuery())->forceDelete();\n }\n \n return $this->runSoftDelete();\n@@ -72,7 +72,7 @@ protected function performDeleteOnModel()\n */\n protected function runSoftDelete()\n {\n- $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());\n+ $query = $this->setKeysForSaveQuery($this->newModelQuery());\n \n $time = $this->freshTimestamp();\n ", "filename": "src/Illuminate/Database/Eloquent/SoftDeletes.php", "status": "modified" }, { "diff": "@@ -19,7 +19,7 @@ public function testDeleteSetsSoftDeletedColumn()\n $model = m::mock(DatabaseSoftDeletingTraitStub::class);\n $model->makePartial();\n $model->shouldReceive('newModelQuery')->andReturn($query = m::mock(stdClass::class));\n- $query->shouldReceive('where')->once()->with('id', 1)->andReturn($query);\n+ $query->shouldReceive('where')->once()->with('id', '=', 1)->andReturn($query);\n $query->shouldReceive('update')->once()->with([\n 'deleted_at' => 'date-time',\n 'updated_at' => 'date-time',\n@@ -104,4 +104,16 @@ public function getUpdatedAtColumn()\n {\n return defined('static::UPDATED_AT') ? static::UPDATED_AT : 'updated_at';\n }\n+\n+ public function setKeysForSaveQuery($query)\n+ {\n+ $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());\n+\n+ return $query;\n+ }\n+\n+ protected function getKeyForSaveQuery()\n+ {\n+ return 1;\n+ }\n }", "filename": "tests/Database/DatabaseSoftDeletingTraitTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.7\r\n- PHP: 7.2.4\r\n\r\n### Description:\r\nThere is a difference in declared return type for `Illuminate\\Http\\Request::ip()` method wrapper and method from base class \r\nhttps://github.com/laravel/framework/blob/5.8/src/Illuminate/Http/Request.php#L272\r\nhttps://github.com/symfony/http-foundation/blob/master/Request.php#L795\r\n\r\nSome libraries use documented return type for type checking and error throws unexpectedly when method return **null** value (it's not a rare case when using proxies), like here\r\nhttps://github.com/cyrildewit/eloquent-viewable/blob/master/src/Resolvers/IpAddressResolver.php#L26\r\n\r\nI think return types should match between both declarations.\r\n\r\n### Steps to reproduce:\r\nRequest::ip() can return null in some environments, behind proxy", "comments": [ { "body": "Please fill out the entire issue template.", "created_at": "2019-03-29T12:33:08Z" }, { "body": "The return type should indeed match the one from Symfony.", "created_at": "2019-03-29T12:34:23Z" } ], "number": 28056, "title": "Request::getClientIp method missed null return type declaration" }
{ "body": "Add null return type for Request::ip() method as it can be returned from base class. Fix for issue #28056 ", "number": 28057, "review_comments": [], "title": "[5.8] Fix missed type declaration from base class (Fixes #28056)" }
{ "commits": [ { "message": "Fix missed type declaration from base class" } ], "files": [ { "diff": "@@ -269,7 +269,7 @@ public function secure()\n /**\n * Get the client IP address.\n *\n- * @return string\n+ * @return string|null\n */\n public function ip()\n {", "filename": "src/Illuminate/Http/Request.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.25 || 5.8.2\r\n- PHP Version: 7.2.13\r\n- Database Driver & Version: NA\r\n\r\n### Description:\r\n`php artisan event:generate` command assumes that event class exists in `app\\Events`\r\n\r\n### Steps To Reproduce:\r\nUpdate your `EventServiceProvider` with event class that is coming from vendor, for [example](https://laravel.com/docs/5.7/passport#events)\r\n```php\r\nprotected $listen = [\r\n 'Laravel\\Passport\\Events\\AccessTokenCreated' => [\r\n 'App\\Listeners\\RevokeOldTokens',\r\n ],\r\n];\r\n```\r\nRun `php artisan event:generate`\r\nCheck your `app/Listeners/PruneOldTokens.php` file, it should have wrong namespace imported.\r\n```\r\nuse App\\Events\\Laravel\\Passport\\Events\\RefreshTokenCreated;\r\n```\r\n", "comments": [ { "body": "Seems like a job for the make:listener command. \r\n", "created_at": "2019-02-09T16:20:49Z" }, { "body": "What happens when you use the `::class` notation instead?", "created_at": "2019-02-11T11:19:35Z" }, { "body": "Tried this \r\n```php\r\n protected $listen = [\r\n \\Laravel\\Passport\\Events\\AccessTokenCreated::class => [\r\n 'App\\Listeners\\RevokeOldTokens',\r\n ],\r\n ];\r\n```\r\nBut same results", "created_at": "2019-02-11T12:15:07Z" }, { "body": "I can not reproduce it on laravel 5.7.x\r\n\r\nThat only will happen if the event class does not exist.\r\nI think you have some typos or something in the namespace of the event class.", "created_at": "2019-02-11T22:52:30Z" }, { "body": "@imanghafoori1\r\nI have laravel passport installed, so i am sure that \r\n`\r\nLaravel\\Passport\\Events\\AccessTokenCreated\r\n`\r\nevent class exists", "created_at": "2019-02-12T06:52:32Z" }, { "body": "I can not reproduce the bug on 5.7.x It does successfully import like the following\r\n\r\n```\r\nuse App\\Providers\\Laravel\\Passport\\Events\\AccessTokenCreated;\r\n```\r\n\r\nBut, if you don't install `passport` it seems like the behavior you described. Please make sure for us.", "created_at": "2019-02-28T13:08:31Z" }, { "body": "5.7.28\r\n\r\n```php\r\n'Foo\\Bar\\Nonexisting\\Event' => [\r\n 'App\\Listeners\\Foo',\r\n],\r\n```\r\n\r\n```bash\r\n$ cat Events/Foo/Bar/Nonexisting/Event.php\r\n<?php\r\n\r\nnamespace App\\Events\\Foo\\Bar\\Nonexisting;\r\n```\r\n\r\nI think the correct behavior in the case of nonexisting non-`\\App` events would be throwing an error?", "created_at": "2019-03-01T15:05:56Z" }, { "body": "Another finding -\r\nThe command work well with [event](https://laravel.com/docs/5.7/notifications#notification-events) from `Illuminate` namespace\r\n```php\r\n// EventServiceProvider\r\nprotected $listen = [\r\n 'Illuminate\\Notifications\\Events\\NotificationSent' => [\r\n 'App\\Listeners\\LogNotification',\r\n ],\r\n];\r\n```", "created_at": "2019-03-03T04:56:49Z" }, { "body": "I've looked over the code involved with ```event:generate``` and believe I've come up with the problem and a solution. Looking for feedback before making a PR.\r\n\r\nIt all happens in the ListenerMakeCommand class.\r\n\r\nThere is a check to see if the given event namespace starts with (1)your project namespace(App), (2)\"Illuminate\", or (3)\"\\\\\".\r\n\r\nSo it looks like the command expects 3 situations:\r\n1. Your event is somewhere in your project's namespace.\r\n2. Your event is in the Illuminate namespace.\r\n3. Your event is elsewhere and you are showing that by starting with a '\\\\'.\r\n\r\nIf those assumptions are true, then you should be able to generate listeners from events in third party namespaces by adding a starting '\\\\' to your event in the ```$listen``` array of your EventServiceProvider. \r\nHowever, if you do that, then the '\\\\' doesn't get dropped and the namespace at the top of the generated listener for your event, will still have the starting '\\\\'.\r\n\r\nI propose a simple call to ```trim``` when replacing the 'DummyFullEvent' at the top of the listener class. \r\nSo instead of:\r\n```php\r\n return str_replace(\r\n 'DummyFullEvent', $event, $stub\r\n );\r\n```\r\nWe can do:\r\n```php\r\n return str_replace(\r\n 'DummyFullEvent', trim($event, '\\\\'), $stub\r\n );\r\n```\r\nAnd the Event namespace will be correct in the Listener class.\r\n\r\nThoughts?\r\n\r\nI've ran several test scenarios with this change in place and everything seems to work as expected?", "created_at": "2019-03-25T15:47:02Z" }, { "body": "@devcircus lgtm 👍 ", "created_at": "2019-03-25T15:59:46Z" }, { "body": "PR was merged.", "created_at": "2019-03-26T17:20:14Z" }, { "body": "#28007 was merged.\r\n\r\n> Note: Using ```event:generate``` as described by the OP, will still not work. \r\n\r\nThe command expects one of three event namespace styles:\r\n1. Your event is in your local project's namespace (eg. App)\r\n - In this case, either import your event at the top of the service provider, or if it doesn't exist yet, just use the string version(eg. 'App\\Events\\MyEvent').\r\n2. Your event is in the Illuminate namespace. \r\n - You can either import the event class or use the string version starting with 'Illuminate'.\r\n3. Your event is in a third-party namespace. \r\n - You must use the string version and start it with a '\\\\'. (eg. '\\MyGreatVendor\\\\MyGreatPackage\\\\MyGreatEvent')\r\n\r\nI guess this could be looked at in the future for a better way to handle all of these cases without having to differentiate, but for now, this should work.", "created_at": "2019-03-26T17:24:20Z" }, { "body": "#30796 I'v open a new issure for my problem. \r\nThree ways only one could be work, and the others would not.\r\nI do not think the problems were solved.", "created_at": "2019-12-11T01:41:09Z" } ], "number": 27468, "title": "event:generate command namespace issue" }
{ "body": "## Problem Summary\r\nSee #27468\r\nThe issue arises when running ```event:generate``` for events in third-party namespaces (non-App and non-Illuminate). \r\nThe FQCN of the event (in the \"use\" statement at the top of the Listener class) has a preceding '\\\\'.\r\n\r\n## Before\r\n```php\r\n<?php\r\n\r\nnamespace App\\Listeners;\r\n\r\nuse \\GreatLaravelPackages\\GreatePackage\\GreatEvent;\r\n\r\nclass MyGreatListener\r\n{\r\n}\r\n```\r\n\r\n## After\r\n```php\r\n<?php\r\n\r\nnamespace App\\Listeners;\r\n\r\nuse GreatLaravelPackages\\GreatePackage\\GreatEvent;\r\n\r\nclass MyGreatListener\r\n{\r\n}\r\n```\r\n\r\n## Details\r\nIn ```ListenerMakeCommand```, there is a check to see if the given event namespace starts with: \r\n(1) your project namespace(App) \r\n(2)\"Illuminate\"\r\n(3)\"\\\\\"\r\n\r\nSo it looks like the ```event:generate``` command expects 3 situations:\r\n1. Your event is somewhere in your project's namespace (App).\r\n2. Your event is in the Illuminate namespace.\r\n3. Your event is elsewhere and you are showing that by starting with a '\\\\'.\r\n\r\nIf those assumptions are true, then you should be able to generate listeners from events in third party namespaces by adding a starting '\\\\' to your event in the ```$listen``` array of your EventServiceProvider.\r\n \r\nHowever, if you do that, then the '\\\\' doesn't get dropped and the namespace at the top of the generated listener for your event, will still have the starting '\\\\'.\r\n\r\n## Solution\r\nSimply ```trim``` the full event name when replacing the ```DummyFullEvent```.\r\n", "number": 28007, "review_comments": [], "title": "[5.8] Fix incorrect event namespace in generated listener." }
{ "commits": [ { "message": "Fix incorrect event namespace in generated listener." } ], "files": [ { "diff": "@@ -52,7 +52,7 @@ protected function buildClass($name)\n );\n \n return str_replace(\n- 'DummyFullEvent', $event, $stub\n+ 'DummyFullEvent', trim($event, '\\\\'), $stub\n );\n }\n ", "filename": "src/Illuminate/Foundation/Console/ListenerMakeCommand.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8\r\n- PHP Version: 7.3\r\n- Database Driver & Version: MySQL\r\n\r\n### Description:\r\nBy default Laravel will 'null' a resource key when whenLoaded returns false, however when I attach the KeyBy method to the end of the call, this will throw an error.\r\n\r\n> Call to undefined method Illuminate\\Http\\Resources\\Json\\AnonymousResourceCollection::keyBy()\r\n\r\n### Steps To Reproduce:\r\n\r\n```\r\n public function toArray($request)\r\n {\r\n return [\r\n 'id' => $this->id,\r\n 'data' => [\r\n 'translations' => MenuTranslationResource::collection($this->whenLoaded('translations'))\r\n ->keyBy(function ($trans) {\r\n return $trans['locale'];\r\n })\r\n ]\r\n ];\r\n }\r\n```", "comments": [ { "body": "Hey there @notflip. ResourceCollections aren't really collections like the collection class but rather also JsonResources. That's why they don't share the same functionality. ", "created_at": "2019-03-22T14:30:01Z" }, { "body": "You would have to build this manually:\r\n\r\n```php\r\npublic function toArray($request)\r\n{\r\n $data = [\r\n 'id' => $this->id,\r\n 'data' => [],\r\n ];\r\n\r\n if ($this->resource->relationLoaded('translations')) {\r\n $result['data']['translations'] = MenuTranslationResource::collection($this->resource->translations)\r\n ->keyBy(function ($trans) {\r\n return $trans['locale'];\r\n });\r\n } \r\n \r\n return $data;\r\n}\r\n```", "created_at": "2019-03-22T14:50:59Z" }, { "body": "@staudenmeir that still wouldn't work since the `collection` method returns an instance of `AnonymousResourceCollection` which isn't an instance of `Illuminate\\Support\\Collection`, right?", "created_at": "2019-03-22T15:15:05Z" }, { "body": "@driesvints Is there a way to make this work? Can I define the keyBy somewhere else as to achieve the key => value result from that resource? Thank you.", "created_at": "2019-03-22T15:15:52Z" }, { "body": "@driesvints `AnonymousResourceCollection` has a `__call()` method that forwards this to the underlying collection.", "created_at": "2019-03-22T15:21:45Z" }, { "body": "@notflip I don't know for certain myself atm. I haven't worked with json resources a lot myself yet. I think it's best if you asked on one of the below channels. You'll probably get faster feedback there.\r\n\r\n- [Laracasts Forums](https://laracasts.com/discuss)\r\n- [Laravel.io Forums](https://laravel.io/forum)\r\n- [StackOverflow](https://stackoverflow.com/questions/tagged/laravel)\r\n- [Discord](https://discordapp.com/invite/KxwQuKb)\r\n- [Larachat](https://larachat.co)\r\n- [IRC](https://webchat.freenode.net/?nick=laravelnewbie&channels=%23laravel&prompt=1)", "created_at": "2019-03-22T15:21:49Z" }, { "body": "@staudenmeir right. Then that would work. Thanks for noting that 👍 ", "created_at": "2019-03-22T15:22:27Z" }, { "body": "Forget my hacky workaround, this is the actual solution:\r\n\r\n```php\r\npublic function toArray($request)\r\n{\r\n return [\r\n 'id' => $this->id,\r\n 'data' => [\r\n 'translations' => new MenuTranslationResourceCollection(\r\n $this->whenLoaded('translations', function () {\r\n return $this->translations->keyBy(function ($trans) {\r\n return $trans['locale'];\r\n });\r\n })\r\n )\r\n ]\r\n ];\r\n}\r\n\r\nclass MenuTranslationResourceCollection extends ResourceCollection\r\n{\r\n public $collects = 'App\\Http\\Resources\\MenuTranslationResource';\r\n\r\n public $preserveKeys = true;\r\n\r\n /**\r\n * Transform the resource collection into an array.\r\n *\r\n * @param \\Illuminate\\Http\\Request $request\r\n * @return array\r\n */\r\n public function toArray($request)\r\n {\r\n return parent::toArray($request);\r\n }\r\n}\r\n```\r\n\r\n`whenLoaded()` accepts a closure as the second parameter to customize the result.\r\n\r\nThe latest versions of Laravel reset numeric keys in associative arrays, so we have to prevent this by adding `public $preserveKeys = true;` to `MenuTranslationResource`.\r\n\r\nHowever: The example from the [documentation](https://laravel.com/docs/5.8/eloquent-resources#generating-resources) (\"Preserving Collection Keys\") doesn't actually work with `MenuTranslationResource::collection()`. At least for now, we need a separate `MenuTranslationResourceCollection` class (https://github.com/laravel/framework/pull/27394#issuecomment-475833765).", "created_at": "2019-03-23T02:50:39Z" }, { "body": "Okay, re-opening this.", "created_at": "2019-03-23T14:47:49Z" }, { "body": "Final solution for Laravel 5.8.9:\r\n\r\n```php\r\npublic function toArray($request)\r\n{\r\n return [\r\n 'id' => $this->id,\r\n 'data' => [\r\n 'translations' => MenuTranslationResource::collection(\r\n $this->whenLoaded('translations', function () {\r\n return $this->translations->keyBy(function ($trans) {\r\n return $trans['locale'];\r\n });\r\n })\r\n )\r\n ]\r\n ];\r\n}\r\n\r\nclass MenuTranslationResource extends JsonResource\r\n{\r\n public $preserveKeys = true;\r\n\r\n [...]\r\n}\r\n```", "created_at": "2019-04-03T00:11:02Z" }, { "body": "So is this still an issue or can this be closed?", "created_at": "2019-04-04T14:26:46Z" }, { "body": "Can be closed.", "created_at": "2019-04-04T14:31:04Z" } ], "number": 27950, "title": "Resource with whenLoaded and KeyBy" }
{ "body": "As [commented](https://github.com/laravel/framework/pull/27394#issuecomment-475833765) by @staudenmeir, when setting the `preserveKeys` in a resource, but generating a collection from it, the keys are not preserved.\r\n\r\nBefore this PR the example in the docs should not work:\r\n\r\n```php\r\nuse App\\User;\r\nuse App\\Http\\Resources\\User as UserResource;\r\n\r\nRoute::get('/user', function () {\r\n return UserResource::collection(User::all()->keyBy->id);\r\n});\r\n```\r\n\r\nAs the `JsonResource::collection` returns a `AnonymousResourceCollection` and this class does not have a `preserveKeys` attribute, it fails on keeping the keys when serializing as currently we only check the `$preserveKeys` property in the object being serialized.\r\n\r\nThis PR adds a method to the `ConditionallyLoadsAttributes` trait to handle both the cases of serializing a Resoruce or a Collection of resources.\r\n\r\nI used reflection to accomplish this, maybe to 5.9 we could change to using an Interface, I think it would clearer.\r\n\r\nWorth noticing that @staudenmeir found this bug while working on issue #27950", "number": 27985, "review_comments": [ { "body": "should probably catch a reflection exception here?", "created_at": "2019-03-24T17:12:44Z" }, { "body": "Changed the approach and moved this method to another file. But made the change you suggested. Thanks!", "created_at": "2019-03-25T08:55:57Z" } ], "title": "[5.8] Check for preserveKeys when serializing a collection from a resource" }
{ "commits": [ { "message": "check for preserveKeys when serializing a collection from a resource" }, { "message": "use tap" } ], "files": [ { "diff": "@@ -75,7 +75,11 @@ public static function make(...$parameters)\n */\n public static function collection($resource)\n {\n- return new AnonymousResourceCollection($resource, static::class);\n+ return tap(new AnonymousResourceCollection($resource, static::class), function ($collection) {\n+ if (property_exists(static::class, 'preserveKeys')) {\n+ $collection->preserveKeys = (new static([]))->preserveKeys === true;\n+ }\n+ });\n }\n \n /**", "filename": "src/Illuminate/Http/Resources/Json/JsonResource.php", "status": "modified" }, { "diff": "@@ -3,6 +3,7 @@\n namespace Illuminate\\Tests\\Integration\\Http;\n \n use Orchestra\\Testbench\\TestCase;\n+use Illuminate\\Support\\Collection;\n use Illuminate\\Support\\Facades\\Route;\n use Illuminate\\Http\\Resources\\MergeValue;\n use Illuminate\\Http\\Resources\\MissingValue;\n@@ -629,6 +630,39 @@ public function test_keys_are_preserved_if_the_resource_is_flagged_to_preserve_k\n $response->assertJson(['data' => $data]);\n }\n \n+ public function test_keys_are_preserved_in_an_anonymous_colletion_if_the_resource_is_flagged_to_preserve_keys()\n+ {\n+ $data = Collection::make([\n+ [\n+ 'id' => 1,\n+ 'authorId' => 5,\n+ 'bookId' => 22,\n+ ],\n+ [\n+ 'id' => 2,\n+ 'authorId' => 5,\n+ 'bookId' => 15,\n+ ],\n+ [\n+ 'id' => 3,\n+ 'authorId' => 42,\n+ 'bookId' => 12,\n+ ],\n+ ])->keyBy->id;\n+\n+ Route::get('/', function () use ($data) {\n+ return ResourceWithPreservedKeys::collection($data);\n+ });\n+\n+ $response = $this->withoutExceptionHandling()->get(\n+ '/', ['Accept' => 'application/json']\n+ );\n+\n+ $response->assertStatus(200);\n+\n+ $response->assertJson(['data' => $data->toArray()]);\n+ }\n+\n public function test_leading_merge_keyed_value_is_merged_correctly()\n {\n $filter = new class {", "filename": "tests/Integration/Http/ResourceTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.2\r\n- PHP Version: 7.2\r\n- Database Driver & Version: n/a\r\n\r\n### Description:\r\n[[5.8] Provide a path of the view in compiled view](https://github.com/laravel/framework/pull/27544) added a new feature so that the first line of a compiled template contains the path to the view.\r\n\r\nUnfortunately this breaks templates using `<?php declare(strict_types = 1);` in the first line.\r\n\r\nPHP requires strict_types to be the very first statement in the PHP file. The error:\r\n```PHP Fatal error: strict_types declaration must be the very first statement in the script in /vagrant/project/storage/framework/views/b4b770a497bc79e9d39868f8567850fb50c4f817.php on line 2\r\n\r\nIn b4b770a497bc79e9d39868f8567850fb50c4f817.php line 2:\r\n \r\n strict_types declaration must be the very first statement in the script \r\n```\r\n\r\n### Steps To Reproduce:\r\nTemplate:\r\n```php\r\n<?php declare(strict_types = 1);\r\n// anything you want\r\n```\r\n\r\nGenerated template in 5.7:\r\n```php\r\n<?php declare(strict_types = 1);\r\n// anything you want\r\n```\r\n\r\nGenerated template in 5.8:\r\n```php\r\n<?php /* /vagrant/project/resources/views/emails/template.blade.php */ ?>\r\n<?php declare(strict_types = 1);\r\n// anything you want\r\n```\r\n\r\nWere I work there's a strict policy about this requirement with no exceptions, same for type declarations. I've been using them since Laravel 5.1 and never had issues so far.", "comments": [ { "body": "Unfortunately strict types declaration was not taken into account by myself, my fault. \r\nSome info about usages: https://github.com/search?q=declare%28strict_types+language%3Ablade&type=Code\r\n\r\n@taylorotwell do you see any possible pitfalls in the first scenario when we add template path as a last line in the compiled view as a fix for the issue? \r\n", "created_at": "2019-02-28T09:25:51Z" }, { "body": "This might be a very subjective opinion but is it even our responsibility to fix this? Just don't put the declaration on top? I've indeed seen some examples which place it next to the `<?php` declaration but other major projects (Doctrine amongst else) do this two lines below. Even the upcoming PSR-12 Extended Coding Style requires it to be two lines below: https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#3-declare-statements-namespace-and-import-statements", "created_at": "2019-02-28T10:25:37Z" }, { "body": "What I'm trying to say is that it's not very common to put things right after the `<?php` declaration and even should be avoided imo.", "created_at": "2019-02-28T10:26:38Z" }, { "body": "I see no problem adding it to the end of the script instead.", "created_at": "2019-02-28T14:40:17Z" }, { "body": "I have to retract my statement. Didn't notice it's a separate php statement. This indeed won't work: https://3v4l.org/6UfqU", "created_at": "2019-02-28T14:46:31Z" }, { "body": "If we can generate it as follows it'll work.\r\n\r\n```\r\n<?php /* /vagrant/project/resources/views/emails/template.blade.php */ \r\ndeclare(strict_types = 1);\r\n```", "created_at": "2019-02-28T14:47:57Z" }, { "body": "@bzixilu would the phpstorm functionality still work with the above example?", "created_at": "2019-02-28T15:17:02Z" }, { "body": "So, how can we move forward here?\r\n\r\nI know PhpStorm made it their news that they now support template debugging ( https://blog.jetbrains.com/phpstorm/2019/03/phpstorm-2019-1-beta/ ) and sure, it's useful.\r\n\r\nLaravel itself though has no stake in it and if the original developer doens't come forward with a fix, shouldn't this be reverted then as it breaks functionality which is perfectly legal and fine and worked _literally_ for years until this came along?", "created_at": "2019-03-16T08:17:57Z" }, { "body": "First of all, sorry for the long silence.\r\n\r\n@driesvints if I understand you right, you suggest to insert a path to the first <?php ...> tag in the compiled view if it exists. The solution might work indeed, but it's a little bit harder than just adding the path at the end of the compiled view since it requires Blade compiler as well as PhpStorm to go through the file and find this first PHP tag.\r\n\r\nBesides, there is a couple of other minor things. It's easier for an eye to find a debug info in a permanent place like at the end of the file. Furthermore, in the future, we will also need to provide line mappings in the debug info. If we insert those lines somewhere in the middle of the compiled view, it will look strange.\r\n\r\nSo I would prefer to just move the comment with a view path to the end of the file (please take a look at pull-request https://github.com/laravel/framework/pull/27914)\r\nHowever, all mentioned above concerns are not very essential and may be subjective and if you insist I will implement the fix in the suggested way.", "created_at": "2019-03-18T12:18:33Z" }, { "body": "@bzixilu this looks good! ", "created_at": "2019-03-18T13:14:44Z" }, { "body": "PR was merged.", "created_at": "2019-03-18T15:06:07Z" }, { "body": "Thank you @bzixilu 👍 ", "created_at": "2019-03-18T15:33:21Z" }, { "body": "Hi everyone,\r\n\r\nWe noticed an error in our package caused by this PR and I just wanted to check if that behavior is intended.\r\n\r\nThere's a [simple test](https://github.com/hyn/multi-tenant/blob/5.x/tests/unit-tests/Filesystem/LoadsViewsTest.php#L49) that checks whether our package can override the basic views. All we do is simply create a view through the filesystem, then check if the rendered view has the text we provided in it.\r\n\r\nNormally tests pass with ease, but since this PR got merged, we get this error.\r\n```\r\n1) Hyn\\Tenancy\\Tests\\Filesystem\\LoadsViewsTest::loads_additional_views\r\nFailed asserting that two strings are equal.\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n-'bar'\r\n+'bar\\n\r\n+'\r\n```\r\n\r\nJust wanted to check with you if this behavior was intentional or unintentional.", "created_at": "2019-03-20T08:03:50Z" }, { "body": "It's a side effect of the change: https://github.com/laravel/framework/pull/27914/files#diff-314543ef8cd684a5a1ca0d2388d419ebR122", "created_at": "2019-03-20T08:16:36Z" }, { "body": "@mfn Yeah, appreciate the reply, so this is intentional and will stay like this? :)", "created_at": "2019-03-20T11:59:32Z" }, { "body": "I think it's best that we remove the newline if there's no path present.", "created_at": "2019-03-21T12:35:28Z" }, { "body": "Well, for me it's not exactly clear how this behavior could be caused by the change mentioned above since I would expect in failed test something like: \r\n```\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n-'bar'\r\n+'bar\\n\r\n+<?php /* */ ?>\r\n+'\r\n```\r\nif no path specified in the view. But probably I missed something. \r\n\r\nBut I totally agree that we should not add the path if it's not specified in the view. \r\nPlease find the pull-request with the fix: #27976\r\nI hope it helps to resolve the issue above.", "created_at": "2019-03-22T14:31:26Z" }, { "body": "PR was merged.", "created_at": "2019-03-22T15:49:24Z" } ], "number": 27704, "title": "[5.8] Path of the view in compiled template causes regression with declare(strict_types=1) in templates" }
{ "body": "The pull-request relates to recent feature: https://github.com/laravel/framework/pull/27544\r\nAs it's discussed in #27704 it makes sense to add the path to view only if it's specified and not empty.\r\nPlease take a look.", "number": 27976, "review_comments": [], "title": "[5.8] don't add the path if it's null or empty" }
{ "commits": [ { "message": "[5.8] don't add the path if it's null or empty" }, { "message": "[5.8] don't add the path if it's null or empty\n\n+ fix code style issues" }, { "message": "Styling" } ], "files": [ { "diff": "@@ -118,10 +118,17 @@ public function compile($path = null)\n }\n \n if (! is_null($this->cachePath)) {\n- $contents = $this->compileString($this->files->get($this->getPath())).\n- \"\\n<?php /* {$this->getPath()} */ ?>\";\n+ $contents = $this->compileString(\n+ $this->files->get($this->getPath())\n+ );\n \n- $this->files->put($this->getCompiledPath($this->getPath()), $contents);\n+ if (! empty($this->getPath())) {\n+ $contents .= \"\\n<?php /* {$this->getPath()} */ ?>\";\n+ }\n+\n+ $this->files->put(\n+ $this->getCompiledPath($this->getPath()), $contents\n+ );\n }\n }\n ", "filename": "src/Illuminate/View/Compilers/BladeCompiler.php", "status": "modified" }, { "diff": "@@ -101,6 +101,24 @@ public function testIncludePathToTemplate()\n $compiler->compile('foo');\n }\n \n+ public function testDontIncludeEmptyPath()\n+ {\n+ $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n+ $files->shouldReceive('get')->once()->with('')->andReturn('Hello World');\n+ $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('').'.php', 'Hello World');\n+ $compiler->setPath('');\n+ $compiler->compile();\n+ }\n+\n+ public function testDontIncludeNullPath()\n+ {\n+ $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n+ $files->shouldReceive('get')->once()->with(null)->andReturn('Hello World');\n+ $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1(null).'.php', 'Hello World');\n+ $compiler->setPath(null);\n+ $compiler->compile();\n+ }\n+\n public function testShouldStartFromStrictTypesDeclaration()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);", "filename": "tests/View/ViewBladeCompilerTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.5\r\n- PHP Version: 7.2.12\r\n- Database Driver & Version: n/a\r\n\r\n### Description:\r\n\r\nWhen upgrading our applications to use Laravel v5.8 there is a major breaking change in the way environment variables are being handled which renders useless the majority of third-party composer libraries that use PHP's `getenv` function.\r\n\r\nThis change is documented here: https://laravel.com/docs/5.8/upgrade which is great, and which we are using to upgrade our systems. Unfortunately this guide does not cover the actual change that was made in the underlying way the Dotenv library is being used. For whatever reason the adapter that was being used to populate the environment that `getenv` uses is no longer being loaded. This is a huge breaking change that effects an entire ecosystem of third-party libraries when being used with Laravel.\r\n\r\nThere was an issue raised here which was recently closed: https://github.com/laravel/framework/issues/27913 In that issue, the response was to use the Laravel `env` helper instead of PHP's `getenv` function. This is good advice for Laravel applications where _you_ are in control of all code but for third-party composer libraries this is not possible. There are literally thousands of libraries out there that have no idea they are being used with Laravel and use `getenv` internally.\r\n\r\nWhat this ultimately means is that it's impossible for us to upgrade any of our applications to Laravel 5.8 while this is broken.\r\n\r\n### Steps To Reproduce:\r\n\r\nUse any code (including any third-party composer library) that uses `getenv` to load an environment variable from the `.env` file. It always returns `false`.", "comments": [ { "body": "`getenv` & `putenv` work just fine for any environment variable outside Laravel's `.env` environment. I've just tested this on a fresh 5.8 app. If you have an integration which relies on integrating with Laravel you should use a custom config file and use the env helper.", "created_at": "2019-03-21T13:14:49Z" }, { "body": "> Use any code (including any third-party composer library) that uses getenv to load an environment variable from the .env file. It always returns false.\r\n\r\nThis indeed won't work anymore but that's documented in the upgrade guide. In this situation you should replace `getenv` with the `env` helper.", "created_at": "2019-03-21T13:15:51Z" }, { "body": "> getenv & putenv work just fine for any environment variable outside Laravel's .env environment.\r\n\r\nYes, I understand that but we _are_ using Laravel here.\r\n\r\n>I've just tested this on a fresh 5.8 app. If you have an integration which relies on integrating with Laravel you should use a custom config file and use the env helper.\r\n\r\nThis would make sense if we are the ones who were responsible for the code. This code is in a third-party library that uses `getenv` throughout. We have no access to the code other than changing the vendor'ed dependency loaded through composer.\r\n\r\n> This indeed won't work anymore but that's documented in the upgrade guide. In this situation you should replace getenv with the env helper.\r\n\r\nHow can I do this if it's a third-party library? Also you are implying the library uses Laravel and has access to the helper. We are using an AWS library which is framework agnostic and will never be able to use the Laravel `env` helper. This also applies to hundreds, if not, thousands of framework agnostic PHP libraries that use `getenv`.\r\n\r\nDo you understand that the Laravel `env` helper function is not available outside of the Laravel framework? Developers rely on the `getenv` function instead when writing a composer library that requires ENV variables.\r\n\r\nWhy has this been closed? This is a huge breaking change that affects lots of PHP libraries which essentially can't be used with Laravel now.", "created_at": "2019-03-21T13:43:22Z" }, { "body": "You should ask the maintainer to update their library to support 5.8. Which library are we talking about exactly? \r\n\r\nCan you provide a **practical** code example which demonstrate how this breaks your app? Please provide third party libraries in the **exact** version you're using them.", "created_at": "2019-03-21T13:51:38Z" }, { "body": "Amazon AWS SDK v3.90.4\r\n\r\nI can't understand why there has been no deprecation notices regarding this or notices about such a huge change in functionality on a minor revision. This is disappointing coming from you guys.", "created_at": "2019-03-21T13:58:27Z" }, { "body": "Another related issue: https://github.com/laravel/framework/issues/27828", "created_at": "2019-03-21T14:01:08Z" }, { "body": "Please **link** to the library in question.", "created_at": "2019-03-21T14:04:14Z" }, { "body": "> I can't understand why there has been no deprecation notices regarding this or notices about such a huge change in functionality on a minor revision. This is disappointing coming from you guys.\r\n\r\nPlease read our upgrade guide before upgrading.", "created_at": "2019-03-21T14:04:48Z" }, { "body": "> Please link to the library in question.\r\n\r\nAre you being serious? https://github.com/aws/aws-sdk-php\r\n\r\nHere's another we're having the same problem with:\r\nhttps://github.com/braintree/braintree_php\r\n\r\n> Please read our upgrade guide before upgrading.\r\n\r\nWe were following it to upgrade our services. Nowhere does it say that the Laravel `.env` file is no longer populating the `getenv` PHP function and that any third-party libraries that rely on it will fail.\r\n\r\nMaybe I can't see it, so can you point that part out please?", "created_at": "2019-03-21T14:23:57Z" }, { "body": "Here's a few more libraries we've identified as affected:\r\n\r\nhttps://github.com/FriendsOfPHP/PHP-CS-Fixer\r\nhttps://github.com/googleapis/google-api-php-client-services\r\nhttps://github.com/vyuldashev/laravel-queue-rabbitmq", "created_at": "2019-03-21T14:32:42Z" }, { "body": "> Are you being serious? https://github.com/aws/aws-sdk-php\r\n\r\nYes, I was. I wanted to make sure we were talking about the same one. This library doesn't integrate with Laravel. There's a separate one which does but it's updated to be used with 5.8 and makes use of the `env` helper in its config file: https://github.com/aws/aws-sdk-php-laravel\r\n\r\n> Here's another we're having the same problem with: https://github.com/braintree/braintree_php\r\n\r\nThis library doesn't directly integrates with Laravel either.\r\n\r\n> Maybe I can't see it, so can you point that part out please?\r\n\r\nThe docs here: https://laravel.com/docs/5.8/upgrade#environment-variable-parsing link to https://github.com/vlucas/phpdotenv/blob/master/UPGRADING.md where at the bottom it details how we implemented the library according to their upgrade guide in a way not to call functions that aren't tread-safe (like `getenv`). But I can agree with you that this isn't super obvious. I'll send in a PR to the docs to make this more explicit.", "created_at": "2019-03-21T14:32:57Z" }, { "body": "@nomad-software I really think you're missing the point of what's being discussed here. If you are using the `.env` file you should **always** use the `env` helper and not the `getenv` function. If you set env variables in any other way (CLI, php config) you can use the `getenv` function.", "created_at": "2019-03-21T14:34:23Z" }, { "body": "So we are only allowed to use libraries officially supported by Laravel now? You do realise that packagist contains are little more than that right?\r\n\r\n> I really think you're missing the point of what's being discussed here.\r\n\r\nNo you are missing the point. You are breaking developer's environments for no good reason (on a minor release I may add) and have not informed anyone of such a big change.\r\n\r\nWhy would you introduce a nice elegant way of handling environment variables (the `.env` file) that developers have been using for years then all of a sudden cripple its use and now advocate defining env vars in multiple different places? This is a huge step backward for no advantage. There is litterally no upside here. You've even broken your own server: https://github.com/laravel/framework/issues/27828", "created_at": "2019-03-21T14:40:07Z" }, { "body": "I have to agree with @nomad-software here , you are essentially saying that from now on all packages will need to have a version made to work with Laravel. I am also not seeing understanding why you are fighting a \"FIX\" that is literally adding two words to a method.", "created_at": "2019-03-21T14:43:53Z" }, { "body": "I've tried being patient and helping to figuring out your problem but because of the negativity going on here and the remarks I've decided that this is where this conversation ends.\r\n\r\nIf you genuinely feel that there's a problem you are free to open up a new issue where we can discuss this in a calm and peaceful manner and I'll be happy to help you figure everything out. ", "created_at": "2019-03-21T14:45:30Z" }, { "body": "What is the fix? I'm not familiar with DotEnv 3.0.", "created_at": "2019-03-21T15:00:37Z" }, { "body": "I've unlocked this again in a hopeful attempt we can perhaps resolve this peacefully.", "created_at": "2019-03-21T16:08:16Z" }, { "body": "As a reminder to all unaware users, Laravel **does not** follow semver, so 5.7 --> 5.8 is a **major** update, not a **minor** update.\r\n\r\nhttps://laravel.com/docs/5.8/releases#versioning-scheme", "created_at": "2019-03-21T16:17:53Z" }, { "body": "We fixed it by altering the ```createDotenv``` function in the ```LoadEnvironmentVariables``` class to look like the below.\r\n```\r\nprotected function createDotenv($app)\r\n {\r\n return Dotenv::create(\r\n $app->environmentPath(),\r\n $app->environmentFile(),\r\n new DotenvFactory([new EnvConstAdapter, new ServerConstAdapter, new PutenvAdapter])\r\n );\r\n }\r\n```\r\nEssentially just adding the ```PutenvAdapter``` object back into the ```DotenvFactory``` constructor this then tells DotEnv to push the ```env``` variables into the php enviroment by using ```putenv()```. ", "created_at": "2019-03-21T16:18:34Z" }, { "body": "I think Laravel developers know in general that Laravel does not follow semver. However this change would make the life of developers 'harder' by default, and make an upgrade path more complicated than it should be.", "created_at": "2019-03-21T16:24:59Z" }, { "body": "@AndyMac2508 like said above this would re-introduce the issue about tread-safety as detailed in the phpdotenv upgrade guide: https://github.com/vlucas/phpdotenv/blob/master/UPGRADING.md\r\n\r\nBut at this point we're thinking about maybe adding the `PutenvAdapter` just for the sake of it since this seems to be affecting much more than the original PR considered. \r\n\r\nFor reference, here's the original PR and a detailed explanation of why these changes were made: https://github.com/laravel/framework/pull/27462", "created_at": "2019-03-21T16:27:37Z" }, { "body": "Don't disagree, but OP kept referring to this as a **minor** update, so I wanted to make sure everyone was on the same page.", "created_at": "2019-03-21T16:27:57Z" }, { "body": "Gotcha, I don't mind adding the `PutenvAdapter` back in. Sorry, I'm on vacation with the family and just woke up to this thread. 😅 ", "created_at": "2019-03-21T16:30:52Z" }, { "body": "I've released 5.8.6 with the PutEnvAdapter in place by default to be more similar to 5.7 behavior.", "created_at": "2019-03-21T16:36:00Z" }, { "body": "You should never rely on getenv being set by Laravel .env files, because if you cache the config file, the .env isn't loaded in production anymore.", "created_at": "2019-03-21T16:37:33Z" }, { "body": "@taylorotwell Thankyou.\r\n\r\n> You should never rely on getenv being set by Laravel .env files, because if you cache the config file, the .env isn't loaded in production anymore.\r\n\r\nYes but for dev, staging and test environments it's a god send.", "created_at": "2019-03-21T16:40:12Z" }, { "body": "As a \"for the future\", I think @driesvints should get more support when it comes to tickets like this. It's clear that he didn't understand the issue and closed the issue out of frustration that people were continuing to disagree with him.", "created_at": "2019-03-21T16:51:09Z" }, { "body": "> You should never rely on getenv being set by Laravel .env files, because if you cache the config file, the .env isn't loaded in production anymore.\r\n\r\nIsn't the entire point of .env is to overwrite system env variables for development access?\r\n\r\nWe shouldn't rely on a .env within production, but .env is extremely useful for local development overrides. Let's assume it's a Docker container: system env will be set within docker, and .env is meant to override those values on a server-by-server instance.\r\n\r\nIn that instance ^^ Laravel will have to set/override the system env vars with all values supplied within .env.", "created_at": "2019-03-21T16:56:34Z" }, { "body": "I asked for this a while back and Graham gave some valid reasons on why it was changed in the first place. See #27814.\r\n\r\nGlad to see this was finally merged in though, it caused some issues for the setup I have now.", "created_at": "2019-03-21T17:01:36Z" }, { "body": "@garygreen that's all well and fine in Laravel but illuminate/support is a generic package that can be used outside of Laravel. Let's take Lumen as an example, you can't config cache there.", "created_at": "2019-03-21T17:59:26Z" } ], "number": 27949, "title": "Laravel 5.8 update breaks third-party composer libraries" }
{ "body": "This PR makes it possible to retrieve `.env` values with `getenv`, which is necessary for some third party libraries to work as expected.\r\n\r\nThis restores the 5.7 behavior. See https://github.com/vlucas/phpdotenv#upgrading-from-v2 for more info.\r\n\r\nResolves #27949 and #27913 .", "number": 27958, "review_comments": [], "title": "[5.8] Allow retrieving env variables with getenv" }
{ "commits": [ { "message": "Test env variables are loaded into $_ENV, $_SERVER, and getenv" }, { "message": "Allow retrieving env variables with getenv from env helper function" } ], "files": [ { "diff": "@@ -8,6 +8,7 @@\n use Dotenv\\Environment\\DotenvFactory;\n use Illuminate\\Contracts\\Support\\Htmlable;\n use Illuminate\\Support\\HigherOrderTapProxy;\n+use Dotenv\\Environment\\Adapter\\PutenvAdapter;\n use Dotenv\\Environment\\Adapter\\EnvConstAdapter;\n use Dotenv\\Environment\\Adapter\\ServerConstAdapter;\n \n@@ -642,7 +643,7 @@ function env($key, $default = null)\n static $variables;\n \n if ($variables === null) {\n- $variables = (new DotenvFactory([new EnvConstAdapter, new ServerConstAdapter]))->createImmutable();\n+ $variables = (new DotenvFactory([new EnvConstAdapter, new PutEnvAdapter, new ServerConstAdapter]))->createImmutable();\n }\n \n return Option::fromValue($variables->get($key))", "filename": "src/Illuminate/Support/helpers.php", "status": "modified" }, { "diff": "@@ -37,6 +37,9 @@ public function testCanLoad()\n (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('.env'));\n \n $this->assertSame('BAR', env('FOO'));\n+ $this->assertSame('BAR', getenv('FOO'));\n+ $this->assertSame('BAR', $_ENV['FOO']);\n+ $this->assertSame('BAR', $_SERVER['FOO']);\n }\n \n public function testCanFailSilent()", "filename": "tests/Foundation/Bootstrap/LoadEnvironmentVariablesTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.2\r\n- PHP Version: 7.2\r\n- Database Driver & Version: n/a\r\n\r\n### Description:\r\n[[5.8] Provide a path of the view in compiled view](https://github.com/laravel/framework/pull/27544) added a new feature so that the first line of a compiled template contains the path to the view.\r\n\r\nUnfortunately this breaks templates using `<?php declare(strict_types = 1);` in the first line.\r\n\r\nPHP requires strict_types to be the very first statement in the PHP file. The error:\r\n```PHP Fatal error: strict_types declaration must be the very first statement in the script in /vagrant/project/storage/framework/views/b4b770a497bc79e9d39868f8567850fb50c4f817.php on line 2\r\n\r\nIn b4b770a497bc79e9d39868f8567850fb50c4f817.php line 2:\r\n \r\n strict_types declaration must be the very first statement in the script \r\n```\r\n\r\n### Steps To Reproduce:\r\nTemplate:\r\n```php\r\n<?php declare(strict_types = 1);\r\n// anything you want\r\n```\r\n\r\nGenerated template in 5.7:\r\n```php\r\n<?php declare(strict_types = 1);\r\n// anything you want\r\n```\r\n\r\nGenerated template in 5.8:\r\n```php\r\n<?php /* /vagrant/project/resources/views/emails/template.blade.php */ ?>\r\n<?php declare(strict_types = 1);\r\n// anything you want\r\n```\r\n\r\nWere I work there's a strict policy about this requirement with no exceptions, same for type declarations. I've been using them since Laravel 5.1 and never had issues so far.", "comments": [ { "body": "Unfortunately strict types declaration was not taken into account by myself, my fault. \r\nSome info about usages: https://github.com/search?q=declare%28strict_types+language%3Ablade&type=Code\r\n\r\n@taylorotwell do you see any possible pitfalls in the first scenario when we add template path as a last line in the compiled view as a fix for the issue? \r\n", "created_at": "2019-02-28T09:25:51Z" }, { "body": "This might be a very subjective opinion but is it even our responsibility to fix this? Just don't put the declaration on top? I've indeed seen some examples which place it next to the `<?php` declaration but other major projects (Doctrine amongst else) do this two lines below. Even the upcoming PSR-12 Extended Coding Style requires it to be two lines below: https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#3-declare-statements-namespace-and-import-statements", "created_at": "2019-02-28T10:25:37Z" }, { "body": "What I'm trying to say is that it's not very common to put things right after the `<?php` declaration and even should be avoided imo.", "created_at": "2019-02-28T10:26:38Z" }, { "body": "I see no problem adding it to the end of the script instead.", "created_at": "2019-02-28T14:40:17Z" }, { "body": "I have to retract my statement. Didn't notice it's a separate php statement. This indeed won't work: https://3v4l.org/6UfqU", "created_at": "2019-02-28T14:46:31Z" }, { "body": "If we can generate it as follows it'll work.\r\n\r\n```\r\n<?php /* /vagrant/project/resources/views/emails/template.blade.php */ \r\ndeclare(strict_types = 1);\r\n```", "created_at": "2019-02-28T14:47:57Z" }, { "body": "@bzixilu would the phpstorm functionality still work with the above example?", "created_at": "2019-02-28T15:17:02Z" }, { "body": "So, how can we move forward here?\r\n\r\nI know PhpStorm made it their news that they now support template debugging ( https://blog.jetbrains.com/phpstorm/2019/03/phpstorm-2019-1-beta/ ) and sure, it's useful.\r\n\r\nLaravel itself though has no stake in it and if the original developer doens't come forward with a fix, shouldn't this be reverted then as it breaks functionality which is perfectly legal and fine and worked _literally_ for years until this came along?", "created_at": "2019-03-16T08:17:57Z" }, { "body": "First of all, sorry for the long silence.\r\n\r\n@driesvints if I understand you right, you suggest to insert a path to the first <?php ...> tag in the compiled view if it exists. The solution might work indeed, but it's a little bit harder than just adding the path at the end of the compiled view since it requires Blade compiler as well as PhpStorm to go through the file and find this first PHP tag.\r\n\r\nBesides, there is a couple of other minor things. It's easier for an eye to find a debug info in a permanent place like at the end of the file. Furthermore, in the future, we will also need to provide line mappings in the debug info. If we insert those lines somewhere in the middle of the compiled view, it will look strange.\r\n\r\nSo I would prefer to just move the comment with a view path to the end of the file (please take a look at pull-request https://github.com/laravel/framework/pull/27914)\r\nHowever, all mentioned above concerns are not very essential and may be subjective and if you insist I will implement the fix in the suggested way.", "created_at": "2019-03-18T12:18:33Z" }, { "body": "@bzixilu this looks good! ", "created_at": "2019-03-18T13:14:44Z" }, { "body": "PR was merged.", "created_at": "2019-03-18T15:06:07Z" }, { "body": "Thank you @bzixilu 👍 ", "created_at": "2019-03-18T15:33:21Z" }, { "body": "Hi everyone,\r\n\r\nWe noticed an error in our package caused by this PR and I just wanted to check if that behavior is intended.\r\n\r\nThere's a [simple test](https://github.com/hyn/multi-tenant/blob/5.x/tests/unit-tests/Filesystem/LoadsViewsTest.php#L49) that checks whether our package can override the basic views. All we do is simply create a view through the filesystem, then check if the rendered view has the text we provided in it.\r\n\r\nNormally tests pass with ease, but since this PR got merged, we get this error.\r\n```\r\n1) Hyn\\Tenancy\\Tests\\Filesystem\\LoadsViewsTest::loads_additional_views\r\nFailed asserting that two strings are equal.\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n-'bar'\r\n+'bar\\n\r\n+'\r\n```\r\n\r\nJust wanted to check with you if this behavior was intentional or unintentional.", "created_at": "2019-03-20T08:03:50Z" }, { "body": "It's a side effect of the change: https://github.com/laravel/framework/pull/27914/files#diff-314543ef8cd684a5a1ca0d2388d419ebR122", "created_at": "2019-03-20T08:16:36Z" }, { "body": "@mfn Yeah, appreciate the reply, so this is intentional and will stay like this? :)", "created_at": "2019-03-20T11:59:32Z" }, { "body": "I think it's best that we remove the newline if there's no path present.", "created_at": "2019-03-21T12:35:28Z" }, { "body": "Well, for me it's not exactly clear how this behavior could be caused by the change mentioned above since I would expect in failed test something like: \r\n```\r\n--- Expected\r\n+++ Actual\r\n@@ @@\r\n-'bar'\r\n+'bar\\n\r\n+<?php /* */ ?>\r\n+'\r\n```\r\nif no path specified in the view. But probably I missed something. \r\n\r\nBut I totally agree that we should not add the path if it's not specified in the view. \r\nPlease find the pull-request with the fix: #27976\r\nI hope it helps to resolve the issue above.", "created_at": "2019-03-22T14:31:26Z" }, { "body": "PR was merged.", "created_at": "2019-03-22T15:49:24Z" } ], "number": 27704, "title": "[5.8] Path of the view in compiled template causes regression with declare(strict_types=1) in templates" }
{ "body": "The pull-request contains the fix for [5.8] Path of the view in compiled template causes regression with declare(strict_types=1) in templates #27704", "number": 27914, "review_comments": [], "title": "[5.8] Path of the view in compiled template causes regression with declare(strict_types=1) in templates #27704" }
{ "commits": [ { "message": "[5.8] Path of the view in compiled template causes regression with declare(strict_types=1) in templates" }, { "message": "[5.8] Path of the view in compiled template causes regression with declare(strict_types=1) in templates\n\n+ test on declare(strict_types=1)" } ], "files": [ { "diff": "@@ -118,8 +118,8 @@ public function compile($path = null)\n }\n \n if (! is_null($this->cachePath)) {\n- $contents = \"<?php /* {$this->getPath()} */ ?>\\n\".\n- $this->compileString($this->files->get($this->getPath()));\n+ $contents = $this->compileString($this->files->get($this->getPath())).\n+ \"\\n<?php /* {$this->getPath()} */ ?>\";\n \n $this->files->put($this->getCompiledPath($this->getPath()), $contents);\n }", "filename": "src/Illuminate/View/Compilers/BladeCompiler.php", "status": "modified" }, { "diff": "@@ -49,15 +49,15 @@ public function testCompileCompilesFileAndReturnsContents()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');\n- $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"<?php /* foo */ ?>\\nHello World\");\n+ $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"Hello World\\n<?php /* foo */ ?>\");\n $compiler->compile('foo');\n }\n \n public function testCompileCompilesAndGetThePath()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');\n- $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"<?php /* foo */ ?>\\nHello World\");\n+ $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"Hello World\\n<?php /* foo */ ?>\");\n $compiler->compile('foo');\n $this->assertEquals('foo', $compiler->getPath());\n }\n@@ -73,7 +73,7 @@ public function testCompileWithPathSetBefore()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');\n- $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"<?php /* foo */ ?>\\nHello World\");\n+ $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"Hello World\\n<?php /* foo */ ?>\");\n // set path before compilation\n $compiler->setPath('foo');\n // trigger compilation with null $path\n@@ -97,10 +97,18 @@ public function testIncludePathToTemplate()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');\n- $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"<?php /* foo */ ?>\\nHello World\");\n+ $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', \"Hello World\\n<?php /* foo */ ?>\");\n $compiler->compile('foo');\n }\n \n+ public function testShouldStartFromStrictTypesDeclaration()\n+ {\n+ $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n+ $strictTypeDecl = \"<?php\\ndeclare(strict_types = 1);\";\n+ $this->assertTrue(substr($compiler->compileString(\"<?php\\ndeclare(strict_types = 1);\\nHello World\"),\n+ 0, strlen($strictTypeDecl)) === $strictTypeDecl);\n+ }\n+\n protected function getFiles()\n {\n return m::mock(Filesystem::class);", "filename": "tests/View/ViewBladeCompilerTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.4.36\r\n- PHP Version: 5.6.32\r\n- Database Driver & Version: Mongo\r\n\r\n### Description:\r\nWhen validating nested arrays with the same keys and rules, an incorrect error message will be picked up, for example, if the rules are:\r\n\r\n`\r\n$rules = [\r\n 'item.*.text' => 'required',\r\n 'item.*.subitem.text' => 'required',\r\n];\r\n`\r\n\r\nand the messages:\r\n\r\n`\r\n$messages = [\r\n 'item.*.text.required' => 'top level item required',\r\n 'item.*.subitem.text.required' => 'sub item required',\r\n];\r\n`\r\n\r\n\"top level item required\" will be returned as the error message for both items\r\n\r\nI believe this is due to an error in the \\Illuminate\\Support\\Str line 152\r\n\r\nThe pattern is currently:\r\n\r\n`$pattern = str_replace('\\*', '.*', $pattern);`\r\n\r\nI think it needs to be:\r\n\r\n`$pattern = str_replace('\\*', '[^.]*', $pattern);`\r\n\r\nEdit: above only really applies to validation, so perhaps Str.php isn't the best location for the change\r\n\r\n### Steps To Reproduce:\r\nDefine the rules specified above, and provide invalid input for both fields\r\n", "comments": [ { "body": "Workaround: put the more restrictive regex first in the rules and messages arrays", "created_at": "2017-12-21T09:25:18Z" }, { "body": "Note that 5.4 is no longer supported. Can you reproduce the issue in a 5.5 environment?", "created_at": "2017-12-21T09:58:19Z" }, { "body": "@Dylan-DPC I can reproduce in 5.5 yes, my controller code:\r\n\r\n```\r\npublic function thisRouteRequiresValidation(Request $request)\r\n{\r\n $rules = [\r\n 'hello.*.text' => 'required',\r\n 'hello.*.world.text' => 'required',\r\n ];\r\n\r\n $messages = [\r\n 'hello.*.text.required' => 'hello.*.text required',\r\n 'hello.*.world.text.required' => 'hello.*.world.text required',\r\n ];\r\n\r\n $res = Validator::make($request->all(), $rules, $messages);\r\n $fail = $res->fails();\r\n $messages = $res->errors();\r\n return response()->json(['hello' => 'world', 'fail' => $fail, 'messages' => $messages]);\r\n}\r\n```\r\n\r\nI sent a request with the content:\r\n\r\n```\r\n{\r\n\t\"hello\": [\r\n\t\t{\r\n\t\t\t\"text\": \"Hello World\"\r\n\t\t}\r\n\t]\r\n}\r\n```\r\n\r\nand the response is:\r\n\r\n```\r\n{\r\n \"hello\": \"world\",\r\n \"fail\": true,\r\n \"messages\": {\r\n \"hello.0.world.text\": [\r\n \"hello.*.text required\"\r\n ]\r\n }\r\n}\r\n```\r\n\r\nas you can see, the rule fired is the hello.0.world.text rule, but the message for hello.*.text has been given", "created_at": "2018-04-09T07:47:23Z" }, { "body": "`Str::is()` is called in [`FormatsMessages::getFromLocalArray()`](https://github.com/laravel/framework/blob/5.6/src/Illuminate/Validation/Concerns/FormatsMessages.php#L101).\r\n\r\nWe can't use `str_replace('*', '[^.]*', $sourceKey)` because it gets escaped by `preg_quote()`.\r\n\r\nWe could:\r\n\r\n - Add a `$wildcard = '.*'` parameter to `Str::is()` and override it with `'[^.]*'`.\r\n - Add a `$escape = true` parameter to `Str::is()` and override it with `false` (Taylor is not fan of those).\r\n - Add something like `Str::isRaw()` which doesn't escape the pattern(s).", "created_at": "2018-04-24T01:26:40Z" }, { "body": "@staudenmeir Been thinking about this (for almost a year apparently)\r\n\r\nNot sure it's worth doing `Str::isRaw` since it would basically be a direct passthrough to `preg_match` \r\n\r\nWhat do you think about changing `FormatsMessages::getFromLocalArray` to use preg_match directly?\r\nEither that or the `$wildcard = '.*'` solution\r\n\r\nHappy to do the work and submit a PR once we decide on a solution", "created_at": "2019-03-01T08:41:20Z" }, { "body": "Scratch that, `$wildcard` seems the most elegant to me, will submit a PR today!", "created_at": "2019-03-01T09:52:51Z" }, { "body": "Remember to target Laravel 5.9, as this is a breaking change.", "created_at": "2019-03-01T10:07:16Z" }, { "body": "I considered it non breaking as existing usage of `Str::is` will function as normal.\r\n\r\nBut I suppose this will change the behaviour of validation (to be correct), so that is why?", "created_at": "2019-03-01T10:10:22Z" }, { "body": "Adding the new parameter to `Str::is()` is the breaking change. It's optional, but still breaks code that overrides the `Str::is()` method.", "created_at": "2019-03-01T10:22:08Z" }, { "body": "@staudenmeir I see what you mean, targeted to 5.9", "created_at": "2019-03-01T10:23:47Z" }, { "body": "Since the PR was rejected I'm also closing this issue. Feel free to create your own macro with this specific behavior.", "created_at": "2019-03-04T15:05:30Z" } ], "number": 22499, "title": "Nested arrays with same key names pick up incorrect validation message" }
{ "body": "Breaking change as may change the behaviour of validation (to be correct)\r\n\r\nSee #22499 \r\n", "number": 27730, "review_comments": [ { "body": "The convention is two spaces:\r\n```suggestion\r\n * @param string $wildcard\r\n```", "created_at": "2019-03-01T10:46:20Z" }, { "body": "IMO, `$this->assertFalse(Str::is('foo.*.baz', 'foo.bar.bar.baz', '[^.]*'));` would be better.\r\n\r\n`'test.bar.bar.baz'` doesn't test the `$wildcard`, it still works without it.", "created_at": "2019-03-01T10:48:33Z" }, { "body": "Ah, typo, I started with test.*.test or something like that and switched to foo/bar", "created_at": "2019-03-01T10:51:54Z" } ], "title": "[5.9] Better handling for wildcards in validation message keys" }
{ "commits": [ { "message": "Add ability to specify wildcard pattern to use for Str::is" }, { "message": "Tweak tests to properly reflect the issue" }, { "message": "Update src/Illuminate/Support/Str.php\n\nCo-Authored-By: mattford <mattford@users.noreply.github.com>" }, { "message": "Fix typo in test" }, { "message": "Merge branch 'LARA-22499' of github.com:mattford/framework into LARA-22499" } ], "files": [ { "diff": "@@ -149,9 +149,10 @@ public static function finish($value, $cap)\n *\n * @param string|array $pattern\n * @param string $value\n+ * @param string $wildcard\n * @return bool\n */\n- public static function is($pattern, $value)\n+ public static function is($pattern, $value, $wildcard = '.*')\n {\n $patterns = Arr::wrap($pattern);\n \n@@ -172,7 +173,7 @@ public static function is($pattern, $value)\n // Asterisks are translated into zero-or-more regular expression wildcards\n // to make it convenient to check if the strings starts with the given\n // pattern such as \"library/*\", making any string check convenient.\n- $pattern = str_replace('\\*', '.*', $pattern);\n+ $pattern = str_replace('\\*', $wildcard, $pattern);\n \n if (preg_match('#^'.$pattern.'\\z#u', $value) === 1) {\n return true;", "filename": "src/Illuminate/Support/Str.php", "status": "modified" }, { "diff": "@@ -98,7 +98,7 @@ protected function getFromLocalArray($attribute, $lowerRule, $source = null)\n // that is not attribute specific. If we find either we'll return it.\n foreach ($keys as $key) {\n foreach (array_keys($source) as $sourceKey) {\n- if (Str::is($sourceKey, $key)) {\n+ if (Str::is($sourceKey, $key, '[^.]*')) {\n return $source[$sourceKey];\n }\n }", "filename": "src/Illuminate/Validation/Concerns/FormatsMessages.php", "status": "modified" }, { "diff": "@@ -191,6 +191,10 @@ public function testIs()\n \n $this->assertTrue(Str::is('foo/bar/baz', $valueObject));\n $this->assertTrue(Str::is($patternObject, $valueObject));\n+\n+ // Tests the wildcard parameter\n+ $this->assertFalse(Str::is('foo.*.baz', 'foo.bar.bar.baz', '[^.]*'));\n+ $this->assertTrue(Str::is('foo.*.baz', 'foo.bar.baz', '[^.]*'));\n }\n \n public function testKebab()", "filename": "tests/Support/SupportStrTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.4.36\r\n- PHP Version: 5.6.32\r\n- Database Driver & Version: Mongo\r\n\r\n### Description:\r\nWhen validating nested arrays with the same keys and rules, an incorrect error message will be picked up, for example, if the rules are:\r\n\r\n`\r\n$rules = [\r\n 'item.*.text' => 'required',\r\n 'item.*.subitem.text' => 'required',\r\n];\r\n`\r\n\r\nand the messages:\r\n\r\n`\r\n$messages = [\r\n 'item.*.text.required' => 'top level item required',\r\n 'item.*.subitem.text.required' => 'sub item required',\r\n];\r\n`\r\n\r\n\"top level item required\" will be returned as the error message for both items\r\n\r\nI believe this is due to an error in the \\Illuminate\\Support\\Str line 152\r\n\r\nThe pattern is currently:\r\n\r\n`$pattern = str_replace('\\*', '.*', $pattern);`\r\n\r\nI think it needs to be:\r\n\r\n`$pattern = str_replace('\\*', '[^.]*', $pattern);`\r\n\r\nEdit: above only really applies to validation, so perhaps Str.php isn't the best location for the change\r\n\r\n### Steps To Reproduce:\r\nDefine the rules specified above, and provide invalid input for both fields\r\n", "comments": [ { "body": "Workaround: put the more restrictive regex first in the rules and messages arrays", "created_at": "2017-12-21T09:25:18Z" }, { "body": "Note that 5.4 is no longer supported. Can you reproduce the issue in a 5.5 environment?", "created_at": "2017-12-21T09:58:19Z" }, { "body": "@Dylan-DPC I can reproduce in 5.5 yes, my controller code:\r\n\r\n```\r\npublic function thisRouteRequiresValidation(Request $request)\r\n{\r\n $rules = [\r\n 'hello.*.text' => 'required',\r\n 'hello.*.world.text' => 'required',\r\n ];\r\n\r\n $messages = [\r\n 'hello.*.text.required' => 'hello.*.text required',\r\n 'hello.*.world.text.required' => 'hello.*.world.text required',\r\n ];\r\n\r\n $res = Validator::make($request->all(), $rules, $messages);\r\n $fail = $res->fails();\r\n $messages = $res->errors();\r\n return response()->json(['hello' => 'world', 'fail' => $fail, 'messages' => $messages]);\r\n}\r\n```\r\n\r\nI sent a request with the content:\r\n\r\n```\r\n{\r\n\t\"hello\": [\r\n\t\t{\r\n\t\t\t\"text\": \"Hello World\"\r\n\t\t}\r\n\t]\r\n}\r\n```\r\n\r\nand the response is:\r\n\r\n```\r\n{\r\n \"hello\": \"world\",\r\n \"fail\": true,\r\n \"messages\": {\r\n \"hello.0.world.text\": [\r\n \"hello.*.text required\"\r\n ]\r\n }\r\n}\r\n```\r\n\r\nas you can see, the rule fired is the hello.0.world.text rule, but the message for hello.*.text has been given", "created_at": "2018-04-09T07:47:23Z" }, { "body": "`Str::is()` is called in [`FormatsMessages::getFromLocalArray()`](https://github.com/laravel/framework/blob/5.6/src/Illuminate/Validation/Concerns/FormatsMessages.php#L101).\r\n\r\nWe can't use `str_replace('*', '[^.]*', $sourceKey)` because it gets escaped by `preg_quote()`.\r\n\r\nWe could:\r\n\r\n - Add a `$wildcard = '.*'` parameter to `Str::is()` and override it with `'[^.]*'`.\r\n - Add a `$escape = true` parameter to `Str::is()` and override it with `false` (Taylor is not fan of those).\r\n - Add something like `Str::isRaw()` which doesn't escape the pattern(s).", "created_at": "2018-04-24T01:26:40Z" }, { "body": "@staudenmeir Been thinking about this (for almost a year apparently)\r\n\r\nNot sure it's worth doing `Str::isRaw` since it would basically be a direct passthrough to `preg_match` \r\n\r\nWhat do you think about changing `FormatsMessages::getFromLocalArray` to use preg_match directly?\r\nEither that or the `$wildcard = '.*'` solution\r\n\r\nHappy to do the work and submit a PR once we decide on a solution", "created_at": "2019-03-01T08:41:20Z" }, { "body": "Scratch that, `$wildcard` seems the most elegant to me, will submit a PR today!", "created_at": "2019-03-01T09:52:51Z" }, { "body": "Remember to target Laravel 5.9, as this is a breaking change.", "created_at": "2019-03-01T10:07:16Z" }, { "body": "I considered it non breaking as existing usage of `Str::is` will function as normal.\r\n\r\nBut I suppose this will change the behaviour of validation (to be correct), so that is why?", "created_at": "2019-03-01T10:10:22Z" }, { "body": "Adding the new parameter to `Str::is()` is the breaking change. It's optional, but still breaks code that overrides the `Str::is()` method.", "created_at": "2019-03-01T10:22:08Z" }, { "body": "@staudenmeir I see what you mean, targeted to 5.9", "created_at": "2019-03-01T10:23:47Z" }, { "body": "Since the PR was rejected I'm also closing this issue. Feel free to create your own macro with this specific behavior.", "created_at": "2019-03-04T15:05:30Z" } ], "number": 22499, "title": "Nested arrays with same key names pick up incorrect validation message" }
{ "body": "See issue #22499 for full details\r\n", "number": 27728, "review_comments": [], "title": "Better handling for wildcards in validation message keys" }
{ "commits": [ { "message": "Add ability to specify wildcard pattern to use for Str::is" }, { "message": "Tweak tests to properly reflect the issue" } ], "files": [ { "diff": "@@ -149,9 +149,10 @@ public static function finish($value, $cap)\n *\n * @param string|array $pattern\n * @param string $value\n+ * @param string $wildcard\n * @return bool\n */\n- public static function is($pattern, $value)\n+ public static function is($pattern, $value, $wildcard = '.*')\n {\n $patterns = Arr::wrap($pattern);\n \n@@ -172,7 +173,7 @@ public static function is($pattern, $value)\n // Asterisks are translated into zero-or-more regular expression wildcards\n // to make it convenient to check if the strings starts with the given\n // pattern such as \"library/*\", making any string check convenient.\n- $pattern = str_replace('\\*', '.*', $pattern);\n+ $pattern = str_replace('\\*', $wildcard, $pattern);\n \n if (preg_match('#^'.$pattern.'\\z#u', $value) === 1) {\n return true;", "filename": "src/Illuminate/Support/Str.php", "status": "modified" }, { "diff": "@@ -98,7 +98,7 @@ protected function getFromLocalArray($attribute, $lowerRule, $source = null)\n // that is not attribute specific. If we find either we'll return it.\n foreach ($keys as $key) {\n foreach (array_keys($source) as $sourceKey) {\n- if (Str::is($sourceKey, $key)) {\n+ if (Str::is($sourceKey, $key, '[^.]*')) {\n return $source[$sourceKey];\n }\n }", "filename": "src/Illuminate/Validation/Concerns/FormatsMessages.php", "status": "modified" }, { "diff": "@@ -191,6 +191,10 @@ public function testIs()\n \n $this->assertTrue(Str::is('foo/bar/baz', $valueObject));\n $this->assertTrue(Str::is($patternObject, $valueObject));\n+\n+ // Tests the wildcard parameter\n+ $this->assertFalse(Str::is('foo.*.baz', 'test.bar.bar.baz', '[^.]*'));\n+ $this->assertTrue(Str::is('foo.*.baz', 'foo.bar.baz', '[^.]*'));\n }\n \n public function testKebab()", "filename": "tests/Support/SupportStrTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.27\r\n- PHP Version: 7.3.2\r\n- Database Driver & Version: redis 4.0.9\r\n\r\n### Description:\r\nWhen calling `Mail::queue($mailable, $queue_name))` an error is created due to an incompatible call to `Mailable::queue()` which expects an `\\Illuminate\\Contracts\\Queue\\Factory` instead of the Queue name.\r\n\r\nOn the [`Mailer::queue` method](https://github.com/laravel/framework/blob/c821cbf6f20fca4c50aa9d8fb08f71425afc07b8/src/Illuminate/Mail/Mailer.php#L377) there is no check/conversion from queue string name to an `\\Illuminate\\Contracts\\Queue\\Factory` object. So, when the [line `$view->queue()`](https://github.com/laravel/framework/blob/c821cbf6f20fca4c50aa9d8fb08f71425afc07b8/src/Illuminate/Mail/Mailer.php#L383) is reached it is incompatible with the expected method signature.\r\n\r\n### Steps To Reproduce:\r\n1. Create a Mailable class (in console: `php artisan make:mail TestMailable`)\r\n2. Call `Mail::queue(new TestMailable, 'my-queue');` from within your code", "comments": [ { "body": "Doing this:\r\n\r\n```\r\n$mailable = (new TestMailable)->onQueue('my-queue');\r\nMail::queue($mailable);\r\n```\r\n\r\nworks as expected, as at some point the queue name is used to load an `Illuminate\\Queue\\QueueManager`, which is used when calling `$view->queue()`\r\n\r\nInstead, doing this:\r\n\r\n```\r\nMail::queue(new TestMailable, 'my-queue');\r\n```\r\n\r\nfails because of the error described before.", "created_at": "2019-02-21T18:22:33Z" }, { "body": "I've followed the code and it seems that `$queue` and `$this->queue` are referencing totally different things.\r\n\r\nWhile ` $this->queue` references the `QueueManager` to use, `$queue` seems to reference the actual queue name to use (which is contained inside the `$view` object). What I did to _fix_ this problem is to change the method code to this:\r\n\r\n```\r\npublic function queue($view, $queue = null)\r\n {\r\n if (! $view instanceof MailableContract) {\r\n throw new InvalidArgumentException('Only mailables may be queued.');\r\n }\r\n\r\n if (is_string($queue)) {\r\n $view->onQueue($queue);\r\n }\r\n\r\n return $view->queue($this->queue);\r\n }\r\n```\r\n\r\nThis replaces the view contained in the mailable to the one being set by the method.\r\n\r\nIs this the correct approach?", "created_at": "2019-02-21T18:48:50Z" }, { "body": "I think you might indeed be onto a bug. Appreciating a PR if you could whip one up.", "created_at": "2019-02-21T22:09:41Z" }, { "body": "Alright, I'll setup a PR and indeed I think this is a bug (I'm guessing the variable naming ended in confusion). I also think this bug reaches beyond this use case, I'm not sure but as I was checking the code I think I saw other places with the same issues. I'll try to get them all on the PR if they exist.", "created_at": "2019-02-22T01:07:47Z" }, { "body": "I've pushed the PR. I reviewed the code and I can gladly say that I did not find any other issues relating to this matter.", "created_at": "2019-02-22T02:03:33Z" } ], "number": 27612, "title": "[5.7] The Mail::queue() causes an error due to incompatible call to Mailable::queue() method" }
{ "body": "The issue was found on the `Illuminate\\Mail\\Mailer::queue` method. The given queue name and the queue manager where used indistinctly which caused the error when calling the `Illuminate\\Mail\\Mailable::queue` method as it expected an `Illuminate\\Contracts\\Queue\\Factory` object.\n\nFixes #27612", "number": 27618, "review_comments": [], "title": "[5.7] Fix an issue when using Mail::queue to queue Mailables" }
{ "commits": [ { "message": "Set the queue name correctly when queing mailables using Mail::queue\n\nA queue name and the queue manager where being used indistinctly so\nthe call errored as it expected an \\Illuminate\\Contracts\\Queue\\Factory\nand not a string." } ], "files": [ { "diff": "@@ -380,7 +380,11 @@ public function queue($view, $queue = null)\n throw new InvalidArgumentException('Only mailables may be queued.');\n }\n \n- return $view->queue(is_null($queue) ? $this->queue : $queue);\n+ if (is_string($queue)) {\n+ $view->onQueue($queue);\n+ }\n+\n+ return $view->queue($this->queue);\n }\n \n /**", "filename": "src/Illuminate/Mail/Mailer.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.13\r\n- PHP Version: 7.1.24\r\n- Database Driver & Version: MySQL\r\n\r\n### Description:\r\nThe documentation for eloquent collections (https://laravel.com/docs/5.7/eloquent-collections#available-methods) states that \r\n\r\n> All Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class\r\n\r\nHowever, there are cases where the two function differently and this can lead to subtle bugs in code built on the framework. Particularly the two collection types differ in how keys are treated with some Eloquent collection methods ignoring specifically assigned keys of the collection in favour of a key structure based on `$model->getKey()`.\r\n\r\n### TL;DR\r\nYou have a situation where\r\n```\r\nModel::all()->keyBy('property')->get('property_value')\r\n```\r\nreturns a value, yet\r\n```\r\nModel::all()->keyBy('property')->only(['property_value'])\r\n```\r\n\r\nreturns nothing.\r\n\r\n### Steps To Reproduce:\r\n\r\nTake a standard collection of two objects, each with two properties, e.g.\r\n```php\r\n$collection = collect([\r\n ['name' => 'foo', 'product_code' => '123'],\r\n ['name' => 'bar', 'product_code' => '456']\r\n]);\r\n```\r\n\r\nYou can key this collection by product code, and filter it to only a specific name using the `keyBy` and `only` collection methods, e.g.\r\n\r\n```php\r\n$collection->keyBy('name')->only(['foo']);\r\n```\r\n\r\nThis returns a filtered collection containing only the item keyed by the value \"foo\":\r\n```\r\n=> Illuminate\\Support\\Collection {#2897\r\n all: [\r\n \"foo\" => [\r\n \"name\" => \"foo\",\r\n \"product_code\" => \"123\",\r\n ],\r\n ],\r\n }\r\n>>>\r\n```\r\n\r\nNow imagine that you have a model (we'll call it Product for sake of argument) with the same two properties, `name` and `product_code`. If you pull a collection of those from the database and try and do the same thing you'll hit problems.\r\n\r\n```\r\nProduct::all()->keyBy('name');\r\n```\r\n\r\nReturns as you'd expect:\r\n\r\n```\r\n=> Illuminate\\Database\\Eloquent\\Collection {#2892\r\n all: [\r\n \"foo\" => App\\Product {#2886\r\n id: 1,\r\n name: \"foo\",\r\n product_code: \"123\",\r\n },\r\n \"bar\" => App\\Product {#2905\r\n id: 2,\r\n name: \"bar\",\r\n product_code: \"456\",\r\n },\r\n ],\r\n }\r\n```\r\n\r\nYou can use some key-related collection methods on this collection, such as `get()`:\r\n\r\n```\r\n>>> Product::all()->keyBy('name')->get('foo');\r\n=> App\\Product {#2891\r\n id: 1,\r\n name: \"foo\",\r\n product_code: \"123\",\r\n }\r\n```\r\n\r\nHowever, `only`, `except` do not work correctly with this keyed collection, so with the same collection as the previous example, `only` fails to find the keyed item:\r\n\r\n```\r\n>>> Product::all()->keyBy('name')->only(['foo']);\r\n=> Illuminate\\Database\\Eloquent\\Collection {#2904\r\n all: [],\r\n }\r\n```\r\n\r\n`except` fails to exclude it:\r\n\r\n```\r\n>>> Product::all()->keyBy('name')->except(['foo']);\r\n=> Illuminate\\Database\\Eloquent\\Collection {#2889\r\n all: [\r\n App\\Product {#2908\r\n id: 1,\r\n name: \"foo\",\r\n product_code: \"123\",\r\n },\r\n App\\Product {#2886\r\n id: 2,\r\n name: \"bar\",\r\n product_code: \"456\",\r\n },\r\n ],\r\n }\r\n```\r\n\r\nSo - we're in the situation where `get($key)` returns an item, but `only([$key])` does not. \r\n\r\nThe root cause seems to be the Eloquent collection's \"only\" and \"except\" methods (and others) which insist on running on a separately built \"dictionary\" (https://github.com/laravel/framework/blob/5.7/src/Illuminate/Database/Eloquent/Collection.php#L364) keyed by the model's `getKey()` results (https://github.com/laravel/framework/blob/5.7/src/Illuminate/Database/Eloquent/Collection.php#L417) and ignore any keys that have been set.\r\n\r\nI assume that this is there so that you can run key-based sensibly on collections pulled straight from the database (which are un-keyed) - however I think it certainly needs to take into account where the collection has been specifically keyed somehow. \r\n\r\nReading through the Eloquent Collection class it seems that `getDictionary()` is used in many of the methods so I'd expect similar misleading results from some of those, although I think careful thought needs to be taken over how things are changed to avoid introducing similar unexpected behaviour.\r\n\r\nNote: This was previously reported in #16976 but I don't think it was understood or explained very well there so got closed with no resolution. \r\n", "comments": [ { "body": "Tricky issue.\r\n\r\nWhat could a non-backwards-breaking fix look like?", "created_at": "2018-11-15T20:37:06Z" }, { "body": "Thanks for bringing this to our attention. Imo this should indeed be solved but the question is how.", "created_at": "2018-11-16T12:09:55Z" }, { "body": "It would be interesting to see if the collection can understand whether it's been keyed (maybe by having the relevant methods toggle an internal flag or similar) or not, so it can use the keys if they exist, or fall back on the `$model->getKey()` behaviour.", "created_at": "2018-11-16T13:15:01Z" }, { "body": "This would be backwards-incompatible but it feels like if any operation is performed on an Eloquent Collection that causes it to change (i.e. `keyBy`), it is no longer an Eloquent Collection and should return a new instance of `Illuminate\\Support\\Collection`. IMO an Eloquent Collection represents a result returned from the database, if you modify the structure of that collection it is no longer representative of the query result.", "created_at": "2018-11-28T00:46:10Z" }, { "body": "->toBase()->only()", "created_at": "2020-04-23T15:08:11Z" } ], "number": 26527, "title": "key inconsistency between base & eloquent collections" }
{ "body": "This PR solves the problem of issue #26527 \r\n\r\nI just set the return of keyBy method as self instead of static, keeping in mind that we use the keyBy, the Eloquent Model in key will be replaced by the given key, so it no longer be more a Eloquent Collection.", "number": 27359, "review_comments": [], "title": "[5.7] Resolve issue #26527 (key inconsistency between base & eloquent collections)" }
{ "commits": [ { "message": "Resolve issue #26527 (key inconsistency between base & eloquent collections)" } ], "files": [ { "diff": "@@ -891,7 +891,7 @@ public function keyBy($keyBy)\n $results[$resolvedKey] = $item;\n }\n \n- return new static($results);\n+ return new self($results);\n }\n \n /**", "filename": "src/Illuminate/Support/Collection.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.20\r\n- PHP Version: Any\r\n- Database Driver & Version: Any\r\n\r\n### Description:\r\n`GenerateCommand@handle()` returns false if no model is executed (if the file already exists). ModelMakeCommand overrides this and still calls `parent::handle()`, but returns nothing. This causes inconsistency between commands, and forces end-developer to re-write the entire `handle()` method when extending it. \r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a CustomModelMake.php command which extends off of the Laravel foundation class and override the `handle()` method.\r\n\r\nFrom the end-developers perspective, the following should work as it does when extending any other command:\r\n```php\r\n<?php\r\nnamespace App\\Console\\Commands;\r\n\r\nclass CustomModelMakeCommand extends ModelMakeCommand {\r\n protected function handle() {\r\n if (parent::handle() === false) {\r\n return false;\r\n }\r\n\r\n if ($this->input->option('all')) {\r\n $this->input->setOption('contract', true);\r\n }\r\n\r\n if ($this->input->option('contract')) {\r\n $this->createContract();\r\n }\r\n }\r\n\r\n protected function createContract() {\r\n // contract creation call here\r\n }\r\n}\r\n```\r\n\r\nThe entirety of the above method would always run, because ModelMake command returns nothing if GeneratorCommand returns false, so the initial condition is never entered. ModeMakeCommand should return false if it did not generate anything, in the same way as its parent class.", "comments": [], "number": 27155, "title": "ModelMakeCommand@handle does not return boolean false" }
{ "body": "ModeMakeCommand@handle should return boolean false in the same manner as its parent.\r\n\r\nFixes #27155\r\n\r\nPlease be gentle, this is my first ever PR \r\n", "number": 27156, "review_comments": [], "title": "[5.7] Update ModelMakeCommand.php" }
{ "commits": [ { "message": "Update ModelMakeCommand.php\n\nModeMakeCommand@handle should return boolean false in the same manner as its parent." } ], "files": [ { "diff": "@@ -37,7 +37,7 @@ class ModelMakeCommand extends GeneratorCommand\n public function handle()\n {\n if (parent::handle() === false && ! $this->option('force')) {\n- return;\n+ return false;\n }\n \n if ($this->option('all')) {", "filename": "src/Illuminate/Foundation/Console/ModelMakeCommand.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7\r\n- PHP Version: 7.2\r\n\r\n### Description:\r\n`ColumnDefinition::index()` has a valid parameter to define the name of the index\r\n\r\n### Steps To Reproduce:\r\nAdd a parameter when calling the index method in a database migration and check that the given parameter is used as index name", "comments": [], "number": 27120, "title": "Missing parameter for index method in ColumnDefinition doc block" }
{ "body": "Resolves #27120\r\n", "number": 27121, "review_comments": [], "title": "[5.7] Fix missing parameter in index() phpdoc" }
{ "commits": [ { "message": "[5.7] Fix missing parameter in index() phpdoc\n\nResolves #27120" } ], "files": [ { "diff": "@@ -15,7 +15,7 @@\n * @method ColumnDefinition default(mixed $value) Specify a \"default\" value for the column\n * @method ColumnDefinition first() Place the column \"first\" in the table (MySQL)\n * @method ColumnDefinition generatedAs(string $expression) Create a SQL compliant identity column (PostgreSQL)\n- * @method ColumnDefinition index() Add an index\n+ * @method ColumnDefinition index(string $indexName) Add an index\n * @method ColumnDefinition nullable(bool $value = true) Allow NULL values to be inserted into the column\n * @method ColumnDefinition primary() Add a primary index\n * @method ColumnDefinition spatialIndex() Add a spatial index", "filename": "src/Illuminate/Database/Schema/ColumnDefinition.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.16\r\n- PHP Version: 7.2.10-0ubuntu0.18.04.1\r\n- Database Driver & Version: \r\n\r\n### Description:\r\n\r\nModelIdentifier object is passed to Listeners instead of real Laravel Model in some cases depending on order of Listeners for same Event.\r\n\r\n### Steps To Reproduce:\r\n\r\n```\r\ngit clone https://github.com/acacha/ModelIndentifierProblem\r\ncd ModelIndentifierProblem\r\ncomposer install\r\nphp artisan migrate\r\ncp .env.example .env\r\nphp artisan key:generate\r\n```\r\n\r\nConfig database in .env file and run:\r\n\r\n```\r\nphp artisan migrate\r\n```\r\n\r\nRun Laravel Valet or similar and execute route /error:\r\n\r\n```\r\nhttp://ModelIndentifierProblem1.test/error\r\n```\r\n\r\nError:\r\n\r\n```\r\nUndefined property: Illuminate\\Contracts\\Database\\ModelIdentifier::$user\r\n```\r\n\r\nWill be throwed\r\n\r\nChange listeners order in **EventServiceProvider** from:\r\n\r\n```\r\nIncidentStored::class => [\r\n LogIncidentStored::class,\r\n SendIncidentCreatedEmail::class,\r\n ],\r\n```\r\n\r\nto:\r\n\r\n```\r\nIncidentStored::class => [\r\n SendIncidentCreatedEmail::class,\r\n LogIncidentStored::class,\r\n ],\r\n```\r\nAnd problem dissapears.\r\n", "comments": [ { "body": "I think i've narrowed it down.\r\n\r\nThe Event gets passed directly to the `Queue` and because it is `Serializeable` it gets serialized as `Jobs` are also `Serializeable`, and because objects are mutable by default in php you'll get the serialized event in your next listener.\r\n\r\nI first thought that this only happens on the `Sync` queue as thats actually just the event bus, but this happens on redis aswel.\r\n\r\nNot sure on how to fix it though, maybe clone every object before it is going to be serialized?", "created_at": "2018-12-11T07:42:32Z" }, { "body": "I might have a fix, but i'm not sure if this problem only exists for this use case.\r\nAs in when the job that is being queued has a property that uses the trait `Illuminate\\Queue\\SerializesModels`.\r\n\r\nI'll create a wip PR soon.", "created_at": "2018-12-14T15:47:05Z" }, { "body": "@koenhoeijmakers @driesvints Hello any news about that issue?", "created_at": "2018-12-31T15:36:29Z" }, { "body": "I haven't really figured out how to write proper tests for this, but the issue has passed by in my thoughts a few times which raises the following question.\r\n\r\nShould we really apply a fix for this or would the consensus be \"Don't queue a job that has a property which uses the trait `Illuminate\\Queue\\SerializesModels`\"?", "created_at": "2019-01-01T20:06:24Z" }, { "body": "Ok I understand what you say it makes sense...", "created_at": "2019-01-08T09:27:33Z" }, { "body": "In the repo provided by myself the problem is with any Listener after LogIncidentStored. It seems LogIncidentStored listener (https://github.com/acacha/ModelIndentifierProblem/blob/master/app/Listeners/LogIncidentStored.php) is the cause of the error maybe because is an event listener that dispatch another event?", "created_at": "2019-03-28T18:53:48Z" }, { "body": "Fixed by updating to PHP 7.4 which uses the new __serialize() and __unserialize() methods on SerializesModels.php which do not mutate the existing properties.", "created_at": "2020-04-30T18:43:23Z" }, { "body": "I think I have the same problem with php ^8.0 and Laravel 8.x. Any ideas | solutions? ", "created_at": "2021-06-03T08:53:04Z" } ], "number": 26791, "title": "ModelIdentifier instead of Laravel Model error in Listener depending on Listeners order for a same event." }
{ "body": "After debugging #26791 which has problems with job serialization i found out that the job is improperly cloned when serializing.\r\n\r\nThe original problem was that the OP was dispatching a job that had a property which was an event (that implemented `SerializesModels`) and therefore the next listener in line didnt get the actual property but a `ModelIdentifier`.\r\n\r\nAt the moment only the `$job` is cloned in the `Queue@createObjectPayload` method.\r\n```php\r\nreturn array_merge($payload, [\r\n 'data' => [\r\n 'commandName' => get_class($job),\r\n 'command' => serialize(clone $job),\r\n ],\r\n]);\r\n```\r\nBut when the underlying property is also an instance of (or well an object that uses) `SerializesModels` it will also serialize this property, which then results in the original property being overridden instead of only the cloned jobs property.\r\n\r\nI might be wrong on this part but this does seem to fix the issue.\r\n\r\nIn the case my theory is right and this might become merged we'll have to decide if this has impact on `Illuminate\\Notifications\\SendQueuedNotifications` as this class has its own implementation of the magic method `__clone`.\r\n ", "number": 26850, "review_comments": [], "title": "[5.8][WIP] fix for #26791" }
{ "commits": [ { "message": "wip fix for #26791" } ], "files": [ { "diff": "@@ -47,6 +47,23 @@ public function __wakeup()\n }\n }\n \n+ public function __clone()\n+ {\n+ foreach ((new ReflectionClass($this))->getProperties() as $property) {\n+ if ($property->isStatic()) {\n+ continue;\n+ }\n+\n+ $value = $this->getPropertyValue($property);\n+\n+ if (is_object($value) && in_array(SerializesModels::class, trait_uses_recursive($value))) {\n+ $value = clone ($value);\n+ }\n+\n+ $property->setValue($this, $value);\n+ }\n+ }\n+\n /**\n * Get the property value for the given property.\n *", "filename": "src/Illuminate/Queue/SerializesModels.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.17\r\n- PHP Version: 7.2\r\n- Database Driver & Version: MySQL 5.7\r\n\r\n### Description:\r\n\r\n[This recent change](https://github.com/laravel/framework/commit/5ff17b497a23ee4a0ab4333a05246a5cc879ab89) by @sebdesign has caused an issue when using illuminate/mail outside of Laravel. The `LoggerInterface` in our situation is a `Monolog\\Logger` instance, as a result the `channel` method is not available to us as per [our unit test](https://travis-ci.org/flarum/core/jobs/467492972).\r\n\r\n### Steps To Reproduce:\r\n\r\n- Bind LoggerInterface to Monolog\\Logger\r\n- Instantiate the Mail Transport manager with driver log\r\n\r\n```\r\n1) Flarum\\Tests\\Install\\DefaultInstallationCommandTest::allows_forum_installation\r\nError: Call to undefined method Monolog\\Logger::channel()\r\n/home/travis/build/flarum/core/vendor/illuminate/mail/TransportManager.php:166\r\n/home/travis/build/flarum/core/vendor/illuminate/support/Manager.php:96\r\n/home/travis/build/flarum/core/vendor/illuminate/support/Manager.php:71\r\n/home/travis/build/flarum/core/vendor/illuminate/mail/MailServiceProvider.php:102\r\n```", "comments": [ { "body": "Hmm you're right. We could check for a specific instance in the method and use the previous behavior if it's an instance without the `channel` method?", "created_at": "2018-12-13T15:45:15Z" }, { "body": "I'll see if I can come up with a solution.", "created_at": "2018-12-13T18:44:18Z" }, { "body": "Looks like that problem are solved in https://github.com/laravel/framework/pull/26842 and https://github.com/laravel/framework/pull/26855 PRs", "created_at": "2018-12-20T23:18:49Z" } ], "number": 26833, "title": "Using illuminate/mail outside of Laravel with driver log breaks" }
{ "body": "Addresses #26833", "number": 26842, "review_comments": [], "title": "[5.7] Allow TransportManager to create log driver with any Psr\\Log\\LoggerInterface instance" }
{ "commits": [ { "message": "Allow TransportManager to create log driver with any Psr\\Log\\LoggerInterface instance" }, { "message": "Fetch the log driver channel only when the LogManager is bound" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n use Aws\\Ses\\SesClient;\n use Illuminate\\Support\\Arr;\n use Psr\\Log\\LoggerInterface;\n+use Illuminate\\Log\\LogManager;\n use Illuminate\\Support\\Manager;\n use GuzzleHttp\\Client as HttpClient;\n use Swift_SmtpTransport as SmtpTransport;\n@@ -160,11 +161,13 @@ protected function createSparkPostDriver()\n */\n protected function createLogDriver()\n {\n- $channel = $this->app['config']['mail.log_channel'];\n+ $logger = $this->app->make(LoggerInterface::class);\n \n- return new LogTransport(\n- $this->app->make(LoggerInterface::class)->channel($channel)\n- );\n+ if ($logger instanceof LogManager) {\n+ $logger = $logger->channel($this->app['config']['mail.log_channel']);\n+ }\n+\n+ return new LogTransport($logger);\n }\n \n /**", "filename": "src/Illuminate/Mail/TransportManager.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7\r\n- PHP Version: 7.2\r\n\r\n### Description:\r\n\r\nClass `Repository` implements the [`set` method](https://github.com/laravel/framework/blob/5.7/src/Illuminate/Cache/Repository.php#L217) whose contract is defined in [`Psr\\SimpleCache\\CacheInterface`](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md#21-cacheinterface). By the contract, return value should be a boolean (true on success and false on failure). Yet, the implementation in the [Repository](https://github.com/laravel/framework/blob/5.7/src/Illuminate/Cache/Repository.php#L217) does not return any value.\r\n\r\nNormally, this doesn't cause any problems in Laravel, but it does when using Laravel's cache repository as a dependency in third-party libraries. To illustrate the problem, take a look at the following \r\ncode excerpt (part of the `Manager` class) from [jeremykendall/php-domain-parser](https://github.com/jeremykendall/php-domain-parser) package:\r\n\r\n```php\r\n/**\r\n * Returns true if the refresh was successful\r\n * @param string $url the Public Suffix List URL\r\n * @param null|mixed $ttl the cache TTL\r\n * @return bool\r\n */\r\npublic function refreshRules(string $url = self::PSL_URL, $ttl = null): bool\r\n{\r\n static $converter;\r\n $converter = $converter ?? new Converter();\r\n $data = json_encode($converter->convert($this->http->getContent($url)));\r\n\r\n return $this->cache->set($this->getCacheKey('PSL', $url), $data, $this->filterTtl($ttl) ?? $this->ttl);\r\n}\r\n```\r\nInjecting Laravel's SimpleCache implementation to the `Manager` class, and calling this method results in a type error because the `set` method's return value is always void, when the expected value is a boolean.\r\n\r\nI've checked all the implemented cache stores in Laravel and all of them have the ability to return a success status as a boolean:\r\n- `ApcStore`: uses https://secure.php.net/manual/en/function.apcu-store.php which returns a bool.\r\n- `ArrayStore`: can just return true.\r\n- `DatabaseStore`: uses https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Query/Builder.php#L2542 which returns a bool.\r\n- `FileStore`: uses http://php.net/manual/en/function.file-put-contents.php which returns int on success or false on failure.\r\n- `MemcachedStore`: uses http://php.net/manual/en/memcached.set.php which returns a bool.\r\n- `RedisStore`: uses https://redis.io/commands/setex which returns string \"OK\" on success.\r\n\r\nIgnoring the fact that these return values don't give enough info about the nature of failures when they occur, is there another reason why a return value for methods `set`, `put`, `setMultiple`, `forever` is not a boolean?", "comments": [ { "body": "@driesvints , can we close this, since https://github.com/laravel/framework/pull/26726 is merged? ", "created_at": "2018-12-08T11:31:16Z" }, { "body": "Looks like, that is fixed in https://github.com/laravel/framework/pull/26726", "created_at": "2018-12-08T21:01:20Z" } ], "number": 26674, "title": "Method `set` in cache repository does not honor the PSR-16 SimpleCache contract" }
{ "body": "This is a copy of the original PR #26700 that now targets the `master` branch. The aim is to solve issue #26674 by making the cache component fully compliant with the PSR-16 `SimpleCache` interface.\r\n\r\nCache stores Apc, Array, Database, File, Memcached, Null, and Redis, as well as the Repository class and contract are affected. Their respective unit tests were updated to check for return values.", "number": 26726, "review_comments": [], "title": "[5.8] Honor PSR-16 SimpleCache interface" }
{ "commits": [ { "message": "Honor PSR-16 SimpleCache interface\n\nMethods `put`, `set`, `putMany`, `setMultiple`, and `forever` now return boolean values.\n\nFixes issue laravel/framework#26674" }, { "message": "Fix return type in Cache contract" }, { "message": "Fix array database store return checks" }, { "message": "Fire KeyWritten event only on success" }, { "message": "Style CI fix" }, { "message": "Fire KeyWritten event on forever success" } ], "files": [ { "diff": "@@ -54,11 +54,11 @@ public function get($key)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n- $this->apc->put($this->prefix.$key, $value, (int) ($minutes * 60));\n+ return $this->apc->put($this->prefix.$key, $value, (int) ($minutes * 60));\n }\n \n /**\n@@ -90,11 +90,11 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->put($key, $value, 0);\n+ return $this->put($key, $value, 0);\n }\n \n /**", "filename": "src/Illuminate/Cache/ApcStore.php", "status": "modified" }, { "diff": "@@ -30,11 +30,13 @@ public function get($key)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n $this->storage[$key] = $value;\n+\n+ return true;\n }\n \n /**\n@@ -69,11 +71,11 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->put($key, $value, 0);\n+ return $this->put($key, $value, 0);\n }\n \n /**", "filename": "src/Illuminate/Cache/ArrayStore.php", "status": "modified" }, { "diff": "@@ -89,7 +89,7 @@ public function get($key)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n@@ -100,9 +100,11 @@ public function put($key, $value, $minutes)\n $expiration = $this->getTime() + (int) ($minutes * 60);\n \n try {\n- $this->table()->insert(compact('key', 'value', 'expiration'));\n+ return $this->table()->insert(compact('key', 'value', 'expiration'));\n } catch (Exception $e) {\n- $this->table()->where('key', $key)->update(compact('value', 'expiration'));\n+ $result = $this->table()->where('key', $key)->update(compact('value', 'expiration'));\n+\n+ return $result > 0;\n }\n }\n \n@@ -196,11 +198,11 @@ protected function getTime()\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->put($key, $value, 5256000);\n+ return $this->put($key, $value, 5256000);\n }\n \n /**", "filename": "src/Illuminate/Cache/DatabaseStore.php", "status": "modified" }, { "diff": "@@ -55,15 +55,17 @@ public function get($key)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n $this->ensureCacheDirectoryExists($path = $this->path($key));\n \n- $this->files->put(\n+ $result = $this->files->put(\n $path, $this->expiration($minutes).serialize($value), true\n );\n+\n+ return $result !== false && $result > 0;\n }\n \n /**\n@@ -112,11 +114,11 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->put($key, $value, 0);\n+ return $this->put($key, $value, 0);\n }\n \n /**", "filename": "src/Illuminate/Cache/FileStore.php", "status": "modified" }, { "diff": "@@ -105,11 +105,11 @@ public function many(array $keys)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n- $this->memcached->set(\n+ return $this->memcached->set(\n $this->prefix.$key, $value, $this->calculateExpiration($minutes)\n );\n }\n@@ -119,7 +119,7 @@ public function put($key, $value, $minutes)\n *\n * @param array $values\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function putMany(array $values, $minutes)\n {\n@@ -129,7 +129,7 @@ public function putMany(array $values, $minutes)\n $prefixedValues[$this->prefix.$key] = $value;\n }\n \n- $this->memcached->setMulti(\n+ return $this->memcached->setMulti(\n $prefixedValues, $this->calculateExpiration($minutes)\n );\n }\n@@ -178,11 +178,11 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->put($key, $value, 0);\n+ return $this->put($key, $value, 0);\n }\n \n /**", "filename": "src/Illuminate/Cache/MemcachedStore.php", "status": "modified" }, { "diff": "@@ -21,7 +21,7 @@ class NullStore extends TaggableStore\n */\n public function get($key)\n {\n- //\n+ return null;\n }\n \n /**\n@@ -30,11 +30,11 @@ public function get($key)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n- //\n+ return false;\n }\n \n /**\n@@ -66,22 +66,22 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- //\n+ return false;\n }\n \n /**\n * Remove an item from the cache.\n *\n * @param string $key\n- * @return void\n+ * @return bool\n */\n public function forget($key)\n {\n- //\n+ return true;\n }\n \n /**", "filename": "src/Illuminate/Cache/NullStore.php", "status": "modified" }, { "diff": "@@ -85,31 +85,37 @@ public function many(array $keys)\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes)\n {\n- $this->connection()->setex(\n+ $result = $this->connection()->setex(\n $this->prefix.$key, (int) max(1, $minutes * 60), $this->serialize($value)\n );\n+\n+ return $result ? true : false;\n }\n \n /**\n * Store multiple items in the cache for a given number of minutes.\n *\n * @param array $values\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function putMany(array $values, $minutes)\n {\n $this->connection()->multi();\n \n+ $resultMany = null;\n foreach ($values as $key => $value) {\n- $this->put($key, $value, $minutes);\n+ $result = $this->put($key, $value, $minutes);\n+ $resultMany = is_null($resultMany) ? $result : $result && $resultMany;\n }\n \n $this->connection()->exec();\n+\n+ return $resultMany ?: false;\n }\n \n /**\n@@ -158,11 +164,13 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->connection()->set($this->prefix.$key, $this->serialize($value));\n+ $result = $this->connection()->set($this->prefix.$key, $this->serialize($value));\n+\n+ return $result ? true : false;\n }\n \n /**", "filename": "src/Illuminate/Cache/RedisStore.php", "status": "modified" }, { "diff": "@@ -23,13 +23,13 @@ class RedisTaggedCache extends TaggedCache\n * @param string $key\n * @param mixed $value\n * @param \\DateTime|float|int|null $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes = null)\n {\n $this->pushStandardKeys($this->tags->getNamespace(), $key);\n \n- parent::put($key, $value, $minutes);\n+ return parent::put($key, $value, $minutes);\n }\n \n /**\n@@ -65,13 +65,13 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n $this->pushForeverKeys($this->tags->getNamespace(), $key);\n \n- parent::forever($key, $value);\n+ return parent::forever($key, $value);\n }\n \n /**", "filename": "src/Illuminate/Cache/RedisTaggedCache.php", "status": "modified" }, { "diff": "@@ -194,55 +194,67 @@ public function pull($key, $default = null)\n * @param string $key\n * @param mixed $value\n * @param \\DateTimeInterface|\\DateInterval|float|int|null $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes = null)\n {\n if (is_array($key)) {\n- $this->putMany($key, $value);\n+ $result = $this->putMany($key, $value);\n \n- return;\n+ return $result;\n }\n \n if (! is_null($minutes = $this->getMinutes($minutes))) {\n- $this->store->put($this->itemKey($key), $value, $minutes);\n+ $result = $this->store->put($this->itemKey($key), $value, $minutes);\n+\n+ if ($result) {\n+ $this->event(new KeyWritten($key, $value, $minutes));\n+ }\n \n- $this->event(new KeyWritten($key, $value, $minutes));\n+ return $result;\n }\n+\n+ return false;\n }\n \n /**\n * {@inheritdoc}\n */\n public function set($key, $value, $ttl = null)\n {\n- $this->put($key, $value, $ttl);\n+ return $this->put($key, $value, $ttl);\n }\n \n /**\n * Store multiple items in the cache for a given number of minutes.\n *\n * @param array $values\n * @param \\DateTimeInterface|\\DateInterval|float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function putMany(array $values, $minutes)\n {\n if (! is_null($minutes = $this->getMinutes($minutes))) {\n- $this->store->putMany($values, $minutes);\n+ $result = $this->store->putMany($values, $minutes);\n \n- foreach ($values as $key => $value) {\n- $this->event(new KeyWritten($key, $value, $minutes));\n+ if ($result) {\n+ foreach ($values as $key => $value) {\n+ $this->event(new KeyWritten($key, $value, $minutes));\n+ }\n }\n+\n+ return $result;\n }\n+\n+ return false;\n }\n \n /**\n * {@inheritdoc}\n */\n public function setMultiple($values, $ttl = null)\n {\n- $this->putMany($values, $ttl);\n+ return $this->putMany($values, $ttl);\n }\n \n /**\n@@ -309,13 +321,17 @@ public function decrement($key, $value = 1)\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value)\n {\n- $this->store->forever($this->itemKey($key), $value);\n+ $result = $this->store->forever($this->itemKey($key), $value);\n+\n+ if ($result) {\n+ $this->event(new KeyWritten($key, $value, 0));\n+ }\n \n- $this->event(new KeyWritten($key, $value, 0));\n+ return $result;\n }\n \n /**", "filename": "src/Illuminate/Cache/Repository.php", "status": "modified" }, { "diff": "@@ -28,12 +28,16 @@ public function many(array $keys)\n *\n * @param array $values\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function putMany(array $values, $minutes)\n {\n+ $resultMany = null;\n foreach ($values as $key => $value) {\n- $this->put($key, $value, $minutes);\n+ $result = $this->put($key, $value, $minutes);\n+ $resultMany = is_null($resultMany) ? $result : $result && $resultMany;\n }\n+\n+ return $resultMany ?: false;\n }\n }", "filename": "src/Illuminate/Cache/RetrievesMultipleKeys.php", "status": "modified" }, { "diff": "@@ -39,7 +39,7 @@ public function pull($key, $default = null);\n * @param string $key\n * @param mixed $value\n * @param \\DateTimeInterface|\\DateInterval|float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes);\n \n@@ -76,7 +76,7 @@ public function decrement($key, $value = 1);\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value);\n ", "filename": "src/Illuminate/Contracts/Cache/Repository.php", "status": "modified" }, { "diff": "@@ -28,7 +28,7 @@ public function many(array $keys);\n * @param string $key\n * @param mixed $value\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function put($key, $value, $minutes);\n \n@@ -37,7 +37,7 @@ public function put($key, $value, $minutes);\n *\n * @param array $values\n * @param float|int $minutes\n- * @return void\n+ * @return bool\n */\n public function putMany(array $values, $minutes);\n \n@@ -64,7 +64,7 @@ public function decrement($key, $value = 1);\n *\n * @param string $key\n * @param mixed $value\n- * @return void\n+ * @return bool\n */\n public function forever($key, $value);\n ", "filename": "src/Illuminate/Contracts/Cache/Store.php", "status": "modified" }, { "diff": "@@ -115,7 +115,7 @@ public function hash($path)\n * @param string $path\n * @param string $contents\n * @param bool $lock\n- * @return int\n+ * @return int|bool\n */\n public function put($path, $contents, $lock = false)\n {", "filename": "src/Illuminate/Filesystem/Filesystem.php", "status": "modified" }, { "diff": "@@ -43,9 +43,12 @@ public function testGetMultipleReturnsNullWhenNotFoundAndValueWhenFound()\n public function testSetMethodProperlyCallsAPC()\n {\n $apc = $this->getMockBuilder(ApcWrapper::class)->setMethods(['put'])->getMock();\n- $apc->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(60));\n+ $apc->expects($this->once())\n+ ->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(60))\n+ ->willReturn(true);\n $store = new ApcStore($apc);\n- $store->put('foo', 'bar', 1);\n+ $result = $store->put('foo', 'bar', 1);\n+ $this->assertTrue($result);\n }\n \n public function testSetMultipleMethodProperlyCallsAPC()\n@@ -57,13 +60,14 @@ public function testSetMultipleMethodProperlyCallsAPC()\n $this->equalTo('baz'), $this->equalTo('qux'), $this->equalTo(60),\n ], [\n $this->equalTo('bar'), $this->equalTo('norf'), $this->equalTo(60),\n- ]);\n+ ])->willReturn(true);\n $store = new ApcStore($apc);\n- $store->putMany([\n+ $result = $store->putMany([\n 'foo' => 'bar',\n 'baz' => 'qux',\n 'bar' => 'norf',\n ], 1);\n+ $this->assertTrue($result);\n }\n \n public function testIncrementMethodProperlyCallsAPC()\n@@ -85,17 +89,21 @@ public function testDecrementMethodProperlyCallsAPC()\n public function testStoreItemForeverProperlyCallsAPC()\n {\n $apc = $this->getMockBuilder(ApcWrapper::class)->setMethods(['put'])->getMock();\n- $apc->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0));\n+ $apc->expects($this->once())\n+ ->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0))\n+ ->willReturn(true);\n $store = new ApcStore($apc);\n- $store->forever('foo', 'bar');\n+ $result = $store->forever('foo', 'bar');\n+ $this->assertTrue($result);\n }\n \n public function testForgetMethodProperlyCallsAPC()\n {\n $apc = $this->getMockBuilder(ApcWrapper::class)->setMethods(['delete'])->getMock();\n- $apc->expects($this->once())->method('delete')->with($this->equalTo('foo'));\n+ $apc->expects($this->once())->method('delete')->with($this->equalTo('foo'))->willReturn(true);\n $store = new ApcStore($apc);\n- $store->forget('foo');\n+ $result = $store->forget('foo');\n+ $this->assertTrue($result);\n }\n \n public function testFlushesCached()", "filename": "tests/Cache/CacheApcStoreTest.php", "status": "modified" }, { "diff": "@@ -10,18 +10,21 @@ class CacheArrayStoreTest extends TestCase\n public function testItemsCanBeSetAndRetrieved()\n {\n $store = new ArrayStore;\n- $store->put('foo', 'bar', 10);\n+ $result = $store->put('foo', 'bar', 10);\n+ $this->assertTrue($result);\n $this->assertEquals('bar', $store->get('foo'));\n }\n \n public function testMultipleItemsCanBeSetAndRetrieved()\n {\n $store = new ArrayStore;\n- $store->put('foo', 'bar', 10);\n- $store->putMany([\n+ $result = $store->put('foo', 'bar', 10);\n+ $resultMany = $store->putMany([\n 'fizz' => 'buz',\n 'quz' => 'baz',\n ], 10);\n+ $this->assertTrue($result);\n+ $this->assertTrue($resultMany);\n $this->assertEquals([\n 'foo' => 'bar',\n 'fizz' => 'buz',\n@@ -33,8 +36,11 @@ public function testMultipleItemsCanBeSetAndRetrieved()\n public function testStoreItemForeverProperlyStoresInArray()\n {\n $mock = $this->getMockBuilder(ArrayStore::class)->setMethods(['put'])->getMock();\n- $mock->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0));\n- $mock->forever('foo', 'bar');\n+ $mock->expects($this->once())\n+ ->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0))\n+ ->willReturn(true);\n+ $result = $mock->forever('foo', 'bar');\n+ $this->assertTrue($result);\n }\n \n public function testValuesCanBeIncremented()", "filename": "tests/Cache/CacheArrayStoreTest.php", "status": "modified" }, { "diff": "@@ -69,9 +69,10 @@ public function testValueIsInsertedWhenNoExceptionsAreThrown()\n $table = m::mock(stdClass::class);\n $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);\n $store->expects($this->once())->method('getTime')->will($this->returnValue(1));\n- $table->shouldReceive('insert')->once()->with(['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]);\n+ $table->shouldReceive('insert')->once()->with(['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61])->andReturnTrue();\n \n- $store->put('foo', 'bar', 1);\n+ $result = $store->put('foo', 'bar', 1);\n+ $this->assertTrue($result);\n }\n \n public function testValueIsUpdatedWhenInsertThrowsException()\n@@ -84,9 +85,10 @@ public function testValueIsUpdatedWhenInsertThrowsException()\n throw new Exception;\n });\n $table->shouldReceive('where')->once()->with('key', 'prefixfoo')->andReturn($table);\n- $table->shouldReceive('update')->once()->with(['value' => serialize('bar'), 'expiration' => 61]);\n+ $table->shouldReceive('update')->once()->with(['value' => serialize('bar'), 'expiration' => 61])->andReturnTrue();\n \n- $store->put('foo', 'bar', 1);\n+ $result = $store->put('foo', 'bar', 1);\n+ $this->assertTrue($result);\n }\n \n public function testValueIsInsertedOnPostgres()\n@@ -95,16 +97,18 @@ public function testValueIsInsertedOnPostgres()\n $table = m::mock(stdClass::class);\n $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);\n $store->expects($this->once())->method('getTime')->will($this->returnValue(1));\n- $table->shouldReceive('insert')->once()->with(['key' => 'prefixfoo', 'value' => base64_encode(serialize(\"\\0\")), 'expiration' => 61]);\n+ $table->shouldReceive('insert')->once()->with(['key' => 'prefixfoo', 'value' => base64_encode(serialize(\"\\0\")), 'expiration' => 61])->andReturnTrue();\n \n- $store->put('foo', \"\\0\", 1);\n+ $result = $store->put('foo', \"\\0\", 1);\n+ $this->assertTrue($result);\n }\n \n public function testForeverCallsStoreItemWithReallyLongTime()\n {\n $store = $this->getMockBuilder(DatabaseStore::class)->setMethods(['put'])->setConstructorArgs($this->getMocks())->getMock();\n- $store->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(5256000));\n- $store->forever('foo', 'bar');\n+ $store->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(5256000))->willReturn(true);\n+ $result = $store->forever('foo', 'bar');\n+ $this->assertTrue($result);\n }\n \n public function testItemsMayBeRemovedFromCache()", "filename": "tests/Cache/CacheDatabaseStoreTest.php", "status": "modified" }, { "diff": "@@ -37,11 +37,13 @@ public function testPutCreatesMissingDirectories()\n {\n $files = $this->mockFilesystem();\n $hash = sha1('foo');\n+ $contents = '0000000000';\n $full_dir = __DIR__.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2);\n $files->expects($this->once())->method('makeDirectory')->with($this->equalTo($full_dir), $this->equalTo(0777), $this->equalTo(true));\n- $files->expects($this->once())->method('put')->with($this->equalTo($full_dir.'/'.$hash));\n+ $files->expects($this->once())->method('put')->with($this->equalTo($full_dir.'/'.$hash))->willReturn(strlen($contents));\n $store = new FileStore($files, __DIR__);\n- $store->put('foo', '0000000000', 0);\n+ $result = $store->put('foo', $contents, 0);\n+ $this->assertTrue($result);\n }\n \n public function testExpiredItemsReturnNull()\n@@ -72,8 +74,9 @@ public function testStoreItemProperlyStoresValues()\n $contents = '1111111111'.serialize('Hello World');\n $hash = sha1('foo');\n $cache_dir = substr($hash, 0, 2).'/'.substr($hash, 2, 2);\n- $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash), $this->equalTo($contents));\n- $store->put('foo', 'Hello World', 10);\n+ $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash), $this->equalTo($contents))->willReturn(strlen($contents));\n+ $result = $store->put('foo', 'Hello World', 10);\n+ $this->assertTrue($result);\n }\n \n public function testForeversAreStoredWithHighTimestamp()\n@@ -82,9 +85,10 @@ public function testForeversAreStoredWithHighTimestamp()\n $contents = '9999999999'.serialize('Hello World');\n $hash = sha1('foo');\n $cache_dir = substr($hash, 0, 2).'/'.substr($hash, 2, 2);\n- $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash), $this->equalTo($contents));\n+ $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash), $this->equalTo($contents))->willReturn(strlen($contents));\n $store = new FileStore($files, __DIR__);\n- $store->forever('foo', 'Hello World', 10);\n+ $result = $store->forever('foo', 'Hello World', 10);\n+ $this->assertTrue($result);\n }\n \n public function testForeversAreNotRemovedOnIncrement()", "filename": "tests/Cache/CacheFileStoreTest.php", "status": "modified" }, { "diff": "@@ -67,9 +67,10 @@ public function testSetMethodProperlyCallsMemcache()\n \n Carbon::setTestNow($now = Carbon::now());\n $memcache = $this->getMockBuilder(Memcached::class)->setMethods(['set'])->getMock();\n- $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo($now->timestamp + 60));\n+ $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo($now->timestamp + 60))->willReturn(true);\n $store = new MemcachedStore($memcache);\n- $store->put('foo', 'bar', 1);\n+ $result = $store->put('foo', 'bar', 1);\n+ $this->assertTrue($result);\n Carbon::setTestNow();\n }\n \n@@ -104,9 +105,10 @@ public function testStoreItemForeverProperlyCallsMemcached()\n }\n \n $memcache = $this->getMockBuilder(Memcached::class)->setMethods(['set'])->getMock();\n- $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0));\n+ $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0))->willReturn(true);\n $store = new MemcachedStore($memcache);\n- $store->forever('foo', 'bar');\n+ $result = $store->forever('foo', 'bar');\n+ $this->assertTrue($result);\n }\n \n public function testForgetMethodProperlyCallsMemcache()", "filename": "tests/Cache/CacheMemcachedStoreTest.php", "status": "modified" }, { "diff": "@@ -62,8 +62,9 @@ public function testSetMethodProperlyCallsRedis()\n {\n $redis = $this->getRedis();\n $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n- $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, serialize('foo'));\n- $redis->put('foo', 'foo', 60);\n+ $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, serialize('foo'))->andReturn('OK');\n+ $result = $redis->put('foo', 'foo', 60);\n+ $this->assertTrue($result);\n }\n \n public function testSetMultipleMethodProperlyCallsRedis()\n@@ -73,24 +74,26 @@ public function testSetMultipleMethodProperlyCallsRedis()\n $connection = $redis->getRedis();\n $connection->shouldReceive('connection')->with('default')->andReturn($redis->getRedis());\n $connection->shouldReceive('multi')->once();\n- $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, serialize('bar'));\n- $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:baz', 60 * 60, serialize('qux'));\n- $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:bar', 60 * 60, serialize('norf'));\n+ $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, serialize('bar'))->andReturn('OK');\n+ $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:baz', 60 * 60, serialize('qux'))->andReturn('OK');\n+ $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:bar', 60 * 60, serialize('norf'))->andReturn('OK');\n $connection->shouldReceive('exec')->once();\n \n- $redis->putMany([\n+ $result = $redis->putMany([\n 'foo' => 'bar',\n 'baz' => 'qux',\n 'bar' => 'norf',\n ], 60);\n+ $this->assertTrue($result);\n }\n \n public function testSetMethodProperlyCallsRedisForNumerics()\n {\n $redis = $this->getRedis();\n $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, 1);\n- $redis->put('foo', 1, 60);\n+ $result = $redis->put('foo', 1, 60);\n+ $this->assertFalse($result);\n }\n \n public function testIncrementMethodProperlyCallsRedis()\n@@ -113,8 +116,9 @@ public function testStoreItemForeverProperlyCallsRedis()\n {\n $redis = $this->getRedis();\n $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n- $redis->getRedis()->shouldReceive('set')->once()->with('prefix:foo', serialize('foo'));\n- $redis->forever('foo', 'foo', 60);\n+ $redis->getRedis()->shouldReceive('set')->once()->with('prefix:foo', serialize('foo'))->andReturn('OK');\n+ $result = $redis->forever('foo', 'foo', 60);\n+ $this->assertTrue($result);\n }\n \n public function testForgetMethodProperlyCallsRedis()", "filename": "tests/Cache/CacheRedisStoreTest.php", "status": "modified" }, { "diff": "@@ -132,16 +132,19 @@ public function testSettingMultipleItemsInCache()\n {\n // Alias of PuttingMultiple\n $repo = $this->getRepository();\n- $repo->getStore()->shouldReceive('putMany')->once()->with(['foo' => 'bar', 'bar' => 'baz'], 1);\n- $repo->setMultiple(['foo' => 'bar', 'bar' => 'baz'], 1);\n+ $repo->getStore()->shouldReceive('putMany')->once()->with(['foo' => 'bar', 'bar' => 'baz'], 1)->andReturn(true);\n+ $result = $repo->setMultiple(['foo' => 'bar', 'bar' => 'baz'], 1);\n+ $this->assertTrue($result);\n }\n \n public function testPutWithDatetimeInPastOrZeroSecondsDoesntSaveItem()\n {\n $repo = $this->getRepository();\n $repo->getStore()->shouldReceive('put')->never();\n- $repo->put('foo', 'bar', Carbon::now()->subMinutes(10));\n- $repo->put('foo', 'bar', Carbon::now());\n+ $result = $repo->put('foo', 'bar', Carbon::now()->subMinutes(10));\n+ $this->assertFalse($result);\n+ $result = $repo->put('foo', 'bar', Carbon::now());\n+ $this->assertFalse($result);\n }\n \n public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately()\n@@ -215,8 +218,9 @@ public function testRemovingCacheKey()\n public function testSettingCache()\n {\n $repo = $this->getRepository();\n- $repo->getStore()->shouldReceive('put')->with($key = 'foo', $value = 'bar', 1);\n- $repo->set($key, $value, 1);\n+ $repo->getStore()->shouldReceive('put')->with($key = 'foo', $value = 'bar', 1)->andReturn(true);\n+ $result = $repo->set($key, $value, 1);\n+ $this->assertTrue($result);\n }\n \n public function testClearingWholeCache()", "filename": "tests/Cache/CacheRepositoryTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.0\r\n- PHP Version: 7.2.4\r\n- Database Driver & Version: MySQL\r\n\r\n### Description:\r\n\r\nUsing PhpRedis driver for Redis and attempting to use getMultiple(), I get the following error: Argument 1 passed to Redis::mget() must be of the type array, string given.\r\n\r\n### Steps To Reproduce:\r\n\r\nHereby, my Redis config for Laravel:\r\n\r\n```\r\n'redis' => [\r\n\r\n 'client' => 'phpredis',\r\n\r\n 'default' => [\r\n 'host' => env('REDIS_HOST'),\r\n 'password' => env('REDIS_PASSWORD', null),\r\n 'port' => env('REDIS_PORT', 6379),\r\n 'database' => 0,\r\n ],\r\n\r\n ],\r\n```\r\nReproduce: setup Redis, setup Laravel to connect to it using PhpRedis, then:\r\n\r\n```\r\napp()->make(\\Illuminate\\Contracts\\Cache\\Repository::class)->getMultiple([\"key1\", \"key2\"]);\r\n```\r\n\r\nThis did not happen with Laravel 5.6, so this is a regression.", "comments": [ { "body": "PR was merged", "created_at": "2018-12-03T14:36:45Z" } ], "number": 26709, "title": "PhpRedisConnection::getMultiple() throws a TypeError" }
{ "body": "Fixes #26709 . Unfortunately, I could not find a unit test for PhpRedisConnection, and I was not as brave as to introduce a way to test against a Redis connection for the framework, which, apparently, should be the right way to test this kind of changes.", "number": 26710, "review_comments": [], "title": "[5.7] Fix Redis::mget() call, arg should be an array" }
{ "commits": [ { "message": "Fix Redis::mget() call, arg should be an array" } ], "files": [ { "diff": "@@ -45,7 +45,7 @@ public function mget(array $keys)\n {\n return array_map(function ($value) {\n return $value !== false ? $value : null;\n- }, $this->command('mget', $keys));\n+ }, $this->command('mget', [$keys]));\n }\n \n /**", "filename": "src/Illuminate/Redis/Connections/PhpRedisConnection.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": "- Laravel Version: 5.7.13\r\n- PHP Version: 7.1\r\n- Database Driver & Version: Mysql 5.6\r\n\r\n### Description:\r\n\r\nJobs table (created via `php artisan queue:table`) don't have any default value for `reserved` column. When working with mysql in strict mode, mysql needs defined values for all fields that have no default value on db schema.\r\n\r\nThen, we have two options: add a default value on migration or fix `DatabaseQueue::pushToDatabase()`.\r\n\r\nThis fix solve the problem adding attribute to `DatabaseQueue::buildDatabaseRecord()`.\r\n\r\n### Error Log\r\n```\r\nERROR: SQLSTATE[HY000]: General error: 1364 Field 'reserved' doesn't have a default value (SQL: insert into `jobs` (`queue`, `attempts`, `reserved_at`, `available_at`, `created_at`, `payload`) values (default, 0, , 1543435133, 1543435133, some_payload)) at /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, Doctrine\\\\DBAL\\\\Driver\\\\PDOException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'reserved' doesn't have a default value at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:143, PDOException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'reserved' doesn't have a default value at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:141)\r\n[stacktrace]\r\n#0 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(624): Illuminate\\\\Database\\\\Connection->runQueryCallback('insert into `jo...', Array, Object(Closure))\r\n#1 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(459): Illuminate\\\\Database\\\\Connection->run('insert into `jo...', Array, Object(Closure))\r\n#2 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(411): Illuminate\\\\Database\\\\Connection->statement('insert into `jo...', Array)\r\n#3 /app/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php(32): Illuminate\\\\Database\\\\Connection->insert('insert into `jo...', Array)\r\n#4 /app/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2349): Illuminate\\\\Database\\\\Query\\\\Processors\\\\Processor->processInsertGetId(Object(Illuminate\\\\Database\\\\Query\\\\Builder), 'insert into `jo...', Array, NULL)\r\n#5 /app/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php(157): Illuminate\\\\Database\\\\Query\\\\Builder->insertGetId(Array)\r\n#6 /app/vendor/laravel/framework/src/Illuminate/Queue/DatabaseQueue.php(81): Illuminate\\\\Queue\\\\DatabaseQueue->pushToDatabase(NULL, '{\\\"displayName\\\":...')\r\n#7 /app/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(184): Illuminate\\\\Queue\\\\DatabaseQueue->push(Object(App\\\\SomeJob))\r\n#8 /app/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(160): Illuminate\\\\Bus\\\\Dispatcher->pushCommandToQueue(Object(Illuminate\\\\Queue\\\\DatabaseQueue), Object(App\\\\SomeJob))\r\n#9 /app/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(73): Illuminate\\\\Bus\\\\Dispatcher->dispatchToQueue(Object(App\\\\SomeJob))\r\n#10 /app/vendor/laravel/framework/src/Illuminate/Foundation/Bus/PendingDispatch.php(112): Illuminate\\\\Bus\\\\Dispatcher->dispatch(Object(App\\\\SomeJob))\r\n#11 /app/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(392): Illuminate\\\\Foundation\\\\Bus\\\\PendingDispatch->__destruct()\r\n#12 /app/app/SomeObserver.php(29): dispatch(Object(App\\\\SomeJob))\r\n```", "number": 26656, "review_comments": [], "title": "[5.7] 🐛 Bug Fix: Jobs queue fails when mysql connection is in strict mode" }
{ "commits": [ { "message": "Merge pull request #1 from laravel/master\n\nMaster" }, { "message": "jobs has a default value now. fix problem when mysql works with strict mode. QueueDatabaseQueueUnitTest fixed" } ], "files": [ { "diff": "@@ -176,6 +176,7 @@ protected function buildDatabaseRecord($queue, $payload, $availableAt, $attempts\n return [\n 'queue' => $queue,\n 'attempts' => $attempts,\n+ 'reserved' => false,\n 'reserved_at' => null,\n 'available_at' => $availableAt,\n 'created_at' => $this->currentTime(),", "filename": "src/Illuminate/Queue/DatabaseQueue.php", "status": "modified" }, { "diff": "@@ -98,13 +98,15 @@ public function testBulkBatchPushesOntoDatabase()\n 'queue' => 'queue',\n 'payload' => json_encode(['displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'timeout' => null, 'data' => ['data']]),\n 'attempts' => 0,\n+ 'reserved' => false,\n 'reserved_at' => null,\n 'available_at' => 'available',\n 'created_at' => 'created',\n ], [\n 'queue' => 'queue',\n 'payload' => json_encode(['displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'timeout' => null, 'data' => ['data']]),\n 'attempts' => 0,\n+ 'reserved' => false,\n 'reserved_at' => null,\n 'available_at' => 'available',\n 'created_at' => 'created',", "filename": "tests/Queue/QueueDatabaseQueueUnitTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.9\r\n- PHP Version: 7.1.19\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n\r\nWhen using the cache locks its possible to delete another client's lock. If this happens the lock is free and can be acquired again, even though it has not expired yet. It is easy for this to happen if a client takes longer than it expects to finish a task and overruns the expiration, i.e.\r\n\r\n- Client A acquires lock `foo` with a 10 second expiration\r\n- Client A begins performing a task\r\n- Client A takes longer than expected and the lock is automatically released by the expiration\r\n- Client B acquires the lock\r\n- Client A finishes it's task and attempts to release the lock, **deleting client B's lock**\r\n- Client C is now able to acquire the lock\r\n\r\nThis issue is especially difficult to diagnose because the lock will not throw an exception if the timeout has been exceeded when `release` is called.\r\n\r\nWe can't do anything about client A exceeding it's expiration time but we can prevent client A from deleting client B's lock. The redis docs [recommend setting a random token](https://redis.io/commands/set#patterns) instead of the value `1`. You can then confirm the token is what you set and only delete the key if the token matches.\r\n\r\nThe reproduction steps below use Redis but this issue seems to exist with both the Redis and Memcached locks.\r\n\r\n### Steps To Reproduce:\r\n\r\nI've added a failing test case here: https://github.com/yuloh/framework/commit/a0acbfd60cb276d9c99091a7a56432b815993a92. In the test `$firstLock->release();` should do nothing, as the lock has already been released. Instead it releases `$secondLock`.", "comments": [ { "body": "Heya @yuloh. This should indeed be addressed I believe. Would be great if anyone could assist with this.", "created_at": "2018-11-09T15:34:12Z" }, { "body": "Great catch @yuloh , I opened a PR fixing this using the approach you posted.", "created_at": "2018-11-28T00:29:24Z" }, { "body": "Discussion can continue at #26645. :)", "created_at": "2019-01-03T19:02:21Z" }, { "body": "@GrahamCampbell please leave this open until the fix has been implemented.", "created_at": "2019-01-04T10:38:34Z" }, { "body": "The PR was merged and will be released once 5.8 is out.", "created_at": "2019-01-15T15:47:03Z" } ], "number": 26213, "title": "Cache locks are unsafe" }
{ "body": "Resolves: #26213 \r\n\r\nBefore this change out of order releases of the same cache lock could lead to situation where client A acquired the lock, took longer than the timeout, which made client B successfully acquire the lock. If A now finishes while B is still holding the lock A will release the lock that does not belong to it any more.\r\n\r\nThis fix introduces a unique value that is written as the cache value to stop A from deleting B's lock.\r\n\r\nExample from the original issue:\r\n> * Client A acquires lock `foo` with a 10 second expiration\r\n> * Client A begins performing a task\r\n> * Client A takes longer than expected and the lock is automatically released by the expiration\r\n> * Client B acquires the lock\r\n> * Client A finishes it's task and attempts to release the lock, **deleting client B's lock**\r\n> * Client C is now able to acquire the lock\r\n\r\nThis change does not break the existing API as it introduces the `scoped($scope)` function, plus a sugar function `safe()` that generates a random `$scope` using the `uniqid()` function.\r\n\r\nThis is most likely something that should be default for 5.8 (I will create a follow up PR after this one is merged) as it makes Cache locking much more robust. For 5.7 the opt-in is important as it could otherwise disrupt already existing locks in production deployments.\r\n\r\nHappy to discuss the API of this :-)", "number": 26645, "review_comments": [ { "body": "Since `uniqid` is based on the current time and concurrent requests are likely to attempt to acquire the lock at the same time this seems like it may cause collisions. Using `Str::random(20)` instead would significantly reduce the chance of a collision.", "created_at": "2018-11-28T15:26:33Z" }, { "body": "Since `$scope` is typehinted as a string it shouldn't be necessary to serialize/unserialize.", "created_at": "2018-11-28T15:27:31Z" }, { "body": "There is a race condition here. It's possible for `canRelease` to return true, the lock to then be released because it was expired, and another client to acquire the lock before `del` is called. If that happens you will delete the other clients lock instead of your own.\r\n\r\nWith Redis you can use a Lua script to perform an atomic operation. Since scripts are blocking no other client can acquire the lock between the check and the delete.\r\n\r\n```lua\r\nif redis.call(\"get\",KEYS[1]) == ARGV[1] then\r\n return redis.call(\"del\",KEYS[1])\r\nelse\r\n return 0\r\nend\r\n```\r\n\r\nUnfortunately I don't think there is a good solution for memcached.\r\n\r\nhttps://redis.io/topics/distlock", "created_at": "2018-11-28T15:41:46Z" }, { "body": "Good point, will fix", "created_at": "2018-11-28T15:42:34Z" }, { "body": "Actually it is necessary for compatibility, like in the `RedisStore`: https://github.com/laravel/framework/blob/9f313ce9bb5ad49a06ae78d33fbdd1c92a0e21f6/src/Illuminate/Cache/RedisStore.php#L276\r\n\r\nTests are failing if we don't serialise it.", "created_at": "2018-11-28T15:47:09Z" }, { "body": "Couldn't we use a transaction for that? The Redis docs say:\r\n> It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction.\r\n\r\nFor Memcached the `cas` command can be used setting it to `null`. Though this would eliminate the possibility of storing the lock for later release as @taylorotwell pointed out above, as the `cas` assumes a state on the client: http://php.net/manual/de/memcached.cas.php", "created_at": "2018-11-28T15:59:58Z" }, { "body": "> Couldn't we use a transaction for that? \r\n\r\nYou need to check if the key matches the token before deleting it. I don't think there is an equivalent Redis command that does that. Redis transactions aren't like database transactions, the GET will just be queued until EXEC and you can't read the value of the key in PHP before you call `EXEC`.", "created_at": "2018-11-28T16:10:29Z" }, { "body": "> the GET will just be queued until EXEC\r\n\r\nyep, right just tried that", "created_at": "2018-11-28T16:28:42Z" }, { "body": "Actually it was the test failing that was using the cache instead of the lock to verify, fixed it and got rid of the serialize.", "created_at": "2018-11-28T16:38:38Z" }, { "body": "We probably want this to be `string|null`?", "created_at": "2018-12-04T17:17:21Z" }, { "body": "Actually the nullability of the owner field is just an artifact that was left from the 5.7 implementation. Shouldn't we move to `string` only for all `@return` and `@var` (except for the constructors)?", "created_at": "2018-12-04T17:25:58Z" }, { "body": "@GrahamCampbell any opinion on that one?", "created_at": "2018-12-12T11:03:11Z" }, { "body": "Yes, if that is their type.", "created_at": "2019-01-02T16:01:28Z" } ], "title": "[5.8] Allow locks to be secure against out of order releases" }
{ "commits": [ { "message": "Add option for scoped Cache locks\n\nBefore this change out of order releases of the same cache lock could lead\nto situation where client A acquired the lock, took longer than the timeout,\nwhich made client B successfully acquire the lock. If A now finishes while B\nis still holding the lock A will release the lock that does not belong to it.\n\nThis fix introduces a unique value that is written as the cache value to stop\nA from deleting B's lock." }, { "message": "Use Str::random instead of uniqid" }, { "message": "Use locks for check in test to eliminate need for serialization" }, { "message": "Style fixes" }, { "message": "Renamed scoped to owned" }, { "message": "WIP - move to 5.8 and make owned locks the default behaviour" }, { "message": "Fixes" }, { "message": "Fixed invalid phpdoc" }, { "message": "Fixed invalid phpdoc" }, { "message": "Restore lock with original owner token and memcached changes" }, { "message": "Introduce restoreLock function" }, { "message": "Move redis lock release to lua script" }, { "message": "Style fixes" } ], "files": [ { "diff": "@@ -2,6 +2,7 @@\n \n namespace Illuminate\\Cache;\n \n+use Illuminate\\Support\\Str;\n use Illuminate\\Support\\InteractsWithTime;\n use Illuminate\\Contracts\\Cache\\Lock as LockContract;\n use Illuminate\\Contracts\\Cache\\LockTimeoutException;\n@@ -24,17 +25,30 @@ abstract class Lock implements LockContract\n */\n protected $seconds;\n \n+ /**\n+ * The scope identifier of this lock.\n+ *\n+ * @var string\n+ */\n+ protected $owner;\n+\n /**\n * Create a new lock instance.\n *\n * @param string $name\n * @param int $seconds\n+ * @param string|null $owner\n * @return void\n */\n- public function __construct($name, $seconds)\n+ public function __construct($name, $seconds, $owner = null)\n {\n+ if (is_null($owner)) {\n+ $owner = Str::random();\n+ }\n+\n $this->name = $name;\n $this->seconds = $seconds;\n+ $this->owner = $owner;\n }\n \n /**\n@@ -51,6 +65,13 @@ abstract public function acquire();\n */\n abstract public function release();\n \n+ /**\n+ * Returns the owner value written into the driver for this lock.\n+ *\n+ * @return mixed\n+ */\n+ abstract protected function getCurrentOwner();\n+\n /**\n * Attempt to acquire the lock.\n *\n@@ -101,4 +122,24 @@ public function block($seconds, $callback = null)\n \n return true;\n }\n+\n+ /**\n+ * Returns the current owner of the lock.\n+ *\n+ * @return string\n+ */\n+ public function getOwner()\n+ {\n+ return $this->owner;\n+ }\n+\n+ /**\n+ * Determines whether this lock is allowed to release the lock in the driver.\n+ *\n+ * @return bool\n+ */\n+ protected function isOwnedByCurrentProcess()\n+ {\n+ return $this->getCurrentOwner() === $this->owner;\n+ }\n }", "filename": "src/Illuminate/Cache/Lock.php", "status": "modified" }, { "diff": "@@ -0,0 +1,25 @@\n+<?php\n+\n+namespace Illuminate\\Cache;\n+\n+class LuaScripts\n+{\n+ /**\n+ * Get the Lua script to atomically release a lock.\n+ *\n+ * KEYS[1] - The name of the lock\n+ * ARGV[1] - The owner key of the lock instance trying to release it\n+ *\n+ * @return string\n+ */\n+ public static function releaseLock()\n+ {\n+ return <<<'LUA'\n+if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n+ return redis.call(\"del\",KEYS[1])\n+else\n+ return 0\n+end\n+LUA;\n+ }\n+}", "filename": "src/Illuminate/Cache/LuaScripts.php", "status": "added" }, { "diff": "@@ -17,11 +17,12 @@ class MemcachedLock extends Lock\n * @param \\Memcached $memcached\n * @param string $name\n * @param int $seconds\n+ * @param string|null $owner\n * @return void\n */\n- public function __construct($memcached, $name, $seconds)\n+ public function __construct($memcached, $name, $seconds, $owner = null)\n {\n- parent::__construct($name, $seconds);\n+ parent::__construct($name, $seconds, $owner);\n \n $this->memcached = $memcached;\n }\n@@ -34,7 +35,7 @@ public function __construct($memcached, $name, $seconds)\n public function acquire()\n {\n return $this->memcached->add(\n- $this->name, 1, $this->seconds\n+ $this->name, $this->owner, $this->seconds\n );\n }\n \n@@ -44,7 +45,29 @@ public function acquire()\n * @return void\n */\n public function release()\n+ {\n+ if ($this->isOwnedByCurrentProcess()) {\n+ $this->memcached->delete($this->name);\n+ }\n+ }\n+\n+ /**\n+ * Releases this lock in disregard of ownership.\n+ *\n+ * @return void\n+ */\n+ public function forceRelease()\n {\n $this->memcached->delete($this->name);\n }\n+\n+ /**\n+ * Returns the owner value written into the driver for this lock.\n+ *\n+ * @return mixed\n+ */\n+ protected function getCurrentOwner()\n+ {\n+ return $this->memcached->get($this->name);\n+ }\n }", "filename": "src/Illuminate/Cache/MemcachedLock.php", "status": "modified" }, { "diff": "@@ -188,13 +188,26 @@ public function forever($key, $value)\n /**\n * Get a lock instance.\n *\n+ * @param string $name\n+ * @param int $seconds\n+ * @param string|null $owner\n+ * @return \\Illuminate\\Contracts\\Cache\\Lock\n+ */\n+ public function lock($name, $seconds = 0, $owner = null)\n+ {\n+ return new MemcachedLock($this->memcached, $this->prefix.$name, $seconds, $owner);\n+ }\n+\n+ /**\n+ * Restore a lock instance using the owner identifier.\n+ *\n * @param string $name\n- * @param int $seconds\n+ * @param string $owner\n * @return \\Illuminate\\Contracts\\Cache\\Lock\n */\n- public function lock($name, $seconds = 0)\n+ public function restoreLock($name, $owner)\n {\n- return new MemcachedLock($this->memcached, $this->prefix.$name, $seconds);\n+ return $this->lock($name, 0, $owner);\n }\n \n /**", "filename": "src/Illuminate/Cache/MemcachedStore.php", "status": "modified" }, { "diff": "@@ -17,11 +17,12 @@ class RedisLock extends Lock\n * @param \\Illuminate\\Redis\\Connections\\Connection $redis\n * @param string $name\n * @param int $seconds\n+ * @param string|null $owner\n * @return void\n */\n- public function __construct($redis, $name, $seconds)\n+ public function __construct($redis, $name, $seconds, $owner = null)\n {\n- parent::__construct($name, $seconds);\n+ parent::__construct($name, $seconds, $owner);\n \n $this->redis = $redis;\n }\n@@ -33,7 +34,7 @@ public function __construct($redis, $name, $seconds)\n */\n public function acquire()\n {\n- $result = $this->redis->setnx($this->name, 1);\n+ $result = $this->redis->setnx($this->name, $this->owner);\n \n if ($result === 1 && $this->seconds > 0) {\n $this->redis->expire($this->name, $this->seconds);\n@@ -48,7 +49,27 @@ public function acquire()\n * @return void\n */\n public function release()\n+ {\n+ $this->redis->eval(LuaScripts::releaseLock(), 1, $this->name, $this->owner);\n+ }\n+\n+ /**\n+ * Releases this lock in disregard of ownership.\n+ *\n+ * @return void\n+ */\n+ public function forceRelease()\n {\n $this->redis->del($this->name);\n }\n+\n+ /**\n+ * Returns the owner value written into the driver for this lock.\n+ *\n+ * @return string\n+ */\n+ protected function getCurrentOwner()\n+ {\n+ return $this->redis->get($this->name);\n+ }\n }", "filename": "src/Illuminate/Cache/RedisLock.php", "status": "modified" }, { "diff": "@@ -168,13 +168,26 @@ public function forever($key, $value)\n /**\n * Get a lock instance.\n *\n+ * @param string $name\n+ * @param int $seconds\n+ * @param string|null $owner\n+ * @return \\Illuminate\\Contracts\\Cache\\Lock\n+ */\n+ public function lock($name, $seconds = 0, $owner = null)\n+ {\n+ return new RedisLock($this->connection(), $this->prefix.$name, $seconds, $owner);\n+ }\n+\n+ /**\n+ * Restore a lock instance using the owner identifier.\n+ *\n * @param string $name\n- * @param int $seconds\n+ * @param string $owner\n * @return \\Illuminate\\Contracts\\Cache\\Lock\n */\n- public function lock($name, $seconds = 0)\n+ public function restoreLock($name, $owner)\n {\n- return new RedisLock($this->connection(), $this->prefix.$name, $seconds);\n+ return $this->lock($name, 0, $owner);\n }\n \n /**", "filename": "src/Illuminate/Cache/RedisStore.php", "status": "modified" }, { "diff": "@@ -27,4 +27,18 @@ public function block($seconds, $callback = null);\n * @return void\n */\n public function release();\n+\n+ /**\n+ * Returns the current owner of the lock.\n+ *\n+ * @return string\n+ */\n+ public function getOwner();\n+\n+ /**\n+ * Releases this lock in disregard of ownership.\n+ *\n+ * @return void\n+ */\n+ public function forceRelease();\n }", "filename": "src/Illuminate/Contracts/Cache/Lock.php", "status": "modified" }, { "diff": "@@ -9,7 +9,17 @@ interface LockProvider\n *\n * @param string $name\n * @param int $seconds\n+ * @param string|null $owner\n * @return \\Illuminate\\Contracts\\Cache\\Lock\n */\n- public function lock($name, $seconds = 0);\n+ public function lock($name, $seconds = 0, $owner = null);\n+\n+ /**\n+ * Restore a lock instance using the owner identifier.\n+ *\n+ * @param string $name\n+ * @param string $owner\n+ * @return \\Illuminate\\Contracts\\Cache\\Lock\n+ */\n+ public function restoreLock($name, $owner);\n }", "filename": "src/Illuminate/Contracts/Cache/LockProvider.php", "status": "modified" }, { "diff": "@@ -37,20 +37,20 @@ public function setUp()\n \n public function test_memcached_locks_can_be_acquired_and_released()\n {\n- Cache::store('memcached')->lock('foo')->release();\n+ Cache::store('memcached')->lock('foo')->forceRelease();\n $this->assertTrue(Cache::store('memcached')->lock('foo', 10)->get());\n $this->assertFalse(Cache::store('memcached')->lock('foo', 10)->get());\n- Cache::store('memcached')->lock('foo')->release();\n+ Cache::store('memcached')->lock('foo')->forceRelease();\n $this->assertTrue(Cache::store('memcached')->lock('foo', 10)->get());\n $this->assertFalse(Cache::store('memcached')->lock('foo', 10)->get());\n- Cache::store('memcached')->lock('foo')->release();\n+ Cache::store('memcached')->lock('foo')->forceRelease();\n }\n \n public function test_memcached_locks_can_block_for_seconds()\n {\n Carbon::setTestNow();\n \n- Cache::store('memcached')->lock('foo')->release();\n+ Cache::store('memcached')->lock('foo')->forceRelease();\n $this->assertEquals('taylor', Cache::store('memcached')->lock('foo', 10)->block(1, function () {\n return 'taylor';\n }));\n@@ -61,7 +61,7 @@ public function test_memcached_locks_can_block_for_seconds()\n \n public function test_locks_can_run_callbacks()\n {\n- Cache::store('memcached')->lock('foo')->release();\n+ Cache::store('memcached')->lock('foo')->forceRelease();\n $this->assertEquals('taylor', Cache::store('memcached')->lock('foo', 10)->get(function () {\n return 'taylor';\n }));\n@@ -80,4 +80,34 @@ public function test_locks_throw_timeout_if_block_expires()\n return 'taylor';\n }));\n }\n+\n+ public function test_concurrent_memcached_locks_are_released_safely()\n+ {\n+ Cache::store('memcached')->lock('bar')->forceRelease();\n+\n+ $firstLock = Cache::store('memcached')->lock('bar', 1);\n+ $this->assertTrue($firstLock->acquire());\n+ sleep(2);\n+\n+ $secondLock = Cache::store('memcached')->lock('bar', 10);\n+ $this->assertTrue($secondLock->acquire());\n+\n+ $firstLock->release();\n+\n+ $this->assertTrue(Cache::store('memcached')->has('bar'));\n+ }\n+\n+ public function test_memcached_locks_can_be_released_using_owner_token()\n+ {\n+ Cache::store('memcached')->lock('foo')->forceRelease();\n+\n+ $firstLock = Cache::store('memcached')->lock('foo', 10);\n+ $this->assertTrue($firstLock->get());\n+ $owner = $firstLock->getOwner();\n+\n+ $secondLock = Cache::store('memcached')->restoreLock('foo', $owner);\n+ $secondLock->release();\n+\n+ $this->assertTrue(Cache::store('memcached')->lock('foo')->get());\n+ }\n }", "filename": "tests/Integration/Cache/MemcachedCacheLockTest.php", "status": "modified" }, { "diff": "@@ -30,11 +30,15 @@ public function tearDown()\n \n public function test_redis_locks_can_be_acquired_and_released()\n {\n- Cache::store('redis')->lock('foo')->release();\n- $this->assertTrue(Cache::store('redis')->lock('foo', 10)->get());\n+ Cache::store('redis')->lock('foo')->forceRelease();\n+\n+ $lock = Cache::store('redis')->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n $this->assertFalse(Cache::store('redis')->lock('foo', 10)->get());\n- Cache::store('redis')->lock('foo')->release();\n- $this->assertTrue(Cache::store('redis')->lock('foo', 10)->get());\n+ $lock->release();\n+\n+ $lock = Cache::store('redis')->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n $this->assertFalse(Cache::store('redis')->lock('foo', 10)->get());\n Cache::store('redis')->lock('foo')->release();\n }\n@@ -43,12 +47,42 @@ public function test_redis_locks_can_block_for_seconds()\n {\n Carbon::setTestNow();\n \n- Cache::store('redis')->lock('foo')->release();\n+ Cache::store('redis')->lock('foo')->forceRelease();\n $this->assertEquals('taylor', Cache::store('redis')->lock('foo', 10)->block(1, function () {\n return 'taylor';\n }));\n \n- Cache::store('redis')->lock('foo')->release();\n+ Cache::store('redis')->lock('foo')->forceRelease();\n $this->assertTrue(Cache::store('redis')->lock('foo', 10)->block(1));\n }\n+\n+ public function test_concurrent_redis_locks_are_released_safely()\n+ {\n+ Cache::store('redis')->lock('foo')->forceRelease();\n+\n+ $firstLock = Cache::store('redis')->lock('foo', 1);\n+ $this->assertTrue($firstLock->get());\n+ sleep(2);\n+\n+ $secondLock = Cache::store('redis')->lock('foo', 10);\n+ $this->assertTrue($secondLock->get());\n+\n+ $firstLock->release();\n+\n+ $this->assertFalse(Cache::store('redis')->lock('foo')->get());\n+ }\n+\n+ public function test_redis_locks_can_be_released_using_owner_token()\n+ {\n+ Cache::store('redis')->lock('foo')->forceRelease();\n+\n+ $firstLock = Cache::store('redis')->lock('foo', 10);\n+ $this->assertTrue($firstLock->get());\n+ $owner = $firstLock->getOwner();\n+\n+ $secondLock = Cache::store('redis')->restoreLock('foo', $owner);\n+ $secondLock->release();\n+\n+ $this->assertTrue(Cache::store('redis')->lock('foo')->get());\n+ }\n }", "filename": "tests/Integration/Cache/RedisCacheLockTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.10 \r\n- PHP Version: 7.2.5\r\n- Database Driver & Version: mysql:5.7\r\n\r\n### Description:\r\nEmail verification link `/email/verify/{id}` will always return true for authenticated users regardless if route->parameter->id matches user->id.\r\n\r\n\r\n### Steps To Reproduce:\r\n- Register or log in as unconfirmed user \"A\" (user->id = 1) to generate email verification confirmation that contains email verification link. \r\n- Log out user \"A\".\r\n- Register or login as unconfirmed user \"B\" (user->id = 2). \r\n- While logged in, click the email verification link from the email sent out to user \"A\" which will have route parameter id = 1.\r\n- The link will successfully redirect as if the process was successful even though the route parameter id (1) does not match the user id of user \"B\" id(2).\r\n\r\nWe have overridden the verify() method in our VerificationController to address in our app.\r\n\r\n```php\r\n /**\r\n * Mark the authenticated user's email address as verified.\r\n *\r\n * @param \\Illuminate\\Http\\Request $request\r\n * @return \\Illuminate\\Http\\Response\r\n * @throws AuthorizationException\r\n */\r\n\tpublic function verify(Request $request)\r\n\t{\r\n\t\tif ($request->route('id') != $request->user()->getKey()) {\r\n\t\t\tthrow new \\Illuminate\\Auth\\Access\\AuthorizationException\\AuthorizationException();\r\n\t\t}\r\n\r\n\t\tif ($request->user()->markEmailAsVerified()) {\r\n\t\t\tevent(new Verified($request->user()));\r\n\t\t}\r\n\r\n\t\treturn redirect($this->redirectPath())->with('verified', true);\r\n\t}\r\n```", "comments": [ { "body": "I can indeed see why this would give you trouble. Given the fact that we use user ids in the url and not a random string we should indeed require the actual user to be logged in so your solution makes sense I believe. Feel free to send in a PR to the 5.7 branch.", "created_at": "2018-11-15T12:11:10Z" } ], "number": 26507, "title": "Email Verification fails to authorize route id properly" }
{ "body": "Issue fix #26507", "number": 26528, "review_comments": [ { "body": "Please use the fully qualified class name.", "created_at": "2018-11-16T12:27:16Z" }, { "body": "Please keep the 2nd space that was there.", "created_at": "2018-11-16T12:27:36Z" } ], "title": "[5.7] Fix verify of current user id on email verification" }
{ "commits": [ { "message": "Add verify of current user id on email verification" }, { "message": "Style fix" }, { "message": "Style fix" }, { "message": "Style fix" }, { "message": "Fix StyleCI failures" }, { "message": "Styling fix" } ], "files": [ { "diff": "@@ -4,6 +4,7 @@\n \n use Illuminate\\Http\\Request;\n use Illuminate\\Auth\\Events\\Verified;\n+use Illuminate\\Auth\\Access\\AuthorizationException;\n \n trait VerifiesEmails\n {\n@@ -27,11 +28,15 @@ public function show(Request $request)\n *\n * @param \\Illuminate\\Http\\Request $request\n * @return \\Illuminate\\Http\\Response\n+ * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n */\n public function verify(Request $request)\n {\n- if ($request->route('id') == $request->user()->getKey() &&\n- $request->user()->markEmailAsVerified()) {\n+ if ($request->route('id') != $request->user()->getKey()) {\n+ throw new AuthorizationException();\n+ }\n+\n+ if ($request->user()->markEmailAsVerified()) {\n event(new Verified($request->user()));\n }\n ", "filename": "src/Illuminate/Foundation/Auth/VerifiesEmails.php", "status": "modified" } ] }
{ "body": "Experienced this in 5.0 and 5.1\n\nMySQL version: 5.6\nForge provisioned server.\n\nWe use Galera Cluster for MySQL, but each site reads and writes from only one database. I don't think that would have anything to do with this error. I used `artisan session:table` to create the table so everything is standard schema-wise. Happens quite intermittently, about once per day.\n\n```\nIlluminate\\Database\\QueryExceptionGET /diaz/edit\nSQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4c1698dcfe5da87c5f77c90592855490817e575d' for key 'sessions_id_unique' (SQL: insert into `sessions` (`id`, `payload`, `last_activity`) values (4c1698dcfe5da87c5f77c90592855490817e575d, YTo1OntzOjY6Il90b2tlbiI7czo0MDoid1NLSjlmNGFxUml4RkowRVVkU0M3UjhNdldhWlZEY2hwTDhrbEU3YSI7czo3OiJtZXNzYWdlIjtzOjI2OiJMb2dpbiB0byBlZGl0IHlvdXIgcHJvZmlsZSI7czo1OiJmbGFzaCI7YToyOntzOjM6Im5ldyI7YTowOnt9czozOiJvbGQiO2E6MTp7aTowO3M6NzoibWVzc2FnZSI7fX1zOjk6Il9wcmV2aW91cyI7YToxOntzOjM6InVybCI7czozNzoiaHR0cHM6Ly9tYW5pbGEuZXNjb3J0cy5saWZlL2RpYXovZWRpdCI7fXM6OToiX3NmMl9tZXRhIjthOjM6e3M6MToidSI7aToxNDM0MTY4Njc0O3M6MToiYyI7aToxNDM0MTY4Njc0O3M6MToibCI7czoxOiIwIjt9fQ==, 1434168674))\n```\n", "comments": [ { "body": "Is it possible that insert quieries are not written immediately but with some latency?\n", "created_at": "2015-06-13T13:31:05Z" }, { "body": "yes but not much. I am not caching config.\n", "created_at": "2015-06-13T14:13:54Z" }, { "body": "You probably need to cache config. That fixes most issues I see like this.\n", "created_at": "2015-06-13T14:49:31Z" }, { "body": "I'm using config:cache but I still see this issue every day or so.\nWe still relay on `dotenv` to populate server variables, so this might be the issue.\n", "created_at": "2015-06-13T17:38:06Z" }, { "body": "Why do you think it is a config cache issue?\nI guess there may be some latency between sending response (with session ID) and app termination (when session is being saved to databse).\n\nFor example:\n1. User sends request - session id created (session->exists == false)\n2. User gets response (with generated session id).\n3. Some ajax or another request catches session id (session->exists == false as the first request is not finished - session is not written).\n4. One of requests terminates app ([session written to database with INSERT](https://github.com/laravel/framework/blob/5.1/src/Illuminate/Session/DatabaseSessionHandler.php#L79))\n5. Another request terminates with INSERT statement again (because session->exists is false in both cases)\n\nOtherwise it may be database INSERT query latency so the second request executes SELECT before insert finishes.\n", "created_at": "2015-06-13T18:13:59Z" }, { "body": "Happened to me now after switched to database driver for session .. any idea?\n\nThanks\n\nping @taylorotwell \n", "created_at": "2015-11-09T15:51:08Z" }, { "body": "I am experiencing the issue as well, using the default session build with the DB.\n", "created_at": "2015-11-10T14:55:25Z" }, { "body": ":+1:\n", "created_at": "2015-11-10T15:31:03Z" }, { "body": "@GrahamCampbell why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver -> save method. \n", "created_at": "2016-01-28T23:18:39Z" }, { "body": "This needs reopening.\n\nOn Jan 28, 2016, 5:18 PM -0600, Dean Mnotifications@github.com, wrote:\n\n> @GrahamCampbell(https://github.com/GrahamCampbell)why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver ->save method.\n> \n> —\n> Reply to this email directly orview it on GitHub(https://github.com/laravel/framework/issues/9251#issuecomment-176477099).\n", "created_at": "2016-01-29T00:20:34Z" }, { "body": "Does anyone have a solution?\n\nOn Jan 28, 2016, 5:18 PM -0600, Dean Mnotifications@github.com, wrote:\n\n> @GrahamCampbell(https://github.com/GrahamCampbell)why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver ->save method.\n> \n> —\n> Reply to this email directly orview it on GitHub(https://github.com/laravel/framework/issues/9251#issuecomment-176477099).\n", "created_at": "2016-01-29T00:20:44Z" }, { "body": "Deployed this fix to my environment today. I will let you know if that resolves the issue. \n#12059 \n", "created_at": "2016-01-29T01:13:46Z" }, { "body": "@taylorotwell @GrahamCampbell \n\nLaravel version 5.2.37\n\nI've seen a number of these session integrity issues show up on laracasts, stackoverflow, etc. I ran into the same issue today and able to replicate to some degree. It seems to a session DB related issue vs. session file. To be honest it is not really a bug but a dev issue that can be solved with middleware. That said given the norm of multi device it might be something you want to look into, but unsure if even that applies.\n\nREPLICATE: Let’s say you have a home.blade.php and second page called register.blade.php a route ‘/register’ which yields content from home. If you load /register from lets say from a MAMP stack everything will work fine as expected. Now while you still have that session, open a new browser tab. Make a copy of home.blade.php , lets say debug.blade.php which again yields to the same register.blade.php a route ‘/register’ and now if you load /register it will load register and will create the duplicate session id. Now if you go back to original tab and attempt to load register or you will get a DB session integrity duplicate issue. Which is why a number of bug complaints are login / logout related as I suspect is because they are directing to a different (duplicate) home page while still using the same session. Unsure what is causing the duplicate issue i.e if it is csrf token / session / DB session / home page issue.\n\nHope his helps.\n", "created_at": "2016-06-13T16:52:27Z" }, { "body": "Any solution for this Bug?\n", "created_at": "2016-06-13T20:30:50Z" }, { "body": ":+1:\n", "created_at": "2016-06-13T21:17:57Z" }, { "body": "> Any solution for this Bug?\n\nNot in 3 hours.\n", "created_at": "2016-06-13T21:28:04Z" }, { "body": "fwiw, I noticed I can also replicate it again by breaking a blade template load during ajax requests. For example if I force a blade template fails (e.g. wrong name) while I'm doing an ajax init() data load on vanilla route. \n\n<code>\nRoute::get('/register', [\n 'as' => 'getRegister',\n 'uses' => 'ApiController@getRegister',\n]); \n</code>\n\nbeen trying to debug it further but none of angular / testing tools are giving me any additional insight. I do believe that to @rkgrep summary above that there is a session / queue issue / conflict and might be ajax related. In my case I have a number of angular services init ajax http requests and if the template fails i.e. exception and then attempt to reload . It returns the unencoded JSON with a 200 status code.\n\n```\n javascript?v=1453465343:2050 Uncaught SyntaxError: Unexpected token < \n\nfollowed by a \n\n angular.js:13642 SyntaxError: Unexpected token < in JSON at position 11625. \n```\n\nthe position 11625 is where the html document gets appended to the JSON data. \n\nI think it is worth nothing that I get the following exception if it detects an existing session record, but I get the above silent fail if it has 2 existing session records i.e somehow the DB has written 2 identical session records and if it attempts to write a 3rd it fails silently and sends back JSON data but unencoded.\n\n<code>\nNext exception 'Illuminate\\Database\\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'a26e09eaf0a210a34e58ebab42acd9435681e0a5' for key 'sessions_id_unique' (SQL: insert into `sessions` (`payload`, `last_activity`, `user_id`, `ip_address`, `user_agent`, `id`) values (YTo0OntzOjY6Il90b2tlbiI7czo0MDoiOVE3M3ZLam12YlpFVEhLNDBSOVAwMDdIZWpKeGY0YUFNQVZDRTFJUCI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MzI6Imh0dHA6Ly93d3cuY21vOjg4ODgvYXBpL3BlcnNvbmFzIjt9czo5OiJfc2YyX21ldGEiO2E6Mzp7czoxOiJ1IjtpOjE0NjU5MjE0ODU7czoxOiJjIjtpOjE0NjU5MjE0ODU7czoxOiJsIjtzOjE6IjAiO31zOjU6ImZsYXNoIjthOjI6e3M6Mzoib2xkIjthOjA6e31zOjM6Im5ldyI7YTowOnt9fX0=, 1465921486, , ::1, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36, a26e09eaf0a210a34e58ebab42acd9435681e0a5))' in /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php:713\nStack trace:\n#0 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(669): Illuminate\\Database\\Connection->runQueryCallback('insert into `se...', Array, Object(Closure))\n#1 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(442): Illuminate\\Database\\Connection->run('insert into`se...', Array, Object(Closure))\n#2 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(398): Illuminate\\Database\\Connection->statement('insert into `se...', Array)\n#3 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2039): Illuminate\\Database\\Connection->insert('insert into`se...', Array)\n#4 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php(117): Illuminate\\Database\\Query\\Builder->insert(Array)\n#5 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/Store.php(262): Illuminate\\Session\\DatabaseSessionHandler->write('a26e09eaf0a210a...', 'a:4:{s:6:\"_toke...')\n#6 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(88): Illuminate\\Session\\Store->save()\n#7 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(155): Illuminate\\Session\\Middleware\\StartSession->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))\n#8 /Users/nolros/Documents/cmo/public/index.php(58): Illuminate\\Foundation\\Http\\Kernel->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))\n#9 {main} \n</code>\n\nhere is an example of the ajax request\n\n<code>\n Request URL:http://www.cmo:8888/api/personas\nRequest Method:GET\nStatus Code:200 OK\nRemote Address:[::1]:8888\nResponse Headers\nview source\nCache-Control:no-cache\nConnection:Keep-Alive\nContent-Type:application/json\nDate:Tue, 14 Jun 2016 16:24:45 GMT\nKeep-Alive:timeout=5, max=96\nphpdebugbar-id:b73cf0e58e0f47fd49857463540cbaf3\nServer:Apache\nSet-Cookie:laravel_session=a26e09eaf0a210a34e58ebab42acd9435681e0a5; path=/; httponly\nSet - Cookie:XSRF - TOKEN = eyJpdiI6Ijd2Y0pmN3JCSWRTNGE5dzFnT1FSSFE9PSIsInZhbHVlIjoiNWFubHNNYTVLeGRRc1B4RW9zMGNBQ3NVTFpDeTUrVkdzZWpWWjBRXC9scDlRejQ0TnpwNHQzV3BrUkJlamNUSm5jZjFudmFCM1VLb0dlUEhERHVPN0xRPT0iLCJtYWMiOiJjNTYxZDc3NmM0ZTI5M2MzNGI2ZmM3MDIxZGFjMDZiMzc1MGI1OTM4YWExOGI5NzczNTUzMzJiMmE3ZDkxZmRjIn0 % 3D; expires = Tue, 14 - Jun - 2016 18:24:46 GMT; Max - Age = 7200; path =/\nTransfer-Encoding:chunked\nX-Powered-By:PHP/5.6.10\nRequest Headers\nview source\nAccept:application/json, text/plain, _/_\nAccept-Encoding:gzip, deflate, sdch\nAccept-Language:en-US,en;q=0.8\nCache-Control:no-cache\nConnection:keep-alive\nCookie:cmosolution=eyJpdiI6IlBIYUhCQzJYUUxkMFwvZ0x2RmJraFhnPT0iLCJ2YWx1ZSI6IjVqaXA2ak9WN3laaHdVNkVtRVRPbVJOVThoRTVGV2E0K1RiTHdIcFQ4eGNCTU9nYjRnUnhVWEduODJvS1wvVW15QUlcL1ZyWlp0Z3o0MVhGem1rUzZPZjlLNEY5VTF3eW4zckE0ZXNHTHRCZXlOVVRDWkFoS3NlNHlBRVR3Y3IwdFkiLCJtYWMiOiI1NDcxNmRiZTBiN2NiMmQ5ODcwYTMyZDcxY2ZmYzFkMGU1NmRiNTc0MDAxNTBiMTVhZjNlZjJkMTljNjIyYmFlIn0%3D; remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6Im94R1B6NFwvUnpMQUp2M0VuTDN3cFlnPT0iLCJ2YWx1ZSI6IjNJZUVCSnFhR1IzZ0tVaVNTd3hUb1NcL2FIcHFcL1pJaE9FMGRIc2hQV1NDZzBycmVxN2xUb0s3aUdjWnpRaDFCWlwveHhCXC8xZG1wOE5WdnJpc0RYK094UGVMWDJ1cjNiSFE0R2tMM2VhRkJuVT0iLCJtYWMiOiJhMjMzYTFlNmM2MWIxNDJlNDQwZDJiZTNhNjhhNWFhNzRlZThiYjNhNjc1NDhiY2MxNjI0MTc2MGY3MDgwYWQxIn0%3D; XSRF-TOKEN=eyJpdiI6IlZ5bHZNNlVXM0ZqM0tWd0dheUtJUEE9PSIsInZhbHVlIjoieGdyYzRtOUFHaHptMGVYbUw1ZzNIVU5hTjQ5cDM1QWljNHBWazVWZVVZdXdBRnl1YWFpc1UzVE53Q0tlbGZLQUxVazdLcWZ0enZxWG5vUURGZHVcL2RnPT0iLCJtYWMiOiI3NDIxNDJmN2Q3NWYxYWE2MTY0NDc4MGM4ZWNkMzFiNDY3OWE3ZWExMmNiMDEzZDNiYjU1Njg4NGQ5NzJhZmMxIn0%3D; laravel_session=a26e09eaf0a210a34e58ebab42acd9435681e0a5\nHost:www.cmo:8888\nPragma:no-cache\nReferer:http://www.cmo:8888/register\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36\nX-XSRF-TOKEN:eyJpdiI6IlZ5bHZNNlVXM0ZqM0tWd0dheUtJUEE9PSIsInZhbHVlIjoieGdyYzRtOUFHaHptMGVYbUw1ZzNIVU5hTjQ5cDM1QWljNHBWazVWZVVZdXdBRnl1YWFpc1UzVE53Q0tlbGZLQUxVazdLcWZ0enZxWG5vUURGZHVcL2RnPT0iLCJtYWMiOiI3NDIxNDJmN2Q3NWYxYWE2MTY0NDc4MGM4ZWNkMzFiNDY3OWE3ZWExMmNiMDEzZDNiYjU1Njg4NGQ5NzJhZmMxIn0=\n</code>\n\nThe issue is resolved if I delete the DB session. This probably doesn't help much but I thought I would share anyway.\n", "created_at": "2016-06-14T16:58:11Z" }, { "body": "Any solution?\n", "created_at": "2016-06-14T19:19:29Z" }, { "body": "Is it working on the very latest version?\n", "created_at": "2016-06-14T19:45:17Z" }, { "body": "5.1.*\n", "created_at": "2016-06-14T19:52:25Z" }, { "body": "Please provide the exact version.\n", "created_at": "2016-06-14T20:08:57Z" }, { "body": "Laravel Framework version 5.1.39 (LTS)\n", "created_at": "2016-06-14T20:15:32Z" }, { "body": "@GrahamCampbell fails in version 5.2.37 but no problem in version 5.2.38. I've run all tests and tried all scenarios and pleased to report no problem. Thank you!\n", "created_at": "2016-06-14T21:25:11Z" }, { "body": "Great. ;)\n", "created_at": "2016-06-14T21:44:59Z" }, { "body": "But, if it's still broken on 5.1?\n", "created_at": "2016-06-14T21:45:52Z" }, { "body": "Version 5.1.39 does not work\n", "created_at": "2016-06-14T21:57:59Z" }, { "body": "I made the same change to 5.1 as to 5.2. If there is still a problem please someone make a PR. I am on vacation.\n", "created_at": "2016-06-15T00:18:33Z" }, { "body": "Version 5.1.39 does not work\n", "created_at": "2016-06-15T14:28:30Z" }, { "body": "Someone make a PR to fix please.\n", "created_at": "2016-06-15T23:39:37Z" }, { "body": "I think this was a recent change/update. Have been working on something for a client for months now, and only after a recent composer update did this issue starting showing... Any chance this is a dependency problem?\n\nEdit: For reference, this is happening at least twice a day on a local testbed running MySQL 5.7 and PHP 5.6.19. Switching the server to use 7.0.1 resolves the issue for me.\n\nEdit 2: I could be wrong - was silly and did an update at the same time, so can't confirm what made it work without clearing anything.\n", "created_at": "2016-06-17T15:02:55Z" } ], "number": 9251, "title": "Integrity constraint violation when using database session driver" }
{ "body": "Following up from the pull here - \r\n\r\nhttps://github.com/laravel/framework/pull/26441\r\n\r\nI've reverted my changes to the composer setup and just left the back-port to the database session handler.\r\n\r\nIn response to -\r\n\r\n> I'm sorry but we don't support 4.x any longer\r\n\r\nHoping this trivial update that would be appreciated by some as its a constant irritation for us being stuck on version 4 without the option to update. \r\n\r\n---\r\n\r\nSummary from the previous pull request -\r\n\r\nI've back ported a fix in 5 to solve the session fixation issue.\r\n\r\nThis is the issue discussed here -\r\n#9251 (comment)\r\nand fixed later in laravel 5 on commit d9e0a6a\r\n\r\nHoping that this helps others stuck on a 4.2 codebase experiencing the problem.\r\n\r\nThis manifests itself in the laravel logs as -\r\n\r\nlocal.ERROR: 500 exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'xxxxxxxxxx' for key 'sessions_id_unique'' in vendor/laravel/framework/src/Illuminate/Database/Connection.php:369", "number": 26456, "review_comments": [], "title": "Backport session handler fix" }
{ "commits": [ { "message": "This should solve -\n\nlocal.ERROR: 500 exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'XXXXXXX' for key 'sessions_id_unique'' in vendor/laravel/framework/src/Illuminate/Database/Connection.php:369\n\nhttps://github.com/laravel/framework/issues/9251#issuecomment-270991219\n\nFix -\n\nhttps://github.com/laravel/framework/commit/d9e0a6a03891d16ed6a71151354445fbdc9e6f50" }, { "message": "composer setup" }, { "message": "Update composer.json" }, { "message": "missing \"use\" cursory tests look good" }, { "message": "Revert \"Update composer.json\"\n\nThis reverts commit 3bc8a6ed806081f3174a1d7b2a46c269dd15805c." }, { "message": "Revert \"composer setup\"\n\nThis reverts commit 7e9f1289e80753f254126cc1f2e56e64f65d2d21." } ], "files": [ { "diff": "@@ -1,6 +1,9 @@\n <?php namespace Illuminate\\Session;\n \n use Illuminate\\Database\\Connection;\n+use Carbon\\Carbon;\n+use Illuminate\\Database\\QueryException;\n+use Illuminate\\Support\\Arr;\n \n class DatabaseSessionHandler implements \\SessionHandlerInterface, ExistenceAwareInterface {\n \n@@ -74,22 +77,67 @@ public function read($sessionId)\n \t */\n \tpublic function write($sessionId, $data)\n \t{\n+\t\t$payload = $this->getDefaultPayload($data);\n+\t\t\n+\t\tif (! $this->exists) {\n+ $this->read($sessionId);\n+ }\n+\t\t\n \t\tif ($this->exists)\n \t\t{\n-\t\t\t$this->getQuery()->where('id', $sessionId)->update([\n-\t\t\t\t'payload' => base64_encode($data), 'last_activity' => time(),\n-\t\t\t]);\n+\t\t\t$this->performUpdate($sessionId, $payload);\n \t\t}\n \t\telse\n \t\t{\n-\t\t\t$this->getQuery()->insert([\n-\t\t\t\t'id' => $sessionId, 'payload' => base64_encode($data), 'last_activity' => time(),\n-\t\t\t]);\n+\t\t\t$this->performInsert($sessionId, $payload);\n \t\t}\n \n \t\t$this->exists = true;\n \t}\n-\n+/**\n+ * Perform an insert operation on the session ID.\n+ *\n+ * @param string $sessionId\n+ * @param string $payload\n+ * @return void\n+ */\n+ protected function performInsert($sessionId, $payload)\n+ {\n+ try {\n+ return $this->getQuery()->insert(Arr::set($payload, 'id', $sessionId));\n+ } catch (QueryException $e) {\n+ $this->performUpdate($sessionId, $payload);\n+ }\n+ }\n+\n+ /**\n+ * Perform an update operation on the session ID.\n+ *\n+ * @param string $sessionId\n+ * @param string $payload\n+ * @return int\n+ */\n+ protected function performUpdate($sessionId, $payload)\n+ {\n+ return $this->getQuery()->where('id', $sessionId)->update($payload);\n+ }\n+\t\n+ /**\n+ * Get the default payload for the session.\n+ *\n+ * @param string $data\n+ * @return array\n+ */\n+\tprotected function getDefaultPayload($data)\n+ {\n+\t\t//timestamp was time() in 4.2 origionally\n+ $payload = [\n+ 'payload' => base64_encode($data),\n+ 'last_activity' => Carbon::now()->getTimestamp(),\n+ ];\n+\t\t//just return the payload\n+ return $payload;\n+ }\n \t/**\n \t * {@inheritDoc}\n \t */", "filename": "src/Illuminate/Session/DatabaseSessionHandler.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.5.14\r\n- PHP Version: 7.1.9\r\n- Database Driver & Version: MySQL 5.7.19\r\n\r\n### Description:\r\nNot sure this is a intended behavior or a bug. The date attributes of a model is not affected by the Carbon::serializeUsing feature when serializing the whole model. \r\n\r\nSuggestion: If you could introduce a feature which can specify serialized date format on each model attribute will be great. Example, \r\n`\r\nprotected $dateFormats = ['dob' => 'Y-m-d'];\r\n`\r\n\r\n### Steps To Reproduce:\r\nAppServiceProvider.php\r\n`\r\n \\Illuminate\\Support\\Carbon::serializeUsing(function ($carbon) {\r\n return $carbon->format('Y-m-d');\r\n });\r\n`\r\n\r\nApp\\User.php\r\n`\r\n protected $dates = ['dob'];\r\n`\r\n\r\nHomeController.php\r\n`\r\ndd(Auth::user()->jsonSerialize());\r\n`\r\n", "comments": [ { "body": "You need to use `toJson()` instead of `jsonSerialize ()`", "created_at": "2017-10-17T13:39:11Z" }, { "body": "Nope, same result using `toJson()`\r\n\r\nHomeController.php\r\n`\r\nreturn Auth::user()->toJson();\r\n`\r\n\r\nwill still give me \r\n`\r\n{\"id\":1, ... , \"dob\":\"1968-08-04 00:00:00\"}\r\n`", "created_at": "2017-10-18T02:42:55Z" }, { "body": "@lampard7824 I had the same problem. after diving in the code of the `Model` class, date attributes are serialized with the specified date format (see `getDateFormat()` and `$dateFormat` to override) with a fallback to the database date format. You can override `$dateFormat` to use your own. It works but this also affects the expected format when setting the value whereas we mostly want to change the format only during serialization. To change the format only during serialization, you have to override the `serializeDate()` method like this:\r\n\r\n```php\r\nprotected function serializeDate(\\DateTimeInterface $date)\r\n{\r\n return $date->format(\\DateTime::W3C); // Use your own format here\r\n}\r\n```\r\n\r\nSee [this answer](https://stackoverflow.com/a/41569026/1224564) on StackOverflow for an elegant (imho) fix to this issue.\r\n\r\nThe Laravel documentation is a little bit misleading about date serialization.\r\n", "created_at": "2017-10-26T09:59:14Z" }, { "body": "@bgondy I understand this approach is available. is just that since Laravel 5.5 introduced this `\\Illuminate\\Support\\Carbon::serializeUsing()` new feature, I would expect that this will have effect on serialization on all `\\Illuminate\\Support\\Carbon` instances throughout the whole application, including when serializing eloquent model. ", "created_at": "2017-10-27T01:11:54Z" }, { "body": "@themsaid @lampard7824 is right. This issue should be reopened. \r\nWhat usage does `Illuminate\\Support\\Carbon::serializeUsing()` have if it is not for serialization!?\r\n\r\nCited from documentation: \"To customize how all Carbon dates throughout your application are serialized, use the Carbon::serializeUsing method.\"", "created_at": "2017-10-29T19:46:10Z" }, { "body": "@daviian still can't replicate `return Auth::user()->toJson();` returns a correctly formatted date, this issue needs more information for us to look into, the basic steps of replication above doesn't reproduce the issue on a fresh laravel installation.", "created_at": "2017-10-30T12:16:23Z" }, { "body": "@themsaid , appreciate that you coming back to this issue.\r\n\r\nHere's the step to reproduce, after creating a new laravel 5.5 app\r\n1. run `php artisan make:auth`\r\n2. In AppServiceProvider@boot, add the serializeUsing as below: \r\n```\r\npublic function boot() \r\n{\r\n \\Illuminate\\Support\\Carbon::serializeUsing(function ($carbon) { \r\n return $carbon->format('dmY'); \r\n });\r\n}\r\n```\r\n3. Register a user account using the default Auth register page (app.dev/register)\r\n4. In App\\Http\\Controllers\\HomeController@index, \r\n```\r\npublic function index()\r\n{\r\n return \\Auth::user()->toJson(); // this does not work, the created_at and updated_at attribute still showing the default Y-m-d H:i:s format\r\n return \\Auth::user()->created_at; // this works, which returns expected dmY format \r\n}\r\n```\r\n5. browse to the home url, app.dev/home , and check on the returned result\r\n\r\n6. Not sure whether this is intended behavior, but I am expecting after I set the Carbon::serializeUsing to a custom format, all the model instance when serialized to Json, the date attributes should be following that custom format as well, instead of the \"Y-m-d H:i:s\" format.\r\n\r\nI would expect the serialized Json to be `{\"id\":2,\"name\":\"test\",\"email\":\"test@example.com\",\"created_at\":\"30102017\",\"updated_at\":\"30102017\"}`\r\n\r\ninstead of `{\"id\":2,\"name\":\"test\",\"email\":\"test@example.com\",\"created_at\":\"2017-10-30 16:13:10\",\"updated_at\":\"2017-10-30 16:13:10\"}`\r\n\r\n\r\n\r\n\r\n", "created_at": "2017-10-30T16:14:42Z" }, { "body": "Ok now I see where the confusion is, when you do `toArray()` Laravel will convert all Carbon instances to a string using the model date format, so by the time we're serializing to JSON the date is already a string.\r\n\r\nHowever manually returning a Carbon instance in your toArray() method or a resource toArray() method now you'd get the serialization you want.\r\n\r\n```\r\npublic function toArray(){\r\n return [\r\n 'created_at' => $this->created_at\r\n ];\r\n }\r\n```", "created_at": "2017-10-30T16:48:35Z" }, { "body": "My comment here is not valid: https://github.com/laravel/framework/issues/21703#issuecomment-337234425\r\n\r\nI was testing using a resource rather than an Eloquent instance.", "created_at": "2017-10-30T16:49:48Z" }, { "body": "@themsaid Regarding your proposal to override the `toArray` function. IMHO this should be the default behaviour, or does this approach have any downsides?\r\nAnd to go a step further. I guess this will make the `$dateFormat` attribute obsolete?", "created_at": "2017-10-31T12:00:33Z" }, { "body": "Currently I have no real way of making sure that serialized (json_encode) models use the correct formatting due to this bug.", "created_at": "2018-01-02T15:32:04Z" }, { "body": "For now I wrote a hack that that fixes the issue. You just need to add it to your `BaseModel` for it to work.\r\n\r\n```php\r\n/**\r\n * {@inheritdoc}\r\n *\r\n * @override\r\n *\r\n * @todo This is a temporary hack until the following issue has been fixed https://github.com/laravel/framework/issues/21703\r\n */\r\nprotected function addDateAttributesToArray(array $attributes)\r\n{\r\n $stack = array_map(function ($trace) {\r\n return $trace['function'];\r\n }, debug_backtrace());\r\n\r\n $json = in_array('jsonSerialize', $stack);\r\n\r\n foreach ($this->getDates() as $key) {\r\n if (!isset($attributes[$key])) {\r\n continue;\r\n }\r\n\r\n $date = $this->asDateTime($attributes[$key]);\r\n\r\n if ($json) {\r\n $attributes[$key] = $date->jsonSerialize();\r\n } else {\r\n $attributes[$key] = $this->serializeDate($date);\r\n }\r\n }\r\n\r\n return $attributes;\r\n}\r\n```\r\n\r\n```php\r\n// Somewhere in your AppServiceProvider::boot or something\r\nCarbon::serializeUsing(function ($carbon) {\r\n return $carbon->toAtomString();\r\n});\r\n```", "created_at": "2018-01-03T11:31:41Z" }, { "body": "I'm stuck with the same problem after wasting all day in total frustration!\r\n\r\nI followed the instructions in the Laravel 5.6 docs and added this to my AppServiceProvider:\r\n\r\n```\r\n public function boot()\r\n {\r\n Carbon::serializeUsing(function ($carbon) {\r\n return $carbon->toRfc2822String();\r\n });\r\n }\r\n```\r\n\r\nI then return the whole Eloquent model to an Ajax request, sometimes a View.\r\n\r\nAs far as I understand, the Model is automatically serialized, right?\r\n\r\nSo why am I not seeing the Carbon dates properly formatted?\r\n\r\nAnd why is the Laravel 5.6 doc showing an AppServiceProvider that looks different than the one from Laravel 5.5 or 5.6? For a moment I thought I put it into the wrong place! All the doc blocks look totally different.\r\n\r\nI'm also totally bewildered by the fact that the default date format is not what Javascript pretty much demands in all the places. I have moment.js screaming at me why my date/times are not RFC or ISO and that it will fail soon.", "created_at": "2018-02-11T17:19:59Z" }, { "body": "Has there been any progress concerning this issue.", "created_at": "2018-02-14T13:07:27Z" }, { "body": "Is there any update to this Issue?", "created_at": "2018-04-03T13:20:37Z" }, { "body": "No I don't think so, but I would really appreciate somebody with a little more knowledge of the framework's internals to hook into this. \r\nWhether it is wanted or unwanted behavior, the documentation is definitely easy to misunderstand in what is actually supposed to do when you set set serialization callback via `Carbon::serializeUsing()`. So unless you start digging into the framework yourself quite deeply, you'll have no chance predict how your dates are going to be serialized. \r\nThe general problem that makes it hard to find a good implementation is that it is quite tricky to make a good decision on when to use the global carbon serializer or the serialization format that results from the properties set on the eloquent instances. As far as I understand, at the moment the global serialization callback is not considered at all, if your models are serialized via the built-in eloquent mechanisms. The callback is only used when a carbon is serialized directly. Then `$carbon->jsonSerialize` is called, which uses the global serialization callback.\r\nIn my case I just added the following function overwrite to my base model:\r\n```php\r\nprotected function serializeDate(DateTimeInterface $date)\r\n{\r\n return $date->jsonSerialize();\r\n}\r\n```\r\nThis is at least sufficient for me for now and in my specific case, but it will probably not meet a lot of other needs, because it's unflexible. At least this way you have a central point to define how you dates should be serialized. The internal eloquent date serialization is completely skipped.\r\n\r\nUPDATE\r\nI just realized that it does not work for dates in blade templates: `{{$user->created_at}}` is automatically serialized to the readable format `Y-m-d H:i:s` but I don't know where this comes from, since this is not the format I added via serializeUsing.\r\nThis whole stuff is really annoying and confusing.", "created_at": "2018-04-03T14:50:41Z" }, { "body": "So I've been dealing with this for a few hours and I came up with something that isn't too terrible imo.\r\n\r\nMy problem was related to adding timezones to the carbon instance and to the json output of models.\r\n\r\nI'm not sure was `serializeUsing` was intended for, because it isn't used to serialize dates in `->toJson()` ,but I figured it should.\r\n\r\nAppServiceProvider.php\r\n```php\r\npublic function boot()\r\n{\r\n Carbon::serializeUsing(function (Carbon $carbon) {\r\n return $carbon->format('Y-m-d H:i:s P');\r\n });\r\n}\r\n```\r\n\r\nFor the models I made a trait that overrides two methods.\r\n\r\nOverriding the `asDateTime` method lets the carbon instance be modified so the changes are accessible in the code.\r\n\r\nOverriding the `serializeDate` method makes the carbon instances use `jsonSerialize()` instead of the format provided by the models.\r\n\r\nHasTimezone.php\r\n```php\r\nnamespace App\\Traits;\r\n\r\nuse Illuminate\\Support\\Carbon;\r\n\r\n/**\r\n * App\\Traits\\HasTimezone\r\n */\r\ntrait HasTimezone\r\n{\r\n /**\r\n * Return a timestamp as DateTime object with a timezone.\r\n *\r\n * @param mixed $value\r\n * @return \\Illuminate\\Support\\Carbon\r\n */\r\n protected function asDateTime($value)\r\n {\r\n $carbon = parent::asDateTime($value);\r\n return $carbon->tz(config('tenant.timezone'));\r\n }\r\n\r\n /**\r\n * Prepare a date for array / JSON serialization.\r\n *\r\n * @param \\DateTimeInterface $date\r\n * @return string\r\n */\r\n protected function serializeDate(\\DateTimeInterface $date)\r\n {\r\n return $date->jsonSerialize();\r\n }\r\n}\r\n```\r\n\r\nExample\r\n```php\r\n$t = \\App\\Ticket::first();\r\n$t->created_at\r\n=> Illuminate\\Support\\Carbon @1520959699 {#52\r\n date: 2018-03-13 12:48:19.0 America/New_York (-04:00),\r\n }\r\n\r\n$t->toJson(JSON_PRETTY_PRINT)\r\n=> \"\"\"\r\n {\\n\r\n ...\r\n \"created_at\": \"2018-03-13 12:48:19 -04:00\",\\n\r\n \"updated_at\": \"2018-04-06 12:48:20 -04:00\",\\n\r\n }\r\n \"\"\"\r\n\r\n```\r\n\r\nThis is working for me, for now. I'm sure I'll find something it breaks but I hope it helps others struggling with this.\r\n\r\nEdit 4/10/2018: This wasn't serializing the relation carbon instance correctly, so I looked through the laravel framework code some more and decided to override `serializeDate` instead. Again, it doesn't seem to break anything.", "created_at": "2018-04-06T16:54:44Z" }, { "body": "When casting to an array, all date serialization is handled by HasAttributes->serializeDate\r\n\r\n### To cast dates to a timestamp integer on a single model:\r\n```\r\n protected function serializeDate(\\DateTimeInterface $date)\r\n {\r\n return intval($date->format('U'));\r\n }\r\n```\r\n### The problems with Carbon::serializeUsing:\r\nFrom what I see, the current implementation of Carbon::serializeUsing is only applied in jsonSerialize, and should thus be called Carbon::jsonSerializeUsing.\r\n\r\nWe could change serializeDate() to use $date->serialize(), but if serializeUsing() is not set, that will serialize the whole object while we just want to format the time. That is probably why HasAttributes->serializeDate is avoiding it.\r\n\r\nAlso, Carbon::$serializer is protected, so to make our serialization conditional, we need some extra tweaks to check it from Laravel.\r\n\r\nWith patch #26382, I can finally do this:\r\n```\r\n<?php\r\n\r\nnamespace App\\Providers;\r\n\r\nuse Illuminate\\Support\\ServiceProvider;\r\nuse Illuminate\\Support\\Carbon;\r\n\r\nclass AppServiceProvider extends ServiceProvider\r\n{\r\n /**\r\n * Bootstrap any application services.\r\n *\r\n * @return void\r\n */\r\n public function boot()\r\n {\r\n Carbon::serializeUsing(function ($carbon) {\r\n return intval($carbon->format('U'));\r\n });\r\n }\r\n\r\n /**\r\n * Register any application services.\r\n *\r\n * @return void\r\n */\r\n public function register()\r\n {\r\n //\r\n }\r\n}\r\n\r\n```", "created_at": "2018-11-04T11:11:20Z" }, { "body": "Hi, I read this whole thread and it seems many different intents and expectations are mentioned. And all of them are not bugs, then some can yet be handled.\r\n\r\n# Cast to string such as `{{$user->created_at}}`\r\n\r\nThe easier one: `{{$user->created_at}}` the general case here is about implicit cast of the Carbon object into string. It does not rely to Laravel at all. It follows rules you can find in the Carbon documentation: https://carbon.nesbot.com/docs/#api-formatting\r\n\r\nHere you should avoid to change globally the way Carbon objects are casted to strings, you should rather explicitly format dates in your templates according to users and app settings, the context of the page and so on: `{{ $user->created_at->copy()->tz($userTimezone)->locale($userLanguage)->calendar() }}` or choose a precise isoFormat/format then if you use the same formats in many places, create macros: https://carbon.nesbot.com/docs/#user-settings\r\n\r\n`->copy()` allow you to reuse the original created_at later in your template.\r\n\r\n@Dewbud it's also the better way to handle a given timezone rather than overriding `asDateTime`.\r\n\r\n# Carbon::serializeUsing\r\n\r\nAbout `Carbon::serializeUsing`, indeed the name is not exact, it's inherited from the original method that existed before in Laravel if I remember correctly, it should be `Carbon::jsonEncodeUsing` because it's dedicated to `json_encode` conversions. So it suits for `jsonSerialize` and `toJson`, but not so well for `toArray`. This point should probably be adjusted in Laravel, because right now `jsonSerialize` = `toArray`, then while `\"2018-03-13T12:48:19Z\"` is a perfect match for a JSON output (as `new Date()` in JS will natively understand it), it's not for an SQL database or other APIs and so `toArray` should be less opinionated than `jsonSerialize`, but the current default format with no timezone (`\"2018-03-13 12:48:19\"`) is still a good choice IMHO for the `toArray` output.\r\n\r\n# serializeDate\r\n\r\nThe `serializeDate` that can be overridden at model level has the same problem as above, it's for both `toArray` and `jsonSerialize` but as there is no particular reason to convert dates the same way for both, the tool we miss here is separated methods `serializeDateForArray` and `serializeDateForJson`. `serializeDateForArray` would use the existing default format (`\"2018-03-13 12:48:19\"`), while `serializeDateForJson` would use the serialization passed to `Carbon::serializeUsing()` then only if there is no custom serializer, then it could fallback to `->serializeDateForArray()`\r\n\r\n# Solution\r\n\r\nThe solution would imply breaking change (additional parameter for `toArray`, `attributesToArray` and `relationsToArray`) so `jsonSerialize` could call `toArray` with a closure to be applied on each value handled recursively by `toArray` so custom output by type could be handled in this closure. This solution is the cleanest IMHO but as it's breaking, it has no chance to be implemented until Laravel v5.8/5.9. So until this we have to work around the issue:\r\n\r\n# Work-around\r\n\r\nAs @Dewbud suggested, a trait is a easy way to apply a custom serialization to the models you it in and it does not only apply to timezone, it applies to any formatting needed for JSON output, so I recommend the following trick:\r\n\r\n```php\r\nnamespace App\\Traits;\r\n\r\nuse Illuminate\\Support\\Carbon;\r\n\r\n/**\r\n * App\\Traits\\MyCustomJsonSerialization\r\n */\r\ntrait MyCustomJsonSerialization\r\n{\r\n protected $jsonSerializationInProgress = false;\r\n\r\n /**\r\n * Prepare a date for array / JSON serialization.\r\n *\r\n * @param \\DateTimeInterface $date\r\n * @return string\r\n */\r\n protected function serializeDate(\\DateTimeInterface $date)\r\n {\r\n if ($this->jsonSerializationInProgress) {\r\n // Here you can return anything you need for JSON objects ($date->toJSON), timestamp, etc.\r\n // You can also change the timezone, set the locale to handle internationalization, etc.\r\n return $date->format('Y-m-d\\TH:i:s');\r\n }\r\n\r\n return parent::serializeDate($date);\r\n }\r\n\r\n /**\r\n * Convert the object into something JSON serializable.\r\n *\r\n * @return array\r\n */\r\n protected function jsonSerialize(\\DateTimeInterface $date)\r\n {\r\n $this->jsonSerializationInProgress = true;\r\n $array = $this->toArray();\r\n $this->jsonSerializationInProgress = false;\r\n\r\n return $array;\r\n }\r\n}\r\n```\r\n\r\nI know such a boolean flag is not ideal avoid getting in a mess with `toArray` native usages and should provides a precise customization without having to change a thing in the framework code.\r\n\r\nHope it can help.", "created_at": "2018-12-13T10:36:22Z" }, { "body": "Just as another note, I've also run into this when building an API using `JsonResource` responses. I would have assumed one of the main use cases for global date formatting is for API requests and responses.\r\n\r\nThe default `artisan make:resource Test` command builds a `JsonResource` like the following:\r\n\r\n```php\r\nclass Test extends JsonResource\r\n{\r\n /**\r\n * Transform the resource into an array.\r\n *\r\n * @param \\Illuminate\\Http\\Request $request\r\n * @return array\r\n */\r\n public function toArray($request)\r\n {\r\n return parent::toArray($request); // created_at is formatted to string with incorrect date format\r\n }\r\n}\r\n```\r\n\r\nAny dates here will be converted with strings with the default Laravel (in my case incorrect) formatting.\r\n\r\nHowever if manually building the array they are instead formatted correctly!\r\n\r\n```php\r\nclass Test extends JsonResource\r\n{\r\n /**\r\n * Transform the resource into an array.\r\n *\r\n * @param \\Illuminate\\Http\\Request $request\r\n * @return array\r\n */\r\n public function toArray($request)\r\n {\r\n return [\r\n 'created_at' => $this->created_at, // Now created_at is a carbon class and correct date format is honoured\r\n ];\r\n }\r\n}\r\n```\r\n\r\nHowever it's pretty tedious to have to manually define every single field in the `toArray()` method when 99% of the time you probably just want to serialize the entire model.\r\n\r\nMy work-around:\r\n\r\n```php\r\nclass Test extends JsonResource\r\n{\r\n /**\r\n * Transform the resource into an array.\r\n *\r\n * @param \\Illuminate\\Http\\Request $request\r\n * @return array\r\n */\r\n public function toArray($request)\r\n {\r\n\r\n $arr = parent::toArray($request);\r\n\r\n // toArray transforms the date attributes to strings, but with the wrong format!\r\n // Override dates here with a new carbon instance to honour global format in jsonSerialize()\r\n if ($this->resource->getDates()) {\r\n foreach ($this->resource->getDates() as $date_field) {\r\n $arr[$date_field] = $this->{$date_field};\r\n }\r\n }\r\n\r\n return $arr;\r\n }\r\n}\r\n\r\n```\r\n\r\nWould be nice to see a proper solution to this in 5.8 :)\r\n", "created_at": "2019-01-14T15:01:31Z" }, { "body": "`serializeUsing` is now deprecated by Carbon so I'm closing this as it's no longer recommended to use this: https://github.com/briannesbitt/Carbon/issues/1870\r\n\r\nIn Laravel 7, a new default for date serialization will be used: https://github.com/laravel/framework/pull/30715", "created_at": "2019-12-02T14:39:25Z" }, { "body": "Note than a better replacement for `serializeUsing` could be:\r\n```php\r\nDate::swap(new \\Carbon\\Factory([\r\n 'toJsonFormat' => function ($date) {\r\n return $date->getTimestamp();\r\n },\r\n]));\r\n```\r\n(or `FactoryImmutable` for immutable dates).\r\n\r\nThis will change only `Date` so `Carbon` instances created internally by Laravel. This one won't change globally every `Carbon` instances, so it won't break other libraries that use `Carbon` but you still have to check if none of your installed libraries related to Laravel has some `json_encode($aLaravelDate)` in its code.", "created_at": "2019-12-07T10:53:36Z" }, { "body": "@kylekatarnls Tried this code inside AppServiceProvider's boot method but it doesn't change the format returned by Model timestamps in Laravel 8. Any idea?", "created_at": "2021-05-13T03:41:54Z" }, { "body": "What is the $casts of your model (e.g. are you sure you have Carbon instances in the furst place?) Then var_dump/inspect your instance before to return them as JSON to see if it as the correct toJsonFormat at this point (e.g. if the swap() is correctly applied).", "created_at": "2021-05-13T11:18:31Z" } ], "number": 21703, "title": "Carbon serializeUsing not applicable when serializing model instance" }
{ "body": "Regarding #21703\r\n\r\nFrom what I see, the current implementation of `Carbon::serializeUsing` is only applied in `$carbon->jsonSerialize()`, and should have been called `Carbon::jsonSerializeUsing`.\r\n\r\nWe could change `HasAttributes->serializeDate()` to use `$date->serialize()`, but if `Carbon::$serializer` is not set, that will serialize the whole object while we just want to format the time. That is probably why `HasAttributes->serializeDate()` has been avoiding it.\r\n\r\nThis fix will fallback to the current behaviour if `Carbon::$serializer` is not set.\r\n", "number": 26382, "review_comments": [ { "body": "These should probably still call `getDateFormat()` to keep current behavior.", "created_at": "2018-11-04T11:53:20Z" }, { "body": "I think the practice is to use short int cast `(int) $carbon->format('U')` in this project.", "created_at": "2018-11-06T17:14:04Z" }, { "body": "Is not the opposite?\r\n`$this->assertEquals('2018-11-05 09:26', $model->attributesToArray()['created_at']);`", "created_at": "2018-11-06T17:14:51Z" }, { "body": "Fixed", "created_at": "2018-11-06T18:14:12Z" }, { "body": "Fixed and switched to assertSame", "created_at": "2018-11-06T18:14:31Z" }, { "body": "If you renew this PR for 5.8, you can have one less condition with:\r\n```php\r\nif ($this->dateFormat || !Carbon::getSerializer()) {\r\n return $date->format($this->getDateFormat());\r\n}\r\nreturn $date->serialize();\r\n```", "created_at": "2018-12-13T09:21:47Z" }, { "body": "Please avoid to create gaps between Laravel Carbon and the original Carbon class. For example if someone here want to use CarbonImmutable, then, he loose your feature.\r\n\r\nYou should first propose the change to the Carbon project in a standard way that would fit not only for Laravel but for any PHP app or other framework that can have this problematic.", "created_at": "2018-12-13T09:25:48Z" } ], "title": "[5.7] Fixes for Carbon serialization" }
{ "commits": [ { "message": "Fixes for Carbon serialization" }, { "message": "Fixed coding style" }, { "message": "Use existing function when possible" }, { "message": "Added test case" }, { "message": "Style fix" }, { "message": "Unset serializer after testing" }, { "message": "Switched to assertSame and fixed expected/actual order" } ], "files": [ { "diff": "@@ -841,7 +841,13 @@ protected function asTimestamp($value)\n */\n protected function serializeDate(DateTimeInterface $date)\n {\n- return $date->format($this->getDateFormat());\n+ if ($this->dateFormat) {\n+ return $date->format($this->getDateFormat());\n+ } elseif (Carbon::getSerializer()) {\n+ return $date->serialize();\n+ } else {\n+ return $date->format($this->getDateFormat());\n+ }\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php", "status": "modified" }, { "diff": "@@ -6,5 +6,27 @@\n \n class Carbon extends BaseCarbon\n {\n- //\n+ /**\n+ * Return protected value $serializer.\n+ *\n+ * @return callable|null\n+ */\n+ public static function getSerializer()\n+ {\n+ return static::$serializer;\n+ }\n+\n+ /**\n+ * Return a serialized string of the instance.\n+ *\n+ * @return string\n+ */\n+ public function serialize()\n+ {\n+ if (static::$serializer) {\n+ return call_user_func(static::$serializer, $this);\n+ }\n+\n+ return serialize($this);\n+ }\n }", "filename": "src/Illuminate/Support/Carbon.php", "status": "modified" }, { "diff": "@@ -447,6 +447,21 @@ public function testTimestampsAreCreatedFromStringsAndIntegers()\n $this->assertInstanceOf(Carbon::class, $model->created_at);\n }\n \n+ public function testSerializeDate()\n+ {\n+ $model = new EloquentDateModelStub;\n+ $model->created_at = '2018-11-05 09:26:00';\n+ $this->assertSame('2018-11-05 09:26:00', $model->attributesToArray()['created_at']);\n+ Carbon::serializeUsing(function ($carbon) {\n+ return (int) $carbon->format('U');\n+ });\n+ $this->assertSame(1541409960, $model->attributesToArray()['created_at']);\n+ $model->setDateFormat('Y-m-d H:i');\n+ $model->created_at = '2018-11-05 09:26';\n+ $this->assertSame('2018-11-05 09:26', $model->attributesToArray()['created_at']);\n+ Carbon::serializeUsing(null);\n+ }\n+\n public function testFromDateTime()\n {\n $model = new EloquentModelStub;", "filename": "tests/Database/DatabaseEloquentModelTest.php", "status": "modified" } ] }
{ "body": "In L5.5, 5.6 I experience an issue with _resolving_ callbacks on dependencies registered in the container with an interface class as abstract. A demonstration:\r\n\r\nHaving some interface \r\n\r\n```php\r\nIBar {}\r\n```\r\n\r\nand an implementation \r\n\r\n```php\r\nFoo implements IBar {}\r\n```\r\n\r\nregistered (here as a singleton) in the container \r\n\r\n```php\r\napp()->singleton( IBar::class, Foo::class );\r\n```\r\n\r\nwith a _resolving_ callback \r\n\r\n```php\r\napp()->resolving( IBar::class, $callback );\r\n```\r\n\r\nfires `$callback` **twice** when the abstract is resolved!\r\n\r\nThis is probably because:\r\n\r\n1. When the abstract `IBar` resolves, it triggers the callback\r\n2. To resolve `IBar`, `Foo` must be constructed. As `Foo` implements `IBar`, it triggers the `resolving` event too! \r\n\r\nThis problem can be omitted when avoiding Laravel's container to build Foo by registering a callback instead:\r\n\r\n```php\r\napp()->singleton( IBar::class, f(){ return new Foo; } )\r\n```\r\n\r\nBut this abolishes the ease of automatic dependency injection. \r\n\r\nSo... can we solve this issue by not firing the `resolving()` callback when we are building the implementation of an interface that the callback is registered for? ", "comments": [ { "body": "There has been some attempts to fix this previously in https://github.com/laravel/framework/pull/23290 but it wasn't merged. Perhaps send a PR with your suggested changes?", "created_at": "2018-03-26T12:39:54Z" }, { "body": "Fine, I'll submit a PR these days that will address this issue. \r\n\r\nThis test triggers the problem:\r\n\r\n```php\r\n public function testResolvingCallbacksAreCalledOnceForImplementations()\r\n {\r\n $invocations = 0;\r\n $container = new Container;\r\n $container->resolving( IContainerContractStub::class, function( ) use ( &$invocations ) {\r\n $invocations++;\r\n } );\r\n $container->bind(IContainerContractStub::class, ContainerImplementationStub::class );\r\n\r\n $this->assertEquals( 0, $invocations );\r\n $container->make( IContainerContractStub::class );\r\n $this->assertEquals( 1, $invocations );\r\n }\r\n```", "created_at": "2018-03-26T12:46:58Z" }, { "body": "\"... these days...\"\r\n#23701 ", "created_at": "2018-03-26T14:15:42Z" }, { "body": "Fixed in 5.8.", "created_at": "2019-01-10T15:13:14Z" }, { "body": "The bug is still in 5.8.12", "created_at": "2019-04-21T16:26:57Z" } ], "number": 23699, "title": "resolving() events on interfaces are called twice " }
{ "body": "Fixes #23699 by tracking abstracts that are currently being resolved. \r\nIf an object is built that is an `instanceof` of an object that is already on the stack, firing the resolving() callbacks is inhibited. \r\nThese callbacks are fired eventually when the `instanceof` object is resolved. \r\n\r\nThis is a continuation of #23701.\r\n\r\nI've ran some benchmarks on the adaptions of the `ContainerTest`s that interacts a lot with the `$resolveStack` because of the nested interfaces. \r\nE.g., for `testResolvingCallbacksAreCalledForNestedDependencies` an adaption that resolves many times: \r\n\r\n```php\r\n$container = new Container;\r\n$resolving_dependency_interface_invocations = 0;\r\n$resolving_dependency_implementation_invocations = 0;\r\n$resolving_dependent_invocations = 0;\r\n\r\n$container->bind(IContainerContractStub::class, ContainerImplementationStub::class);\r\n\r\n$container->resolving(IContainerContractStub::class, function () use (&$resolving_dependency_interface_invocations) {\r\n $resolving_dependency_interface_invocations++;\r\n});\r\n\r\n$container->resolving(ContainerImplementationStub::class, function () use (&$resolving_dependency_implementation_invocations) {\r\n $resolving_dependency_implementation_invocations++;\r\n});\r\n\r\n$container->resolving(ContainerNestedDependentStubTwo::class, function () use (&$resolving_dependent_invocations) {\r\n $resolving_dependent_invocations++;\r\n});\r\n\r\nfor($i = 0; $i < 100; $i++){\r\n $container->make(ContainerNestedDependentStubTwo::class, compact('i'));\r\n $container->make(ContainerNestedDependentStubTwo::class, compact('i'));\r\n}\r\n```\r\n\r\nI've also adapted and benched:\r\n- `testResolvingCallbacksAreCalledOnceForImplementations`\r\n- `testResolvingCallbacksAreCalledForSpecificAbstracts`\r\n\r\nhttps://github.com/tomlankhorst/framework/tree/resolve-stack-bench\r\nhttps://github.com/tomlankhorst/framework/pull/1/files\r\n\r\nUsing PHPBench, 10 revs, 10 its (for a total of 10.000 calls per resolve).\r\n`phpbench run tests/Container/ContainerTest.php --tag=no_resolve_stack --store --retry-threshold=4 --revs=10 --iterations=10`\r\n\r\nComparing this to the current master without the resolve stack (that shows the erroneous behaviour of #23699):\r\n```\r\nphpbench report --uuid=tag:no_resolve_stack --uuid=tag:resolve_stack --report='{extends: compare, compare: tag, cols: ['subject']}'\r\n+-------------------------------------------------------+---------------------------+------------------------+\r\n| subject | tag:no_resolve_stack:mean | tag:resolve_stack:mean |\r\n+-------------------------------------------------------+---------------------------+------------------------+\r\n| testResolvingCallbacksAreCalledForSpecificAbstracts | 3,879.860μs | 4,191.810μs |\r\n| testResolvingCallbacksAreCalledOnceForImplementations | 8,213.690μs | 9,426.250μs |\r\n| testResolvingCallbacksAreCalledForNestedDependencies | 54,412.570μs | 60,539.490μs |\r\n+-------------------------------------------------------+---------------------------+------------------------+\r\n```\r\nSo, there's an average performance impact of 10% on resolving. I realize this impact is significant but I also realize that the current behaviour is not acceptable.", "number": 26112, "review_comments": [ { "body": "Not sure we have to resolve the last element on each loop. I would make sense to extract it to a variable before.\r\nOr even slicing the resolveStack.", "created_at": "2018-10-13T15:48:55Z" }, { "body": "This would also work:\r\n```php\r\nreturn collect($this->resolveStack)->slice(0, -1)->contains(function ($resolving) {\r\n $object instanceof $resolving;\r\n});\r\n```", "created_at": "2018-10-13T15:49:20Z" }, { "body": "It does, but it's a big performance hit. \r\n\r\n```\r\nphpbench run tests/Container/ContainerTest.php --revs=100\r\n+-------------------------------------------------------+------------------+-------------------+\r\n| subject | tag:collect:mean | tag:original:mean |\r\n+-------------------------------------------------------+------------------+-------------------+\r\n| testResolvingCallbacksAreCalledForSpecificAbstracts | 5,917.960μs | 4,046.610μs |\r\n| testResolvingCallbacksAreCalledOnceForImplementations | 23,971.640μs | 9,072.640μs |\r\n| testResolvingCallbacksAreCalledForNestedDependencies | 99,831.230μs | 61,386.800μs |\r\n+-------------------------------------------------------+------------------+-------------------+\r\n```\r\n`original` is this PR, `collect` is your alternative. \r\n\r\nNote that the loop breaks through return as soon as a match is found. ", "created_at": "2018-10-13T16:58:37Z" } ], "title": "[5.8] Track abstracts being resolved, fire resolving events once" }
{ "commits": [ { "message": "Test resolving() callbacks being fired once for implementations" }, { "message": "Track abstract resolve stack and inhibit resolving callback when is already on this stack" }, { "message": "StyleCI" }, { "message": "Missing array_pop" }, { "message": "Check if resolve is pending when firing callbacks" }, { "message": "More extensive test" }, { "message": "Performance improvement" } ], "files": [ { "diff": "@@ -84,6 +84,13 @@ class Container implements ArrayAccess, ContainerContract\n */\n protected $buildStack = [];\n \n+ /**\n+ * The stack of de-aliased abstractions currently being resolved.\n+ *\n+ * @var array\n+ */\n+ protected $resolveStack = [];\n+\n /**\n * The parameter override stack.\n *\n@@ -636,6 +643,8 @@ protected function resolve($abstract, $parameters = [])\n {\n $abstract = $this->getAlias($abstract);\n \n+ $this->resolveStack[] = $abstract;\n+\n $needsContextualBuild = ! empty($parameters) || ! is_null(\n $this->getContextualConcrete($abstract)\n );\n@@ -644,6 +653,8 @@ protected function resolve($abstract, $parameters = [])\n // just return an existing instance instead of instantiating new instances\n // so the developer can keep using the same objects instance every time.\n if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {\n+ array_pop($this->resolveStack);\n+\n return $this->instances[$abstract];\n }\n \n@@ -682,6 +693,7 @@ protected function resolve($abstract, $parameters = [])\n $this->resolved[$abstract] = true;\n \n array_pop($this->with);\n+ array_pop($this->resolveStack);\n \n return $object;\n }\n@@ -1048,7 +1060,7 @@ protected function getCallbacksForType($abstract, $object, array $callbacksPerTy\n $results = [];\n \n foreach ($callbacksPerType as $type => $callbacks) {\n- if ($type === $abstract || $object instanceof $type) {\n+ if (($type === $abstract || $object instanceof $type) && ! $this->pendingInResolveStack($object)) {\n $results = array_merge($results, $callbacks);\n }\n }\n@@ -1070,6 +1082,24 @@ protected function fireCallbackArray($object, array $callbacks)\n }\n }\n \n+ /**\n+ * Check if object or a generalisation is pending in the resolve stack.\n+ *\n+ * @param object $object\n+ *\n+ * @return bool\n+ */\n+ protected function pendingInResolveStack($object)\n+ {\n+ foreach ($this->resolveStack as $resolving) {\n+ if ($resolving !== end($this->resolveStack) && $object instanceof $resolving) {\n+ return true;\n+ }\n+ }\n+\n+ return false;\n+ }\n+\n /**\n * Get the container's bindings.\n *", "filename": "src/Illuminate/Container/Container.php", "status": "modified" }, { "diff": "@@ -377,6 +377,64 @@ public function testResolvingCallbacksAreCalledForType()\n $this->assertEquals('taylor', $instance->name);\n }\n \n+ public function testResolvingCallbacksAreCalledOnceForImplementations()\n+ {\n+ $container = new Container;\n+ $resolving_contract_invocations = 0;\n+ $after_resolving_contract_invocations = 0;\n+ $resolving_implementation_invocations = 0;\n+ $after_resolving_implementation_invocations = 0;\n+\n+ $container->resolving(IContainerContractStub::class, function () use (&$resolving_contract_invocations) {\n+ $resolving_contract_invocations++;\n+ });\n+ $container->afterResolving(IContainerContractStub::class, function () use (&$after_resolving_contract_invocations) {\n+ $after_resolving_contract_invocations++;\n+ });\n+ $container->resolving(ContainerImplementationStub::class, function () use (&$resolving_implementation_invocations) {\n+ $resolving_implementation_invocations++;\n+ });\n+ $container->afterResolving(ContainerImplementationStub::class, function () use (&$after_resolving_implementation_invocations) {\n+ $after_resolving_implementation_invocations++;\n+ });\n+ $container->bind(IContainerContractStub::class, ContainerImplementationStub::class);\n+ $container->make(IContainerContractStub::class);\n+\n+ $this->assertEquals(1, $resolving_contract_invocations);\n+ $this->assertEquals(1, $after_resolving_contract_invocations);\n+ $this->assertEquals(1, $resolving_implementation_invocations);\n+ $this->assertEquals(1, $after_resolving_implementation_invocations);\n+ }\n+\n+ public function testResolvingCallbacksAreCalledForNestedDependencies()\n+ {\n+ $container = new Container;\n+ $resolving_dependency_interface_invocations = 0;\n+ $resolving_dependency_implementation_invocations = 0;\n+ $resolving_dependent_invocations = 0;\n+\n+ $container->bind(IContainerContractStub::class, ContainerImplementationStub::class);\n+\n+ $container->resolving(IContainerContractStub::class, function () use (&$resolving_dependency_interface_invocations) {\n+ $resolving_dependency_interface_invocations++;\n+ });\n+\n+ $container->resolving(ContainerImplementationStub::class, function () use (&$resolving_dependency_implementation_invocations) {\n+ $resolving_dependency_implementation_invocations++;\n+ });\n+\n+ $container->resolving(ContainerNestedDependentStubTwo::class, function () use (&$resolving_dependent_invocations) {\n+ $resolving_dependent_invocations++;\n+ });\n+\n+ $container->make(ContainerNestedDependentStubTwo::class);\n+ $container->make(ContainerNestedDependentStubTwo::class);\n+\n+ $this->assertEquals(4, $resolving_dependency_interface_invocations);\n+ $this->assertEquals(4, $resolving_dependency_implementation_invocations);\n+ $this->assertEquals(2, $resolving_dependent_invocations);\n+ }\n+\n public function testUnsetRemoveBoundInstances()\n {\n $container = new Container;\n@@ -951,6 +1009,19 @@ public function testResolvingCallbacksShouldBeFiredWhenCalledWithAliases()\n $this->assertEquals('taylor', $instance->name);\n }\n \n+ public function testInterfaceResolvingCallbacksShouldBeFiredWhenCalledWithAliases()\n+ {\n+ $container = new Container;\n+ $container->alias(IContainerContractStub::class, 'foo');\n+ $container->resolving(IContainerContractStub::class, function ($object) {\n+ return $object->name = 'taylor';\n+ });\n+ $container->bind('foo', ContainerImplementationStub::class);\n+ $instance = $container->make('foo');\n+\n+ $this->assertEquals('taylor', $instance->name);\n+ }\n+\n public function testMakeWithMethodIsAnAliasForMakeMethod()\n {\n $mock = $this->getMockBuilder(Container::class)\n@@ -1126,6 +1197,18 @@ public function __construct(IContainerContractStub $impl)\n }\n }\n \n+class ContainerDependentStubTwo\n+{\n+ public $implA;\n+ public $implB;\n+\n+ public function __construct(IContainerContractStub $implA, IContainerContractStub $implB)\n+ {\n+ $this->implA = $implA;\n+ $this->implB = $implB;\n+ }\n+}\n+\n class ContainerNestedDependentStub\n {\n public $inner;\n@@ -1136,6 +1219,16 @@ public function __construct(ContainerDependentStub $inner)\n }\n }\n \n+class ContainerNestedDependentStubTwo\n+{\n+ public $inner;\n+\n+ public function __construct(ContainerDependentStubTwo $inner)\n+ {\n+ $this->inner = $inner;\n+ }\n+}\n+\n class ContainerDefaultValueStub\n {\n public $stub;", "filename": "tests/Container/ContainerTest.php", "status": "modified" } ] }
{ "body": "When attempting to use delete() or update() on an eloquent model you can not use any joins because you will get an ambiguous column name error on updated_at. This is because the Eloquent/Builder.php does not prefix updated_at with the proper table name. I attempted to do a pull request for this, but the issue is further complicated by Arr::add (used in addUpdatedAtColumn) doing automatic dot notation exploding. This prevents me from adding a table.columnName string similar to the operation of SoftDeletes trait.\n\nLaravel 5.2\n", "comments": [ { "body": "You can disable $timestamps on specific models by doing this: `public $timestamps=false`.\n\nOne question though, why are you using join when updating or deleting a row? Can you describe in detail the exact scenario?\n", "created_at": "2016-06-08T06:12:12Z" }, { "body": "There was an attempt to fix a similar issue: https://github.com/laravel/framework/pull/13519\nBut end up causing problems with Postgres and also sqlite: https://github.com/laravel/framework/issues/13707\n\nSo the fix was reverted: https://github.com/laravel/framework/commit/d12c4bbf8b09ff9cf916a8e54b15e43752f31350\n\nI don't think there'll be an easy solution for this as using a fully qualified column name `table.column` has different rules between drivers which requires having different implementations.\n", "created_at": "2016-06-17T23:58:27Z" }, { "body": "This seems like a pretty major issue. Maybe I'm using Eloquent wrong, but with just a simple use of Eloquent like this: `$model->childRelationship()->update(['some_column' => $value]);` fails.\n", "created_at": "2016-06-23T20:39:41Z" }, { "body": "Yeah it is definitely an issue. The commit referenced by @themsaid was mine, and while I haven't had the time to revisit this issue I am going to devote the time to look for a fix regardless. Anyone who wants to work together to find a solution, you can find contact info on my profile. Really determined to get this resolved.\n", "created_at": "2016-07-15T22:53:47Z" }, { "body": "The only thing that comes to the top of my head is in the Eloquent Model's `getQualifiedUpdatedAtColumn` method, checking which driver is being used and determine the value that way.\n\nThe more long-term way would probably be defining the Eloquent Builder as an abstract class and then each driver has its own implementation of the `addUpdatedAtColumn` method. Of course, that would require Laravel to determine the proper Builder at runtime. \n", "created_at": "2016-07-15T23:12:28Z" }, { "body": "@samrap Did you get the chance to open a PR?\n", "created_at": "2016-09-11T09:20:56Z" }, { "body": "@themsaid Unfortunately not but I'd be happy to work together with you in order to develop a solution. From what I've discovered with this bug it's a much larger issue than it sounds. \n", "created_at": "2016-09-12T17:06:40Z" }, { "body": "@themsaid I don't have experience outside of MySQL but if I get a list of the different qualified column name rules between drivers I think I can handle fixing this issue on my own.\n", "created_at": "2016-09-12T17:11:54Z" }, { "body": "This seems to be an edge case and there hasn't been a fix yet.\nBut we can always attempt to solve with the Query Builder. Join the tables and manually set deleted_at and updated_at.\n", "created_at": "2016-10-12T15:21:24Z" }, { "body": "@trandaihung that's what I personally do, I tried to fix before but every database driver has different rules for the qualified column name which makes this change pretty major.\n", "created_at": "2016-10-13T14:13:54Z" }, { "body": "Aw, I've to use `Carbon::now()`", "created_at": "2017-01-03T08:17:32Z" }, { "body": "Can a method ->withoutTimestamps() be added for this particular case?", "created_at": "2017-01-18T13:32:26Z" }, { "body": "I've ran into this issue today as well.", "created_at": "2017-02-03T01:49:33Z" }, { "body": "@srmklive the join in my case is generated because I have a belongsToMany relation in my model. When soft-deleting the model, the relation also gets soft-deleted.\r\n\r\n@samrap I noticed however the deleted_at column is properly qualified in the delete query, where the updated_at column isn't. Is this the also the case for other scenario's? Why isn't updated_at qualified the same way as the deleted_at column?", "created_at": "2017-06-01T08:17:01Z" }, { "body": "@walterdeboer My PR to fix the issue explains what is going on in-depth: https://github.com/laravel/framework/pull/13519\r\n\r\nUnfortunately, as @themsaid mentioned above, the PR caused a problem when using the Postgres and Sqlite drivers.", "created_at": "2017-06-01T20:09:42Z" }, { "body": "Have this issue as well", "created_at": "2017-07-27T13:00:06Z" }, { "body": "I'm able to sidestep the ambiguity of the updated_at columns in Laravel 5.3 with a toBase() call on the Eloquent builder before doing an update.", "created_at": "2017-08-21T17:14:28Z" }, { "body": "Same problem here. As a workaround had to pluck the ids for the result that i want to update with a select and then update the model with the given ids.\r\n\r\n```\r\n $ids = User::filter($filter)->pluck('id'); //in filter i have a join with an other model that has timestamps\r\n User::whereIn('id',$ids)->update(['field' => 'value']);\r\n```", "created_at": "2017-09-01T10:39:15Z" }, { "body": "Same issue here", "created_at": "2017-09-21T07:21:03Z" }, { "body": "This issue is affecting be on L5.4.36, and also should affect L5.5\r\n\r\n```\r\n$query->join(/* join some table with updated_at */)\r\n->delete()\r\n```\r\n\r\nThis will bring ambiguous column error for `updated_at`", "created_at": "2017-10-30T18:29:15Z" }, { "body": "We're all well aware this issue exists. Can we refrain from unconstructive comments of the type \"same thing happening here\" from this point forward? There are lots of people subscribed to these issue threads that don't need to be getting emails every time someone reconfirms this is a bug 😬 ", "created_at": "2017-10-31T00:12:12Z" }, { "body": "I am using the L5.4.36 and the workaround provided from @Turaylon is not feasible as it could get on the millions of ids on the current project and also the update values come from other tables that will be deprecated\r\n\r\nI ended up using a ReflectionClass to \"disable\" the timestamps for the model on the source model for the query builder:\r\n```\r\n$instance = new \\App\\Models\\Model;\r\n$reflection = new ReflectionClass(\\App\\Models\\Model::class);\r\n$reflection->getProperty('timestamps')->setValue($instance, null);\r\n\r\n$instance->/* wheres(), joins() and so on */->update([/* update values */])\r\n```\r\nThis is not a long term approach or solution, but it bypass the timestamp modification. by not updating that field at all.\r\n\r\nA driver aware implementation (or an alternative to the array splitting) of the `addUpdatedAtColumn` would be appreciated. \r\n", "created_at": "2018-01-30T17:53:15Z" }, { "body": "I've used method toBase() before update \r\n$someMode->relations()->someScope()->toBase()->update(['relationTable.deleted_at'=> now(), 'relationTable.updated_at' => now()]); \r\nAnd it works for me. ", "created_at": "2018-02-22T11:52:47Z" }, { "body": "@samrap I'm happy to help you solve this problem if you're still looking to solve it. I would also be hesitant about the function `getUpdatedAtColumn` knowing about the driver as that seems like an implementation detail that each driver should know how to FQ a property. Something that might be of note in this case is how each driver references properties on a join. I could see putting something like the `addUpdatedAtColumn` method a few levels deeper either in the Query Builder or at the Grammar level even. I would have to dig more but I would be keen on solving this issue with you if you're interested? ", "created_at": "2018-04-19T23:14:31Z" }, { "body": "@slaughter550 I would definitely be interested in working together on a solution. I'll shoot you an email.", "created_at": "2018-04-19T23:30:49Z" }, { "body": "Its still happening, with Lumen 5.5 any news?", "created_at": "2018-09-13T11:16:04Z" }, { "body": "#22366 updated the `SQLiteGrammar` to remove the table name from qualified columns when an UPDATE query is compiled.\r\n\r\nIf we apply the same behavior to the `PostgresGrammar`, couldn't we resubmit @samrap 's PR (#13519)?", "created_at": "2018-09-29T20:19:31Z" }, { "body": "Sound's good to me, @staudenmeir can you make such a PR ?\r\n", "created_at": "2018-10-08T14:36:09Z" }, { "body": "Will be fixed in Laravel 5.8: #26031", "created_at": "2018-10-10T15:27:36Z" }, { "body": "Thanks @staudenmeir ", "created_at": "2018-10-12T23:12:27Z" } ], "number": 13909, "title": "updated_at not fully qualified, creates ambiguous column errors" }
{ "body": "Fixes #13909 issue for Laravel 5.2\r\n\r\nP.s Fixed tests for PHP 7.2\r\n\r\n<!--\r\nPull Requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nPlease include 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": 26022, "review_comments": [], "title": "[5.5] fix(13909): fixed update_at column is ambiguous-column by qualifying …" }
{ "commits": [ { "message": "fix(13909): fixed update_at column is ambiguous-column by qualifying column name" } ], "files": [ { "diff": "@@ -822,10 +822,15 @@ protected function addUpdatedAtColumn(array $values)\n return $values;\n }\n \n- return Arr::add(\n- $values, $this->model->getUpdatedAtColumn(),\n- $this->model->freshTimestampString()\n- );\n+ if (! empty($this->getQuery()->joins)) {\n+ $column = $this->model->getQualifiedUpdatedAtColumn();\n+ } else {\n+ $column = $this->model->getUpdatedAtColumn();\n+ }\n+\n+ return array_merge($values, [\n+ $column => $this->model->freshTimestampString(),\n+ ]);\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -122,4 +122,14 @@ public function getUpdatedAtColumn()\n {\n return static::UPDATED_AT;\n }\n+\n+ /**\n+ * Get the fully qualified \"updated at\" column.\n+ *\n+ * @return string\n+ */\n+ public function getQualifiedUpdatedAtColumn()\n+ {\n+ return $this->getTable().'.'.$this->getUpdatedAtColumn();\n+ }\n }", "filename": "src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php", "status": "modified" } ] }
{ "body": "When attempting to use delete() or update() on an eloquent model you can not use any joins because you will get an ambiguous column name error on updated_at. This is because the Eloquent/Builder.php does not prefix updated_at with the proper table name. I attempted to do a pull request for this, but the issue is further complicated by Arr::add (used in addUpdatedAtColumn) doing automatic dot notation exploding. This prevents me from adding a table.columnName string similar to the operation of SoftDeletes trait.\n\nLaravel 5.2\n", "comments": [ { "body": "You can disable $timestamps on specific models by doing this: `public $timestamps=false`.\n\nOne question though, why are you using join when updating or deleting a row? Can you describe in detail the exact scenario?\n", "created_at": "2016-06-08T06:12:12Z" }, { "body": "There was an attempt to fix a similar issue: https://github.com/laravel/framework/pull/13519\nBut end up causing problems with Postgres and also sqlite: https://github.com/laravel/framework/issues/13707\n\nSo the fix was reverted: https://github.com/laravel/framework/commit/d12c4bbf8b09ff9cf916a8e54b15e43752f31350\n\nI don't think there'll be an easy solution for this as using a fully qualified column name `table.column` has different rules between drivers which requires having different implementations.\n", "created_at": "2016-06-17T23:58:27Z" }, { "body": "This seems like a pretty major issue. Maybe I'm using Eloquent wrong, but with just a simple use of Eloquent like this: `$model->childRelationship()->update(['some_column' => $value]);` fails.\n", "created_at": "2016-06-23T20:39:41Z" }, { "body": "Yeah it is definitely an issue. The commit referenced by @themsaid was mine, and while I haven't had the time to revisit this issue I am going to devote the time to look for a fix regardless. Anyone who wants to work together to find a solution, you can find contact info on my profile. Really determined to get this resolved.\n", "created_at": "2016-07-15T22:53:47Z" }, { "body": "The only thing that comes to the top of my head is in the Eloquent Model's `getQualifiedUpdatedAtColumn` method, checking which driver is being used and determine the value that way.\n\nThe more long-term way would probably be defining the Eloquent Builder as an abstract class and then each driver has its own implementation of the `addUpdatedAtColumn` method. Of course, that would require Laravel to determine the proper Builder at runtime. \n", "created_at": "2016-07-15T23:12:28Z" }, { "body": "@samrap Did you get the chance to open a PR?\n", "created_at": "2016-09-11T09:20:56Z" }, { "body": "@themsaid Unfortunately not but I'd be happy to work together with you in order to develop a solution. From what I've discovered with this bug it's a much larger issue than it sounds. \n", "created_at": "2016-09-12T17:06:40Z" }, { "body": "@themsaid I don't have experience outside of MySQL but if I get a list of the different qualified column name rules between drivers I think I can handle fixing this issue on my own.\n", "created_at": "2016-09-12T17:11:54Z" }, { "body": "This seems to be an edge case and there hasn't been a fix yet.\nBut we can always attempt to solve with the Query Builder. Join the tables and manually set deleted_at and updated_at.\n", "created_at": "2016-10-12T15:21:24Z" }, { "body": "@trandaihung that's what I personally do, I tried to fix before but every database driver has different rules for the qualified column name which makes this change pretty major.\n", "created_at": "2016-10-13T14:13:54Z" }, { "body": "Aw, I've to use `Carbon::now()`", "created_at": "2017-01-03T08:17:32Z" }, { "body": "Can a method ->withoutTimestamps() be added for this particular case?", "created_at": "2017-01-18T13:32:26Z" }, { "body": "I've ran into this issue today as well.", "created_at": "2017-02-03T01:49:33Z" }, { "body": "@srmklive the join in my case is generated because I have a belongsToMany relation in my model. When soft-deleting the model, the relation also gets soft-deleted.\r\n\r\n@samrap I noticed however the deleted_at column is properly qualified in the delete query, where the updated_at column isn't. Is this the also the case for other scenario's? Why isn't updated_at qualified the same way as the deleted_at column?", "created_at": "2017-06-01T08:17:01Z" }, { "body": "@walterdeboer My PR to fix the issue explains what is going on in-depth: https://github.com/laravel/framework/pull/13519\r\n\r\nUnfortunately, as @themsaid mentioned above, the PR caused a problem when using the Postgres and Sqlite drivers.", "created_at": "2017-06-01T20:09:42Z" }, { "body": "Have this issue as well", "created_at": "2017-07-27T13:00:06Z" }, { "body": "I'm able to sidestep the ambiguity of the updated_at columns in Laravel 5.3 with a toBase() call on the Eloquent builder before doing an update.", "created_at": "2017-08-21T17:14:28Z" }, { "body": "Same problem here. As a workaround had to pluck the ids for the result that i want to update with a select and then update the model with the given ids.\r\n\r\n```\r\n $ids = User::filter($filter)->pluck('id'); //in filter i have a join with an other model that has timestamps\r\n User::whereIn('id',$ids)->update(['field' => 'value']);\r\n```", "created_at": "2017-09-01T10:39:15Z" }, { "body": "Same issue here", "created_at": "2017-09-21T07:21:03Z" }, { "body": "This issue is affecting be on L5.4.36, and also should affect L5.5\r\n\r\n```\r\n$query->join(/* join some table with updated_at */)\r\n->delete()\r\n```\r\n\r\nThis will bring ambiguous column error for `updated_at`", "created_at": "2017-10-30T18:29:15Z" }, { "body": "We're all well aware this issue exists. Can we refrain from unconstructive comments of the type \"same thing happening here\" from this point forward? There are lots of people subscribed to these issue threads that don't need to be getting emails every time someone reconfirms this is a bug 😬 ", "created_at": "2017-10-31T00:12:12Z" }, { "body": "I am using the L5.4.36 and the workaround provided from @Turaylon is not feasible as it could get on the millions of ids on the current project and also the update values come from other tables that will be deprecated\r\n\r\nI ended up using a ReflectionClass to \"disable\" the timestamps for the model on the source model for the query builder:\r\n```\r\n$instance = new \\App\\Models\\Model;\r\n$reflection = new ReflectionClass(\\App\\Models\\Model::class);\r\n$reflection->getProperty('timestamps')->setValue($instance, null);\r\n\r\n$instance->/* wheres(), joins() and so on */->update([/* update values */])\r\n```\r\nThis is not a long term approach or solution, but it bypass the timestamp modification. by not updating that field at all.\r\n\r\nA driver aware implementation (or an alternative to the array splitting) of the `addUpdatedAtColumn` would be appreciated. \r\n", "created_at": "2018-01-30T17:53:15Z" }, { "body": "I've used method toBase() before update \r\n$someMode->relations()->someScope()->toBase()->update(['relationTable.deleted_at'=> now(), 'relationTable.updated_at' => now()]); \r\nAnd it works for me. ", "created_at": "2018-02-22T11:52:47Z" }, { "body": "@samrap I'm happy to help you solve this problem if you're still looking to solve it. I would also be hesitant about the function `getUpdatedAtColumn` knowing about the driver as that seems like an implementation detail that each driver should know how to FQ a property. Something that might be of note in this case is how each driver references properties on a join. I could see putting something like the `addUpdatedAtColumn` method a few levels deeper either in the Query Builder or at the Grammar level even. I would have to dig more but I would be keen on solving this issue with you if you're interested? ", "created_at": "2018-04-19T23:14:31Z" }, { "body": "@slaughter550 I would definitely be interested in working together on a solution. I'll shoot you an email.", "created_at": "2018-04-19T23:30:49Z" }, { "body": "Its still happening, with Lumen 5.5 any news?", "created_at": "2018-09-13T11:16:04Z" }, { "body": "#22366 updated the `SQLiteGrammar` to remove the table name from qualified columns when an UPDATE query is compiled.\r\n\r\nIf we apply the same behavior to the `PostgresGrammar`, couldn't we resubmit @samrap 's PR (#13519)?", "created_at": "2018-09-29T20:19:31Z" }, { "body": "Sound's good to me, @staudenmeir can you make such a PR ?\r\n", "created_at": "2018-10-08T14:36:09Z" }, { "body": "Will be fixed in Laravel 5.8: #26031", "created_at": "2018-10-10T15:27:36Z" }, { "body": "Thanks @staudenmeir ", "created_at": "2018-10-12T23:12:27Z" } ], "number": 13909, "title": "updated_at not fully qualified, creates ambiguous column errors" }
{ "body": "Fixes the #13909 issue for the 5.5 version.\r\n\r\n<!--\r\nPull Requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nPlease include 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": 26017, "review_comments": [ { "body": "Like this is the PHP 7.2 break in case `joins` is e.g. null?", "created_at": "2018-10-09T13:20:33Z" }, { "body": "@mfn Yep. Fixed in another PR", "created_at": "2018-10-09T15:06:32Z" }, { "body": "@mfn https://github.com/laravel/framework/pull/26022", "created_at": "2018-10-09T15:06:55Z" } ], "title": "[5.5] fix(13909): fixed update_at column is ambiguous-column by qualifying …" }
{ "commits": [ { "message": "fix(13909): fixed update_at column is ambiguous-column by qualifying column name" } ], "files": [ { "diff": "@@ -822,10 +822,15 @@ protected function addUpdatedAtColumn(array $values)\n return $values;\n }\n \n- return Arr::add(\n- $values, $this->model->getUpdatedAtColumn(),\n- $this->model->freshTimestampString()\n- );\n+ if (count($this->getQuery()->joins) > 0) {\n+ $column = $this->model->getQualifiedUpdatedAtColumn();\n+ } else {\n+ $column = $this->model->getUpdatedAtColumn();\n+ }\n+\n+ return array_merge($values, [\n+ $column => $this->model->freshTimestampString(),\n+ ]);\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -122,4 +122,14 @@ public function getUpdatedAtColumn()\n {\n return static::UPDATED_AT;\n }\n+\n+ /**\n+ * Get the fully qualified \"updated at\" column.\n+ *\n+ * @return string\n+ */\n+ public function getQualifiedUpdatedAtColumn()\n+ {\n+ return $this->getTable().'.'.$this->getUpdatedAtColumn();\n+ }\n }", "filename": "src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.4\r\n- PHP Version: 7.0\r\n- Database Driver & Version: MySQL (MariaDB 10.1)\r\n\r\n### Description:\r\nIncorrect work pagination Eloquent from join\r\n\r\n### Steps To Reproduce:\r\nElse run code\r\n```\r\nEloquent::query()->distinct()\r\n ->select('table_one.*')\r\n ->join('table_two', 'table_two.owner_id', '=', 'table_one.id', 'LEFT OUTER')\r\n->paginate(20,['table_one.id'])\r\n```\r\nthen two queries will execute\r\n```\r\nselect count(*) as aggregate from `table_one` LEFT OUTER join `table_two` on `table_two`.`owner_id` = `table_two`.`id`\r\n```\r\nand\r\n```\r\nselect distinct `table_one`.* from `table_one` LEFT OUTER join `table_two` on `table_two`.`owner_id` = `table_two`.`id`\r\n```\r\nas the first request is incorrect, it should be of the form\r\n```\r\nselect count(distinct table_one.id) as aggregate from `table_one` LEFT OUTER join `table_two` on `table_two`.`owner_id` = `table_two`.`id`\r\n```", "comments": [ { "body": "Why would it be a count?", "created_at": "2017-09-19T11:05:05Z" }, { "body": "A count query is required to calculate the total number of rows. The second query fetches the actual data for the page. The second query looks like it is missing a LIMIT clause in this issue, but I think that is a authoring issue and not related to the reported issue.\r\n\r\nThe issue seems to be the logic that rewrites the query `SELECT DISTINCT *` into a `SELECT COUNT(*)` instead of understanding that it needs to keep the DISTINCT part.\r\n\r\nRelated: [Builder::runPaginationCountQuery](https://github.com/laravel/framework/blob/997e67cc2001006a43b73eaedf17fa1a2555fd66/src/Illuminate/Database/Query/Builder.php#L1785-L1791)", "created_at": "2017-09-19T14:48:47Z" }, { "body": "@Dylan-DPC if there are 2 lines in the second table, the first request for count will return 2, but the second query will return 1 model.\r\ncompare the two functions and understand that there is a mistake\r\nQuery Builder\r\nhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Query/Builder.php#L1718\r\nEloquent Query Builder\r\nhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Builder.php#L683", "created_at": "2017-09-20T03:45:03Z" }, { "body": "I don't see this as a bug actually. It can be enhanced/improved though. Feel free to send in a PR or make a proposal on laravel/internals.", "created_at": "2017-09-20T15:34:39Z" }, { "body": "Well, it returns wrong values. Can we update the docs and state that paginate() does not support joins/distinct/whatever it is in this case that is messing with the result?", "created_at": "2017-09-20T15:38:30Z" }, { "body": "yeah that's better @sisve ", "created_at": "2017-09-20T15:47:26Z" }, { "body": "it is distinct that breaks this\r\n\r\nit looks like the regular query builder paginate method allows for passing fields to count on, but the eloquent builder always does count(*)\r\n\r\nit looks like a fairly simple fix to mirror the behaviour of query builder (not completely sure why it isnt just delegating to that anyway tbh), but guessing changing behaviour of eloquent methods is breaking change, even if it is actually fixing a bug\r\n\r\nhttps://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Query/Builder.php#L1722\r\nhttps://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Eloquent/Builder.php#L708\r\n\r\n@Dylan-DPC not really sure how this isnt a bug. paginator is getting the wrong value for total count, which then causes it to generate links for more pages than there are results for\r\n\r\n\r\n", "created_at": "2017-10-30T15:31:48Z" }, { "body": "Paginator isn't expected to work with joins/distincts, etc. May be it isn't documented enough. ", "created_at": "2017-10-30T15:42:50Z" }, { "body": "A PR that would fix this was merged into the master branch. This will be released in the next version of Laravel.", "created_at": "2019-06-13T14:01:31Z" } ], "number": 21242, "title": "Incorrect work pagination Eloquent" }
{ "body": "When doing a `distinct` query I tried to make the paginator also use a distinct query. The only way to do this seems to be to pass the columns to the paginator so it in turn should build a correct count query.\r\n\r\n```php\r\n$query->paginate(10, ['table.id']);\r\n```\r\n\r\nHowever it seems that the columns are never passed to the `getCountForPagination` in the Eloquent builder. It does in the \"regular\" query Builder. This corrects that.\r\n\r\nThis seems to be the way since the initial refactor 2 years ago and thus possible longer, maybe this should also be backported to earlier version.\r\n\r\n----\r\n\r\nEdit: I missed the `EloquentPaginateTest`, seeing that now I can see why this is done. However this means a paginate on a distinct query will not work when using the Eloquent builder. \r\n\r\nPossibly passing the model's primary key as a distinction column is the way to go... however I'm not too sure about it... it works for my use case but not sure if correct and/or covers most cases.\r\n\r\n(also the test is not how you would use this but I tried to keep the query and test to a minimum to prevent overcomplicated queries clouding the purpose of the test)\r\n\r\n----\r\n\r\nEdit 2: This is discussed already a few times but never fixed: #21242 (PR's: #21891 #21899)\r\n\r\nI hope this can be reconsidered for 5.7 or possibly 5.8 since pagination is just plain broken when using a distinct.", "number": 26014, "review_comments": [], "title": "[5.7] Fix distinct pagination on the Eloquent query builder" }
{ "commits": [ { "message": "Pass the `$columns` to the pagination counter" }, { "message": "Pass the key column to the pagination count query if it's a distinct query" }, { "message": "Add test for distinct pagination on Eloquent query" } ], "files": [ { "diff": "@@ -742,9 +742,11 @@ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page',\n \n $perPage = $perPage ?: $this->model->getPerPage();\n \n- $results = ($total = $this->toBase()->getCountForPagination())\n- ? $this->forPage($page, $perPage)->get($columns)\n- : $this->model->newCollection();\n+ $query = $this->toBase();\n+\n+ $results = ($total = $query->getCountForPagination($query->distinct ? [$this->model->getQualifiedKeyName()] : ['*']))\n+ ? $this->forPage($page, $perPage)->get($columns)\n+ : $this->model->newCollection();\n \n return $this->paginator($results, $total, $perPage, $page, [\n 'path' => Paginator::resolveCurrentPath(),", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -20,6 +20,14 @@ public function setUp()\n $table->string('title')->nullable();\n $table->timestamps();\n });\n+ Schema::create('post_comments', function ($table) {\n+ $table->increments('id');\n+ $table->unsignedInteger('post_id');\n+ $table->foreign('post_id')->references('id')->on('posts');\n+ $table->string('text')->nullable();\n+ $table->unsignedInteger('likes')->default(0);\n+ $table->timestamps();\n+ });\n }\n \n public function test_pagination_on_top_of_columns()\n@@ -32,9 +40,40 @@ public function test_pagination_on_top_of_columns()\n \n $this->assertCount(15, Post::paginate(15, ['id', 'title']));\n }\n+\n+ public function test_pagination_with_distinct()\n+ {\n+ for ($i = 1; $i <= 25; $i++) {\n+ $post = Post::create([\n+ 'title' => 'Title '.$i,\n+ ]);\n+\n+ for ($j = 1; $j <= 5; $j++) {\n+ PostComment::create([\n+ 'post_id' => $post->id,\n+ 'text' => 'Comment '.$j,\n+ 'likes' => $i + $j,\n+ ]);\n+ }\n+ }\n+\n+ $paginator = Post::join('post_comments', 'post_comments.post_id', '=', 'posts.id')\n+ ->where('likes', '>', 10)\n+ ->distinct()\n+ ->select('posts.*')\n+ ->paginate(15);\n+\n+ $this->assertCount(15, $paginator);\n+ $this->assertEquals(20, $paginator->total());\n+ }\n }\n \n class Post extends Model\n {\n protected $guarded = [];\n }\n+\n+class PostComment extends Model\n+{\n+ protected $guarded = [];\n+}", "filename": "tests/Integration/Database/EloquentPaginateTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.2.45\r\n- PHP Version: 7.0.13\r\n\r\n### Description:\r\n\r\nRecently updated a production app from Laravel v5.2.32 to 5.2.45 (latest), and polymorphic eager loads have stopped working. Any help would be much appreciated!\r\n\r\nI get the following error:\r\n\r\n```\r\nCall to undefined method Illuminate\\Database\\Query\\Builder::route()\r\n```\r\n\r\nFrom debugging, the problem seems to be https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Relations/MorphTo.php#L188\r\n\r\nIf i change \r\n\r\n```php\r\n $query = $this->replayMacros($instance->newQuery())\r\n ->mergeModelDefinedRelationConstraints($this->getQuery())\r\n ->with($this->getQuery()->getEagerLoads());\r\n```\r\n\r\nto\r\n\r\n```\r\n $query = $this->replayMacros($instance->newQuery())\r\n ->mergeModelDefinedRelationConstraints($this->getQuery())\r\n ->with($instance->newQuery()->getEagerLoads());\r\n```\r\n\r\nit fixed the problem, but I don't want to submit a PR in-case that is not actually a general fix.\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\nMy `Log` model has two polymorphic relations defined - primary and secondary. When loading primary, the `Journey` and `Achievement` models are being correctly loaded, however `route` is being eager loaded for both of the polymorphic relations, even though it is only defined as the `$with` parameter for `Journey`.\r\n\r\nLog.php\r\n\r\n```php\r\nclass Log extends Model\r\n{\r\n public function primary()\r\n {\r\n return $this->morphTo();\r\n }\r\n\r\n public function secondary()\r\n {\r\n return $this->morphTo();\r\n }\r\n```\r\n\r\nAchievement.php\r\n\r\n```php\r\nclass Achievement extends Model\r\n{\r\n\r\n}\r\n```\r\n\r\nJourney.php\r\n\r\n```php\r\nclass Journey extends Model \r\n{\r\n\r\n protected $with = ['route'];\r\n\r\n public function route()\r\n {\r\n return $this->belongsTo(Route::class)->withTrashed();\r\n }\r\n\r\n}\r\n```\r\n\r\nThanks.", "comments": [ { "body": "5.2 is not supported anymore, can you replicate the problem on a 5.3 installation?", "created_at": "2016-11-30T13:19:01Z" }, { "body": "@themsaid Thanks for the reply.\r\n\r\nYes - I updated the app to Laravel 5.3 and replicated the same issue:\r\n\r\n```\r\nRelationNotFoundException in RelationNotFoundException.php line 20:\r\nCall to undefined relationship [route] on model [Walking\\Achievements\\Achievement].\r\n```\r\n\r\nDo you know if changing `$this->getQuery()->getEagerLoads()` to `$instance->newQuery()->getEagerLoads()` would work, or is that likely to break the intended update from https://github.com/laravel/framework/commit/ee7b8cffb046467d220439b940f983f5dde89d6c ?\r\n\r\n\r\n", "created_at": "2016-11-30T13:28:03Z" }, { "body": "Laravel Version: 5.4.9\r\nPHP Version: 7.1.0\r\n\r\n+1, I've stumbled onto exactly same issue in 5.3, upgraded to 5.4 and it is still reproducible. Looks like ee7b8cffb046467d220439b940f983f5dde89d6c fixes some other (similar) case.\r\n\r\nIn 5.4 the illness is now here:\r\nhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php#L183\r\n\r\nI didn't dig much, but when I replaced `$instance->newQuery()` with `$instance->newQuery()->setEagerLoads([])` (as in ee7b8cffb046467d220439b940f983f5dde89d6c) the issue disappeared. Not sure how it affects eager loading.\r\n\r\nLet me know if you need some sandbox with a reproduce of this issue.", "created_at": "2017-02-04T00:11:33Z" }, { "body": "I just came across this issue in 5.4 as well. Have a model PurchaseOrder with purchaseOrderable() method that contains morphTo().\r\n\r\nIf any of the related models have $with defined, the framework will try and eager load relationships on all objects using the all the keys defined across different models.\r\n\r\nE.g. \r\n\r\nPurchaseOrder\r\n\r\nModel A\r\n- with = ['parentA', 'parentB']\r\n\r\nModel B\r\n- with = ['parentC', 'parentD']\r\n\r\nWill try and load parent A,B,C,D for all models.", "created_at": "2017-04-23T13:50:55Z" }, { "body": "This issue can probably be summed up as \"Polymorphic eager load will try to cross eager load from different polymorphic models, causing a `RelationNotFoundException` exception.\r\n\r\nI actually came up with a workaround for another project where I ran into this issue. The workaround is:\r\n\r\n```php\r\n$results = $results->groupBy('model_type')\r\n ->map(function($group) {\r\n $group->load(['model']);\r\n return $group;\r\n })->flatten();\r\n```\r\n\r\nWhere `model` is the polymorphic relation. I still get eager-loading, but by grouping the polymorphic results before eager loading, I avoid running into the cross eager load issue. I wonder if this approach might work baked into Eloquent somehow?\r\n", "created_at": "2017-04-23T19:54:46Z" }, { "body": "Spot on! Thanks for adding this @davidrushton, a great solution in the mean time.", "created_at": "2017-04-24T02:29:26Z" }, { "body": "Is this still an issue?", "created_at": "2018-08-12T04:05:58Z" }, { "body": "@staudenmeir I've not tested on 5.5 or 5.6, but my 5.4 app (5.4.9) still has this issue.", "created_at": "2018-08-15T11:51:46Z" }, { "body": "@davidrushton I was asking because I couldn't even reproduce the issue on 5.4.0. Is your example still valid?", "created_at": "2018-08-15T14:35:07Z" }, { "body": "@staudenmeir \r\nAs of Laravel 5.4.9 it was reproducible for me (see above).\r\nBut I haven't checked in 5.5 or 5.6.\r\n(probably a failing test needs to be added to not guess)", "created_at": "2018-08-15T14:39:25Z" }, { "body": "I'm using the documentation example and it works on 5.4.0:\r\n\r\n```php\r\nclass Comment extends Model {\r\n public function commentable() {\r\n return $this->morphTo();\r\n }\r\n}\r\n\r\nclass Post extends Model {\r\n protected $with = ['user'];\r\n\r\n public function user() {\r\n return $this->belongsTo(User::class);\r\n }\r\n}\r\n\r\nclass Video extends Model {}\r\n\r\n$post = Post::create(['user_id' => 1]);\r\n$video = Video::create();\r\nComment::create(['commentable_type' => Post::class, 'commentable_id' => $post->id]);\r\nComment::create(['commentable_type' => Video::class, 'commentable_id' => $video->id]);\r\n\r\nComment::with('commentable')->get();\r\n```", "created_at": "2018-08-15T15:19:49Z" }, { "body": "My specific example that still isn't working on 5.4.9 is:\r\n\r\n```php\r\n\r\nclass Index extends Model {\r\n\r\n\tpublic function model()\r\n\t{\r\n\t\treturn $this->morphTo('model');\r\n\t}\r\n\r\n}\r\n\r\nclass Product extends Model {\r\n\t\r\n\tprotected $with = ['prices', 'thumbnail', 'translations'];\r\n\r\n}\r\n\r\nclass Page extends Model {\r\n\r\n\tprotected $with = ['translations'];\r\n\r\n}\r\n```\r\n\r\nWhen I effectively do\r\n\r\n```php\r\n$results = Index::get();\r\n$results->load('model');\r\n```\r\n\r\nI get this exception:\r\n\r\n```\r\nRelationNotFoundException\r\nCall to undefined relationship [thumbnail] on model [Page].\r\n```\r\n\r\nBut when I group the load as so it works:\r\n\r\n```php\r\n$results = Index::get();\r\n$results = $results->groupBy('model_type')\r\n\t->map(function ($group) {\r\n\t $group->load('model');\r\n\t return $group;\r\n\t})->flatten();\r\n```\r\n\r\n", "created_at": "2018-08-15T15:42:31Z" }, { "body": "I see, it only happens on lazy loading:\r\n\r\n```php\r\nComment::all()->load('commentable');\r\n```\r\n\r\nIt's still an issue on 5.6.", "created_at": "2018-08-15T15:55:00Z" }, { "body": "@staudenmeir Thanks for checking 5.6. \r\n\r\nI have to use lazy loading since i'm actually using Laravel Scout to fetch the `Index` results, and that has no `with` method on the builder.", "created_at": "2018-08-15T17:14:51Z" } ], "number": 16604, "title": "[5.4] MorphTo eager load issue" }
{ "body": "`Collection::load()` uses the first model to get the relationships for lazy eager loading. This can cause problems on `MorphTo` relationships when the related models differ in certain aspects:\r\n\r\n### Example 1: Different relationships in `$with` (#16604)\r\n\r\n```php\r\nclass Comment extends Model {\r\n public function commentable() {\r\n return $this->morphTo();\r\n }\r\n}\r\n\r\nclass Post extends Model {\r\n protected $with = ['user'];\r\n\r\n public function user() {\r\n return $this->belongsTo(User::class);\r\n }\r\n}\r\n\r\nclass Video extends Model {}\r\n\r\n$post = Post::create(['user_id' => 1]);\r\n$video = Video::create();\r\n(new Comment)->commentable()->associate($post)->save();\r\n(new Comment)->commentable()->associate($video)->save();\r\n\r\nComment::all()->load('commentable');\r\n```\r\n\r\nThis fails because Eloquent tries to load the `user` relationship on `$video` (as specified in `$post`). \r\n\r\n### Example 2: Different primary keys (#24654)\r\n\r\n```php\r\nclass Comment extends Model {\r\n public function commentable() {\r\n return $this->morphTo();\r\n }\r\n}\r\n\r\nclass Post extends Model {\r\n protected $primaryKey = 'post_id';\r\n}\r\n\r\nclass Video extends Model {\r\n protected $primaryKey = 'video_id';\r\n}\r\n\r\n$post = Post::create();\r\n$video = Video::create();\r\n(new Comment)->commentable()->associate($post)->save();\r\n(new Comment)->commentable()->associate($video)->save();\r\n\r\nComment::all()->load('commentable');\r\n```\r\n\r\nThis fails because Eloquent tries to access the `videos.post_id` column (as specified in `$post`). \r\n\r\n---\r\n\r\nAll this is caused by `HasRelationships::morphTo()` only calling `morphEagerTo()` on eager loading: On *lazy* eager loading, `morphInstanceTo()` is used.\r\n\r\nWe can fix the problem by always using a fresh model instance when getting the relationship in `Builder::getRelation()`. This mimics eager loading where the query builder is initialized with a fresh instance. \r\n\r\nThe new integration test combines different primary keys and the usage of `$with`.\r\n\r\nFixes #16604 and fixes #24654.", "number": 25240, "review_comments": [], "title": "[5.6] Fix MorphTo lazy eager loading" }
{ "commits": [ { "message": "Fix MorphTo lazy eager loading" } ], "files": [ { "diff": "@@ -543,7 +543,7 @@ public function getRelation($name)\n // and error prone. We don't want constraints because we add eager ones.\n $relation = Relation::noConstraints(function () use ($name) {\n try {\n- return $this->getModel()->{$name}();\n+ return $this->getModel()->newInstance()->$name();\n } catch (BadMethodCallException $e) {\n throw RelationNotFoundException::make($this->getModel(), $name);\n }", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -460,7 +460,7 @@ public function testGetRelationProperlySetsNestedRelationships()\n {\n $builder = $this->getBuilder();\n $builder->setModel($this->getMockModel());\n- $builder->getModel()->shouldReceive('orders')->once()->andReturn($relation = m::mock('stdClass'));\n+ $builder->getModel()->shouldReceive('newInstance->orders')->once()->andReturn($relation = m::mock('stdClass'));\n $relationQuery = m::mock('stdClass');\n $relation->shouldReceive('getQuery')->andReturn($relationQuery);\n $relationQuery->shouldReceive('with')->once()->with(['lines' => null, 'lines.details' => null]);\n@@ -473,8 +473,8 @@ public function testGetRelationProperlySetsNestedRelationshipsWithSimilarNames()\n {\n $builder = $this->getBuilder();\n $builder->setModel($this->getMockModel());\n- $builder->getModel()->shouldReceive('orders')->once()->andReturn($relation = m::mock('stdClass'));\n- $builder->getModel()->shouldReceive('ordersGroups')->once()->andReturn($groupsRelation = m::mock('stdClass'));\n+ $builder->getModel()->shouldReceive('newInstance->orders')->once()->andReturn($relation = m::mock('stdClass'));\n+ $builder->getModel()->shouldReceive('newInstance->ordersGroups')->once()->andReturn($groupsRelation = m::mock('stdClass'));\n \n $relationQuery = m::mock('stdClass');\n $relation->shouldReceive('getQuery')->andReturn($relationQuery);", "filename": "tests/Database/DatabaseEloquentBuilderTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,94 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\EloquentMorphToLazyEagerLoadingTest;\n+\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Tests\\Integration\\Database\\DatabaseTestCase;\n+\n+/**\n+ * @group integration\n+ */\n+class EloquentMorphToLazyEagerLoadingTest extends DatabaseTestCase\n+{\n+ public function setUp()\n+ {\n+ parent::setUp();\n+\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->increments('id');\n+ });\n+\n+ Schema::create('posts', function (Blueprint $table) {\n+ $table->increments('post_id');\n+ $table->unsignedInteger('user_id');\n+ });\n+\n+ Schema::create('videos', function (Blueprint $table) {\n+ $table->increments('video_id');\n+ });\n+\n+ Schema::create('comments', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('commentable_type');\n+ $table->integer('commentable_id');\n+ });\n+\n+ $user = User::create();\n+\n+ $post = tap((new Post)->user()->associate($user))->save();\n+\n+ $video = Video::create();\n+\n+ (new Comment)->commentable()->associate($post)->save();\n+ (new Comment)->commentable()->associate($video)->save();\n+ }\n+\n+ public function test_lazy_eager_loading()\n+ {\n+ $comments = Comment::all();\n+\n+ \\DB::enableQueryLog();\n+\n+ $comments->load('commentable');\n+\n+ $this->assertCount(3, \\DB::getQueryLog());\n+ $this->assertTrue($comments[0]->relationLoaded('commentable'));\n+ $this->assertTrue($comments[0]->commentable->relationLoaded('user'));\n+ $this->assertTrue($comments[1]->relationLoaded('commentable'));\n+ }\n+}\n+\n+class Comment extends Model\n+{\n+ public $timestamps = false;\n+\n+ public function commentable()\n+ {\n+ return $this->morphTo();\n+ }\n+}\n+\n+class Post extends Model\n+{\n+ public $timestamps = false;\n+ protected $primaryKey = 'post_id';\n+ protected $with = ['user'];\n+\n+ public function user()\n+ {\n+ return $this->belongsTo(User::class);\n+ }\n+}\n+\n+class User extends Model\n+{\n+ public $timestamps = false;\n+}\n+\n+class Video extends Model\n+{\n+ public $timestamps = false;\n+ protected $primaryKey = 'video_id';\n+}", "filename": "tests/Integration/Database/EloquentMorphToLazyEagerLoadingTest.php", "status": "added" } ] }
{ "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": "Change Event Dispatcher Contract namespace to Event Dispatcher Class namespace as static method **events** is trying to instantiate an object of Dispatcher interface instead of class which gives error when using queue outside laravel\r\n\r\n**Error**\r\n`\r\nTarget [Illuminate\\Contracts\\Events\\Dispatcher] is not instantiable\r\n`\r\n\r\n**Stack Trace**\r\n`\r\nException Stack Trace: #0 /var/www/app/vendor/illuminate/container/Container.php(773): Illuminate\\Container\\Container->notInstantiable('Illuminate\\Contracts\\Events\\Dispatcher') #1 /var/www/app/vendor/illuminate/container/Container.php(646): Illuminate\\Container\\Container->build('Illuminate\\Contracts\\Events\\Dispatcher') #2 /var/www/app/vendor/illuminate/container/Container.php(601): Illuminate\\Container\\Container->resolve('Illuminate\\Contracts\\Events\\Dispatcher', Array) #3 /var/www/app/vendor/illuminate/queue/FailingJob.php(48): Illuminate\\Container\\Container->make('Illuminate\\Contracts\\Events\\Dispatcher') #4 /var/www/app/vendor/illuminate/queue/FailingJob.php(35): Illuminate\\Queue\\FailingJob::events() #5 /var/www/app/vendor/illuminate/queue/Worker.php(435): Illuminate\\Queue\\FailingJob::handle('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, Illuminate\\Queue\\MaxAttemptsExceededException) #6 /var/www/app/vendor/illuminate/queue/Worker.php(397): Illuminate\\Queue\\Worker->failJob('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, Illuminate\\Queue\\MaxAttemptsExceededException) #7 /var/www/app/vendor/illuminate/queue/Worker.php(316): Illuminate\\Queue\\Worker->markJobAsFailedIfAlreadyExceedsMaxAttempts('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, 3) #8 /var/www/app/vendor/illuminate/queue/Worker.php(272): Illuminate\\Queue\\Worker->process('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, Illuminate\\Queue\\WorkerOptions) #9 /var/www/app/vendor/illuminate/queue/Worker.php(118): Illuminate\\Queue\\Worker->runJob(Illuminate\\Queue\\Jobs\\RedisJob, 'job_worker', Illuminate\\Queue\\WorkerOptions) #10 /var/www/app/crons/JobWorker.php(63): Illuminate\\Queue\\Worker->daemon('job_worker', 'job_worker', Illuminate\\Queue\\WorkerOptions)\r\n`", "number": 24285, "review_comments": [], "title": "[5.6] Problem with Failing Job Dispatcher Object Instantiation" }
{ "commits": [ { "message": "Problem with Failing Job Dispatcher Object Instantiation\n\nChange Event Dispatcher Contract namespace to Event Dispatcher Class namespace as static method events is trying to instantiate an object of Dispatcher interface instead of class which gives error when using queue outside laravel\r\n\r\n`\r\nTarget [Illuminate\\Contracts\\Events\\Dispatcher] is not instantiable\r\n`\r\n\r\n`\r\nException Stack Trace: #0 /var/www/publicam_api/vendor/illuminate/container/Container.php(773): Illuminate\\Container\\Container->notInstantiable('Illuminate\\Contracts\\Events\\Dispatcher') #1 /var/www/publicam_api/vendor/illuminate/container/Container.php(646): Illuminate\\Container\\Container->build('Illuminate\\Contracts\\Events\\Dispatcher') #2 /var/www/publicam_api/vendor/illuminate/container/Container.php(601): Illuminate\\Container\\Container->resolve('Illuminate\\Contracts\\Events\\Dispatcher', Array) #3 /var/www/publicam_api/vendor/illuminate/queue/FailingJob.php(48): Illuminate\\Container\\Container->make('Illuminate\\Contracts\\Events\\Dispatcher') #4 /var/www/publicam_api/vendor/illuminate/queue/FailingJob.php(35): Illuminate\\Queue\\FailingJob::events() #5 /var/www/publicam_api/vendor/illuminate/queue/Worker.php(435): Illuminate\\Queue\\FailingJob::handle('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, Illuminate\\Queue\\MaxAttemptsExceededException) #6 /var/www/publicam_api/vendor/illuminate/queue/Worker.php(397): Illuminate\\Queue\\Worker->failJob('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, Illuminate\\Queue\\MaxAttemptsExceededException) #7 /var/www/publicam_api/vendor/illuminate/queue/Worker.php(316): Illuminate\\Queue\\Worker->markJobAsFailedIfAlreadyExceedsMaxAttempts('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, 3) #8 /var/www/publicam_api/vendor/illuminate/queue/Worker.php(272): Illuminate\\Queue\\Worker->process('job_worker', Illuminate\\Queue\\Jobs\\RedisJob, Illuminate\\Queue\\WorkerOptions) #9 /var/www/publicam_api/vendor/illuminate/queue/Worker.php(118): Illuminate\\Queue\\Worker->runJob(Illuminate\\Queue\\Jobs\\RedisJob, 'job_worker', Illuminate\\Queue\\WorkerOptions) #10 /var/www/publicam_api/crons/JobWorker.php(63): Illuminate\\Queue\\Worker->daemon('job_worker', 'job_worker', Illuminate\\Queue\\WorkerOptions)\r\n`" }, { "message": "Merge pull request #1 from haridarshan/haridarshan-patch-1\n\nProblem with Failing Job Dispatcher Object Instantiation" } ], "files": [ { "diff": "@@ -4,7 +4,7 @@\n \n use Illuminate\\Container\\Container;\n use Illuminate\\Queue\\Events\\JobFailed;\n-use Illuminate\\Contracts\\Events\\Dispatcher;\n+use Illuminate\\Events\\Dispatcher;\n \n class FailingJob\n {", "filename": "src/Illuminate/Queue/FailingJob.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.6.22\r\n- PHP Version: 7.1.17\r\n- Database Driver & Version: 4.0.2\r\n\r\n### Description:\r\nIn both PhpRedis and Predis connections when running a scan command, the prefix doesn't appear to function as expected. In a non-prefixed predis connection, scanning with a match of `test` on a prefilled redis database like:\r\n```\r\ntest\r\ntest1\r\ntest2\r\n```\r\nI get the expected single result of test.\r\nWhen running that same test will prefixed entries in the database like:\r\n```\r\npre:test\r\npre:test1\r\npre:test2\r\n```\r\nand the same match condition, I get no results.\r\n\r\nI would assume the expectation would be that any command run on a prefixed connection would only operate on that prefix and that the prefix usage would basically just be invisible like:\r\n\r\n```\r\n// Both prefixed and non-prefixed connections\r\n$redis->set('key1', 'value');\r\n$result = $redis->scan('key*');\r\n// $result = ['key1'];\r\n```\r\nThis is even backed up by the Predis client options (https://github.com/nrk/predis/wiki/Client-Options)\r\n> Specifies a string used to automatically prefix all the keys contained in a command issued to Redis.)\r\n\r\n### Steps To Reproduce:\r\n1. Create 2 connections, one prefixed and one not.\r\n2. Before each run of the scan command, prefill the redis database like shown above, where the prefix is never manually added other than in the connection options.\r\n3. Note that a scan command does not return the same results and scan calls to the prefixed connection yields no results.", "comments": [ { "body": "@ragingdave gonna close this due to inactivity. Feel free to reply if this is still an issue.", "created_at": "2018-11-19T16:53:02Z" }, { "body": "I just ran into this same issue. @driesvints could you reopen this please?\r\n\r\nReproduction steps using `php artisan tinker` and the `phpredis` driver:\r\n\r\n```\r\n>>> RedisFacade::set('example:123', '1')\r\n=> true\r\n>>> RedisFacade::scan('', 'example:*')\r\n=> []\r\n```\r\n\r\nIf you open `redis-cli` in another terminal and run `MONITOR` you can see the following commands being executed:\r\n\r\n```\r\n1582048092.501213 [0 127.0.0.1:57806] \"SET\" \"laravel_database_example:123\" \"1\"\r\n1582048101.392400 [0 127.0.0.1:57806] \"SCAN\" \"0\" \"MATCH\" \"example:*\"\r\n```\r\n\r\nThe same issue occurs when using the `Redis` class directly so I think we need to implement [a similar solution to the `ZADD` command](https://github.com/laravel/framework/blob/b47217e41868d3049ec545cbb713aa94c6f39e55/src/Illuminate/Redis/Connections/PhpRedisConnection.php#L225).", "created_at": "2020-02-18T17:57:56Z" }, { "body": "@matt-allan does anything from the attempted PR help? https://github.com/laravel/framework/pull/24299", "created_at": "2020-02-20T09:40:14Z" }, { "body": "@driesvints thanks for reopening this. There have been a lot of changes since #24299 in both the connection class and the tests that should make fixing this easier. I will try and put a PR together today or early next week.", "created_at": "2020-02-20T14:32:09Z" }, { "body": "There's also a PhpRedis issue for this at https://github.com/phpredis/phpredis/issues/548. Might be better to fix it there instead of creating a workaround that breaks as soon as PhpRedis starts respecting the prefix.", "created_at": "2020-02-20T14:37:49Z" }, { "body": "See https://github.com/phpredis/phpredis/issues/548#issuecomment-589533853.", "created_at": "2020-02-21T09:08:42Z" }, { "body": "That comment would seem to suggest that we would then need versioned phpredis connections to account for that difference?", "created_at": "2020-02-21T13:34:15Z" }, { "body": "It sounds like it's going to be an optional feature you have to specifically opt-in to (for BC reasons), so we don't **have** to take it into account. Although it might make sense to add a version check and delegate prefix handing to PhpRedis in the future.", "created_at": "2020-02-21T13:50:53Z" }, { "body": "Closing this as this seems like a PhpRedis issue rather than a Laravel issue.", "created_at": "2020-04-23T14:14:21Z" }, { "body": "FYI PhpRedis has merged support for a new `SCAN_PREFIX` option which will automatically prepend the prefix to SCAN commands. Once a version with this feature is released, Laravel could add (optional) support for it.", "created_at": "2020-05-19T08:43:03Z" } ], "number": 24257, "title": "Prefixed Redis Connections not working as expected for scan command" }
{ "body": "This adds the adapter methods to properly utilize PhpRedis commands for scan, sscan, hscan, and zscan. fixes #24222\r\n\r\nI do know there is 2 failing tests but those are a by product of another bug which most likely needs to be addressed and is opened in issue: #24257", "number": 24256, "review_comments": [], "title": "[5.6] Fix *scan methods on PhpRedis connections" }
{ "commits": [ { "message": "add scan methods to work on phpredis connection (scan, sscan, hscan, zscan)" }, { "message": "formatting" }, { "message": "formatting" }, { "message": "disable running prefixed scan tests" } ], "files": [ { "diff": "@@ -27,30 +27,20 @@ trait InteractsWithRedis\n */\n public function setUpRedis()\n {\n- $host = getenv('REDIS_HOST') ?: '127.0.0.1';\n- $port = getenv('REDIS_PORT') ?: 6379;\n-\n if (static::$connectionFailedOnceWithDefaultsSkip) {\n $this->markTestSkipped('Trying default host/port failed, please set environment variable REDIS_HOST & REDIS_PORT to enable '.__CLASS__);\n \n return;\n }\n \n- foreach ($this->redisDriverProvider() as $driver) {\n- $this->redis[$driver[0]] = new RedisManager($driver[0], [\n- 'cluster' => false,\n- 'default' => [\n- 'host' => $host,\n- 'port' => $port,\n- 'database' => 5,\n- 'timeout' => 0.5,\n- ],\n- ]);\n- }\n+ $this->configureConnections();\n \n try {\n $this->redis['predis']->connection()->flushdb();\n } catch (\\Exception $e) {\n+ $host = getenv('REDIS_HOST') ?: '127.0.0.1';\n+ $port = getenv('REDIS_PORT') ?: 6379;\n+\n if ($host === '127.0.0.1' && $port === 6379 && getenv('REDIS_HOST') === false) {\n $this->markTestSkipped('Trying default host/port failed, please set environment variable REDIS_HOST & REDIS_PORT to enable '.__CLASS__);\n static::$connectionFailedOnceWithDefaultsSkip = true;\n@@ -60,6 +50,52 @@ public function setUpRedis()\n }\n }\n \n+ public function configureConnections()\n+ {\n+ if (! $this->redis) {\n+ $host = getenv('REDIS_HOST') ?: '127.0.0.1';\n+ $port = getenv('REDIS_PORT') ?: 6379;\n+\n+ foreach ($this->redisDriverProvider() as $driver) {\n+ $this->redis[$driver[0]] = new RedisManager($driver[0], [\n+ 'cluster' => false,\n+ 'default' => [\n+ 'host' => $host,\n+ 'port' => $port,\n+ 'database' => 5,\n+ 'timeout' => 0.5,\n+ ],\n+ ]);\n+\n+ $this->redis[\"{$driver[0]}-prefixed\"] = new RedisManager($driver[0], [\n+ 'cluster' => false,\n+ 'default' => [\n+ 'host' => $host,\n+ 'port' => $port,\n+ 'options' => ['prefix' => 'laravel:'],\n+ 'database' => 5,\n+ 'timeout' => 0.5,\n+ ],\n+ ]);\n+ }\n+ }\n+ }\n+\n+ /**\n+ * Returns the connections for use as dataProvider.\n+ */\n+ public function redisConnections()\n+ {\n+ $connections = [];\n+ $this->configureConnections();\n+\n+ foreach ($this->redis as $driver => $redis) {\n+ $connections[$driver] = [$redis->connection()];\n+ }\n+\n+ return $connections;\n+ }\n+\n /**\n * Teardown redis connection.\n *\n@@ -69,8 +105,8 @@ public function tearDownRedis()\n {\n $this->redis['predis']->connection()->flushdb();\n \n- foreach ($this->redisDriverProvider() as $driver) {\n- $this->redis[$driver[0]]->connection()->disconnect();\n+ foreach ($this->redis as $driver) {\n+ $driver->connection()->disconnect();\n }\n }\n ", "filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithRedis.php", "status": "modified" }, { "diff": "@@ -82,6 +82,26 @@ public function set($key, $value, $expireResolution = null, $expireTTL = null, $\n ]);\n }\n \n+ /**\n+ * Runs the given scan type based on parsed options.\n+ *\n+ * @param string $type\n+ * @param string $key\n+ * @param int $counter\n+ * @param array $options\n+ * @return array\n+ */\n+ public function scan($counter, $options = [])\n+ {\n+ $counter = $counter ?: null;\n+ $opts = array_change_key_case($options, CASE_UPPER);\n+ $match = array_get($opts, 'MATCH');\n+\n+ $result = $this->client->scan($counter, $match, array_get($opts, 'COUNT'));\n+\n+ return [$counter, $result];\n+ }\n+\n /**\n * Set the given key if it doesn't exist.\n *\n@@ -130,6 +150,24 @@ public function hmset($key, ...$dictionary)\n return $this->command('hmset', [$key, $dictionary]);\n }\n \n+ /**\n+ * Scan the given hash key for all values.\n+ *\n+ * @param string $key\n+ * @param int $counter\n+ * @return array\n+ */\n+ public function hscan($key, $counter, $options = [])\n+ {\n+ $counter = $counter ?: null;\n+ $opts = array_change_key_case($options, CASE_UPPER);\n+ $match = array_get($opts, 'MATCH');\n+\n+ $result = $this->client->hscan($key, $counter, $match, array_get($opts, 'COUNT'));\n+\n+ return [$counter, $result];\n+ }\n+\n /**\n * Set the given hash field if it doesn't exist.\n *\n@@ -263,6 +301,50 @@ public function zunionstore($output, $keys, $options = [])\n );\n }\n \n+ /**\n+ * Scan the given set for all values.\n+ *\n+ * @param string $key\n+ * @param int $counter\n+ * @param array $options\n+ * @return array\n+ */\n+ public function zscan($key, $counter, $options = [])\n+ {\n+ $counter = $counter ?: null;\n+ $opts = array_change_key_case($options, CASE_UPPER);\n+ $match = array_get($opts, 'MATCH');\n+\n+ $result = $this->client->zscan($key, $counter, $match, array_get($opts, 'COUNT'));\n+ if ($result == false) {\n+ return [0, []];\n+ }\n+\n+ return [$counter, $result];\n+ }\n+\n+ /**\n+ * Scan the given set for all values.\n+ *\n+ * @param string $key\n+ * @param int $count\n+ * @param array $options\n+ * @return array\n+ */\n+ public function sscan($key, $counter, $options = [])\n+ {\n+ $counter = $counter ?: null;\n+ $opts = array_change_key_case($options, CASE_UPPER);\n+ $match = array_get($opts, 'MATCH');\n+\n+ $result = $this->client->sscan($key, $counter, $match, array_get($opts, 'COUNT'));\n+ if ($result == false) {\n+ return [0, []];\n+ }\n+\n+ return [$counter, $result];\n+ }\n+\n /**\n * Execute commands in a pipeline.\n *", "filename": "src/Illuminate/Redis/Connections/PhpRedisConnection.php", "status": "modified" }, { "diff": "@@ -3,7 +3,6 @@\n namespace Illuminate\\Tests\\Redis;\n \n use PHPUnit\\Framework\\TestCase;\n-use Illuminate\\Redis\\RedisManager;\n use Illuminate\\Foundation\\Testing\\Concerns\\InteractsWithRedis;\n \n class RedisConnectionTest extends TestCase\n@@ -32,572 +31,714 @@ public function tearDown()\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_sets_values_with_expiry()\n+ public function it_sets_values_with_expiry($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->set('one', 'mohamed', 'EX', 5, 'NX');\n- $this->assertEquals('mohamed', $redis->get('one'));\n- $this->assertNotEquals(-1, $redis->ttl('one'));\n+ $redis->set('one', 'mohamed', 'EX', 5, 'NX');\n+ $this->assertEquals('mohamed', $redis->get('one'));\n+ $this->assertNotEquals(-1, $redis->ttl('one'));\n \n- // It doesn't override when NX mode\n- $redis->set('one', 'taylor', 'EX', 5, 'NX');\n- $this->assertEquals('mohamed', $redis->get('one'));\n+ // It doesn't override when NX mode\n+ $redis->set('one', 'taylor', 'EX', 5, 'NX');\n+ $this->assertEquals('mohamed', $redis->get('one'));\n \n- // It overrides when XX mode\n- $redis->set('one', 'taylor', 'EX', 5, 'XX');\n- $this->assertEquals('taylor', $redis->get('one'));\n+ // It overrides when XX mode\n+ $redis->set('one', 'taylor', 'EX', 5, 'XX');\n+ $this->assertEquals('taylor', $redis->get('one'));\n \n- // It fails if XX mode is on and key doesn't exist\n- $redis->set('two', 'taylor', 'PX', 5, 'XX');\n- $this->assertNull($redis->get('two'));\n+ // It fails if XX mode is on and key doesn't exist\n+ $redis->set('two', 'taylor', 'PX', 5, 'XX');\n+ $this->assertNull($redis->get('two'));\n \n- $redis->set('three', 'mohamed', 'PX', 5000);\n- $this->assertEquals('mohamed', $redis->get('three'));\n- $this->assertNotEquals(-1, $redis->ttl('three'));\n- $this->assertNotEquals(-1, $redis->pttl('three'));\n+ $redis->set('three', 'mohamed', 'PX', 5000);\n+ $this->assertEquals('mohamed', $redis->get('three'));\n+ $this->assertNotEquals(-1, $redis->ttl('three'));\n+ $this->assertNotEquals(-1, $redis->pttl('three'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_deletes_keys()\n+ public function it_deletes_keys($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->set('one', 'mohamed');\n- $redis->set('two', 'mohamed');\n- $redis->set('three', 'mohamed');\n+ $redis->set('one', 'mohamed');\n+ $redis->set('two', 'mohamed');\n+ $redis->set('three', 'mohamed');\n \n- $redis->del('one');\n- $this->assertNull($redis->get('one'));\n- $this->assertNotNull($redis->get('two'));\n- $this->assertNotNull($redis->get('three'));\n+ $redis->del('one');\n+ $this->assertNull($redis->get('one'));\n+ $this->assertNotNull($redis->get('two'));\n+ $this->assertNotNull($redis->get('three'));\n \n- $redis->del('two', 'three');\n- $this->assertNull($redis->get('two'));\n- $this->assertNull($redis->get('three'));\n+ $redis->del('two', 'three');\n+ $this->assertNull($redis->get('two'));\n+ $this->assertNull($redis->get('three'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_checks_for_existence()\n+ public function it_checks_for_existence($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->set('one', 'mohamed');\n- $redis->set('two', 'mohamed');\n+ $redis->set('one', 'mohamed');\n+ $redis->set('two', 'mohamed');\n \n- $this->assertEquals(1, $redis->exists('one'));\n- $this->assertEquals(0, $redis->exists('nothing'));\n- $this->assertEquals(2, $redis->exists('one', 'two'));\n- $this->assertEquals(2, $redis->exists('one', 'two', 'nothing'));\n+ $this->assertEquals(1, $redis->exists('one'));\n+ $this->assertEquals(0, $redis->exists('nothing'));\n+ $this->assertEquals(2, $redis->exists('one', 'two'));\n+ $this->assertEquals(2, $redis->exists('one', 'two', 'nothing'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_expires_keys()\n+ public function it_expires_keys($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->set('one', 'mohamed');\n- $this->assertEquals(-1, $redis->ttl('one'));\n- $this->assertEquals(1, $redis->expire('one', 10));\n- $this->assertNotEquals(-1, $redis->ttl('one'));\n+ $redis->set('one', 'mohamed');\n+ $this->assertEquals(-1, $redis->ttl('one'));\n+ $this->assertEquals(1, $redis->expire('one', 10));\n+ $this->assertNotEquals(-1, $redis->ttl('one'));\n \n- $this->assertEquals(0, $redis->expire('nothing', 10));\n+ $this->assertEquals(0, $redis->expire('nothing', 10));\n \n- $redis->set('two', 'mohamed');\n- $this->assertEquals(-1, $redis->ttl('two'));\n- $this->assertEquals(1, $redis->pexpire('two', 10));\n- $this->assertNotEquals(-1, $redis->pttl('two'));\n+ $redis->set('two', 'mohamed');\n+ $this->assertEquals(-1, $redis->ttl('two'));\n+ $this->assertEquals(1, $redis->pexpire('two', 10));\n+ $this->assertNotEquals(-1, $redis->pttl('two'));\n \n- $this->assertEquals(0, $redis->pexpire('nothing', 10));\n+ $this->assertEquals(0, $redis->pexpire('nothing', 10));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n+ }\n+\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_renames_keys($redis)\n+ {\n+ $redis->set('one', 'mohamed');\n+ $redis->rename('one', 'two');\n+ $this->assertNull($redis->get('one'));\n+ $this->assertEquals('mohamed', $redis->get('two'));\n+\n+ $redis->set('three', 'adam');\n+ $redis->renamenx('two', 'three');\n+ $this->assertEquals('mohamed', $redis->get('two'));\n+ $this->assertEquals('adam', $redis->get('three'));\n+\n+ $redis->renamenx('two', 'four');\n+ $this->assertNull($redis->get('two'));\n+ $this->assertEquals('mohamed', $redis->get('four'));\n+ $this->assertEquals('adam', $redis->get('three'));\n+\n+ $redis->flushall();\n+ }\n+\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_scans_all_keys($redis)\n+ {\n+ $redis->set('jeffrey', 1);\n+ $redis->set('matt', 5);\n+ $redis->set('matthew', 6);\n+ $redis->set('taylor', 10);\n+ $redis->set('dave', 12);\n+\n+ $result = $redis->scan(0);\n+ $this->assertCount(2, $result);\n+ $this->assertEquals(0, $result[0]);\n+ $this->assertCount(5, $result[1]);\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n */\n- public function it_renames_keys()\n+ public function it_scans_all_keys_with_options()\n {\n- foreach ($this->connections() as $redis) {\n- $redis->set('one', 'mohamed');\n- $redis->rename('one', 'two');\n- $this->assertNull($redis->get('one'));\n- $this->assertEquals('mohamed', $redis->get('two'));\n+ foreach ($this->redis as $name => $driver) {\n+ if (str_contains($name, 'prefixed')) {\n+ return;\n+ }\n+\n+ $redis = $driver->connection();\n+\n+ $redis->pipeline(function ($pipe) {\n+ for ($x = 0; $x < 1000; $x++) {\n+ $pipe->set($x * rand(0, 1000), $x);\n+ }\n+ });\n+\n+ $result = $redis->scan(0, ['COUNT' => 10]);\n+ $this->assertCount(2, $result);\n+ $this->assertGreaterThan(0, $result[0]);\n+ $this->assertGreaterThanOrEqual(10, count($result[1]));\n \n- $redis->set('three', 'adam');\n- $redis->renamenx('two', 'three');\n- $this->assertEquals('mohamed', $redis->get('two'));\n- $this->assertEquals('adam', $redis->get('three'));\n+ $redis->flushall();\n+\n+ $redis->set('jeffrey', 1);\n+ $redis->set('matt', 5);\n+ $redis->set('matthew', 6);\n+ $redis->set('taylor', 10);\n+ $redis->set('dave', 12);\n \n- $redis->renamenx('two', 'four');\n- $this->assertNull($redis->get('two'));\n- $this->assertEquals('mohamed', $redis->get('four'));\n- $this->assertEquals('adam', $redis->get('three'));\n+ $result = $redis->scan(0, ['mAtCh' => 'matt*']);\n+ $this->assertCount(2, $result[1]);\n+\n+ $result = $redis->scan(0, ['MaTcH' => 'dave']);\n+ $this->assertCount(1, $result[1]);\n \n $redis->flushall();\n }\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_adds_members_to_sorted_set()\n+ public function it_adds_members_to_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', 1, 'mohamed');\n- $this->assertEquals(1, $redis->zcard('set'));\n+ $redis->zadd('set', 1, 'mohamed');\n+ $this->assertEquals(1, $redis->zcard('set'));\n \n- $redis->zadd('set', 2, 'taylor', 3, 'adam');\n- $this->assertEquals(3, $redis->zcard('set'));\n+ $redis->zadd('set', 2, 'taylor', 3, 'adam');\n+ $this->assertEquals(3, $redis->zcard('set'));\n \n- $redis->zadd('set', ['jeffrey' => 4, 'matt' => 5]);\n- $this->assertEquals(5, $redis->zcard('set'));\n+ $redis->zadd('set', ['jeffrey' => 4, 'matt' => 5]);\n+ $this->assertEquals(5, $redis->zcard('set'));\n \n- $redis->zadd('set', 'NX', 1, 'beric');\n- $this->assertEquals(6, $redis->zcard('set'));\n+ $redis->zadd('set', 'NX', 1, 'beric');\n+ $this->assertEquals(6, $redis->zcard('set'));\n \n- $redis->zadd('set', 'NX', ['joffrey' => 1]);\n- $this->assertEquals(7, $redis->zcard('set'));\n+ $redis->zadd('set', 'NX', ['joffrey' => 1]);\n+ $this->assertEquals(7, $redis->zcard('set'));\n \n- $redis->zadd('set', 'XX', ['ned' => 1]);\n- $this->assertEquals(7, $redis->zcard('set'));\n+ $redis->zadd('set', 'XX', ['ned' => 1]);\n+ $this->assertEquals(7, $redis->zcard('set'));\n \n- $this->assertEquals(1, $redis->zadd('set', ['sansa' => 10]));\n- $this->assertEquals(0, $redis->zadd('set', 'XX', 'CH', ['arya' => 11]));\n+ $this->assertEquals(1, $redis->zadd('set', ['sansa' => 10]));\n+ $this->assertEquals(0, $redis->zadd('set', 'XX', 'CH', ['arya' => 11]));\n \n- $redis->zadd('set', ['mohamed' => 100]);\n- $this->assertEquals(100, $redis->zscore('set', 'mohamed'));\n+ $redis->zadd('set', ['mohamed' => 100]);\n+ $this->assertEquals(100, $redis->zscore('set', 'mohamed'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_counts_members_in_sorted_set()\n+ public function it_counts_members_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 10]);\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 10]);\n \n- $this->assertEquals(1, $redis->zcount('set', 1, 5));\n- $this->assertEquals(2, $redis->zcount('set', '-inf', '+inf'));\n- $this->assertEquals(2, $redis->zcard('set'));\n+ $this->assertEquals(1, $redis->zcount('set', 1, 5));\n+ $this->assertEquals(2, $redis->zcount('set', '-inf', '+inf'));\n+ $this->assertEquals(2, $redis->zcard('set'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_increments_score_of_sorted_set()\n+ public function it_increments_score_of_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 10]);\n- $redis->zincrby('set', 2, 'jeffrey');\n- $this->assertEquals(3, $redis->zscore('set', 'jeffrey'));\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 10]);\n+ $redis->zincrby('set', 2, 'jeffrey');\n+ $this->assertEquals(3, $redis->zscore('set', 'jeffrey'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_sets_key_if_not_exists()\n+ public function it_sets_key_if_not_exists($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->set('name', 'mohamed');\n+ $redis->set('name', 'mohamed');\n \n- $this->assertSame(0, $redis->setnx('name', 'taylor'));\n- $this->assertEquals('mohamed', $redis->get('name'));\n+ $this->assertSame(0, $redis->setnx('name', 'taylor'));\n+ $this->assertEquals('mohamed', $redis->get('name'));\n \n- $this->assertSame(1, $redis->setnx('boss', 'taylor'));\n- $this->assertEquals('taylor', $redis->get('boss'));\n+ $this->assertSame(1, $redis->setnx('boss', 'taylor'));\n+ $this->assertEquals('taylor', $redis->get('boss'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_sets_hash_field_if_not_exists()\n+ public function it_sets_hash_field_if_not_exists($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->hset('person', 'name', 'mohamed');\n+ $redis->hset('person', 'name', 'mohamed');\n \n- $this->assertSame(0, $redis->hsetnx('person', 'name', 'taylor'));\n- $this->assertEquals('mohamed', $redis->hget('person', 'name'));\n+ $this->assertSame(0, $redis->hsetnx('person', 'name', 'taylor'));\n+ $this->assertEquals('mohamed', $redis->hget('person', 'name'));\n \n- $this->assertSame(1, $redis->hsetnx('person', 'boss', 'taylor'));\n- $this->assertEquals('taylor', $redis->hget('person', 'boss'));\n+ $this->assertSame(1, $redis->hsetnx('person', 'boss', 'taylor'));\n+ $this->assertEquals('taylor', $redis->hget('person', 'boss'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_calculates_intersection_of_sorted_sets_and_stores()\n+ public function it_calculates_intersection_of_sorted_sets_and_stores($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set1', ['jeffrey' => 1, 'matt' => 2, 'taylor' => 3]);\n- $redis->zadd('set2', ['jeffrey' => 2, 'matt' => 3]);\n+ $redis->zadd('set1', ['jeffrey' => 1, 'matt' => 2, 'taylor' => 3]);\n+ $redis->zadd('set2', ['jeffrey' => 2, 'matt' => 3]);\n+\n+ $redis->zinterstore('output', ['set1', 'set2']);\n+ $this->assertEquals(2, $redis->zcard('output'));\n+ $this->assertEquals(3, $redis->zscore('output', 'jeffrey'));\n+ $this->assertEquals(5, $redis->zscore('output', 'matt'));\n+\n+ $redis->zinterstore('output2', ['set1', 'set2'], [\n+ 'weights' => [3, 2],\n+ 'aggregate' => 'sum',\n+ ]);\n+ $this->assertEquals(7, $redis->zscore('output2', 'jeffrey'));\n+ $this->assertEquals(12, $redis->zscore('output2', 'matt'));\n+\n+ $redis->zinterstore('output3', ['set1', 'set2'], [\n+ 'weights' => [3, 2],\n+ 'aggregate' => 'min',\n+ ]);\n+ $this->assertEquals(3, $redis->zscore('output3', 'jeffrey'));\n+ $this->assertEquals(6, $redis->zscore('output3', 'matt'));\n+\n+ $redis->flushall();\n+ }\n \n- $redis->zinterstore('output', ['set1', 'set2']);\n- $this->assertEquals(2, $redis->zcard('output'));\n- $this->assertEquals(3, $redis->zscore('output', 'jeffrey'));\n- $this->assertEquals(5, $redis->zscore('output', 'matt'));\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_calculates_union_of_sorted_sets_and_stores($redis)\n+ {\n+ $redis->zadd('set1', ['jeffrey' => 1, 'matt' => 2, 'taylor' => 3]);\n+ $redis->zadd('set2', ['jeffrey' => 2, 'matt' => 3]);\n+\n+ $redis->zunionstore('output', ['set1', 'set2']);\n+ $this->assertEquals(3, $redis->zcard('output'));\n+ $this->assertEquals(3, $redis->zscore('output', 'jeffrey'));\n+ $this->assertEquals(5, $redis->zscore('output', 'matt'));\n+ $this->assertEquals(3, $redis->zscore('output', 'taylor'));\n+\n+ $redis->zunionstore('output2', ['set1', 'set2'], [\n+ 'weights' => [3, 2],\n+ 'aggregate' => 'sum',\n+ ]);\n+ $this->assertEquals(7, $redis->zscore('output2', 'jeffrey'));\n+ $this->assertEquals(12, $redis->zscore('output2', 'matt'));\n+ $this->assertEquals(9, $redis->zscore('output2', 'taylor'));\n+\n+ $redis->zunionstore('output3', ['set1', 'set2'], [\n+ 'weights' => [3, 2],\n+ 'aggregate' => 'min',\n+ ]);\n+ $this->assertEquals(3, $redis->zscore('output3', 'jeffrey'));\n+ $this->assertEquals(6, $redis->zscore('output3', 'matt'));\n+ $this->assertEquals(9, $redis->zscore('output3', 'taylor'));\n+\n+ $redis->flushall();\n+ }\n \n- $redis->zinterstore('output2', ['set1', 'set2'], [\n- 'weights' => [3, 2],\n- 'aggregate' => 'sum',\n- ]);\n- $this->assertEquals(7, $redis->zscore('output2', 'jeffrey'));\n- $this->assertEquals(12, $redis->zscore('output2', 'matt'));\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_returns_range_in_sorted_set($redis)\n+ {\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n+ $this->assertEquals(['jeffrey', 'matt'], $redis->zrange('set', 0, 1));\n+ $this->assertEquals(['jeffrey', 'matt', 'taylor'], $redis->zrange('set', 0, -1));\n \n- $redis->zinterstore('output3', ['set1', 'set2'], [\n- 'weights' => [3, 2],\n- 'aggregate' => 'min',\n- ]);\n- $this->assertEquals(3, $redis->zscore('output3', 'jeffrey'));\n- $this->assertEquals(6, $redis->zscore('output3', 'matt'));\n+ $this->assertEquals(['jeffrey' => 1, 'matt' => 5], $redis->zrange('set', 0, 1, 'withscores'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_calculates_union_of_sorted_sets_and_stores()\n+ public function it_returns_rev_range_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set1', ['jeffrey' => 1, 'matt' => 2, 'taylor' => 3]);\n- $redis->zadd('set2', ['jeffrey' => 2, 'matt' => 3]);\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n+ $this->assertEquals(['taylor', 'matt'], $redis->ZREVRANGE('set', 0, 1));\n+ $this->assertEquals(['taylor', 'matt', 'jeffrey'], $redis->ZREVRANGE('set', 0, -1));\n \n- $redis->zunionstore('output', ['set1', 'set2']);\n- $this->assertEquals(3, $redis->zcard('output'));\n- $this->assertEquals(3, $redis->zscore('output', 'jeffrey'));\n- $this->assertEquals(5, $redis->zscore('output', 'matt'));\n- $this->assertEquals(3, $redis->zscore('output', 'taylor'));\n+ $this->assertEquals(['matt' => 5, 'taylor' => 10], $redis->ZREVRANGE('set', 0, 1, 'withscores'));\n \n- $redis->zunionstore('output2', ['set1', 'set2'], [\n- 'weights' => [3, 2],\n- 'aggregate' => 'sum',\n- ]);\n- $this->assertEquals(7, $redis->zscore('output2', 'jeffrey'));\n- $this->assertEquals(12, $redis->zscore('output2', 'matt'));\n- $this->assertEquals(9, $redis->zscore('output2', 'taylor'));\n+ $redis->flushall();\n+ }\n \n- $redis->zunionstore('output3', ['set1', 'set2'], [\n- 'weights' => [3, 2],\n- 'aggregate' => 'min',\n- ]);\n- $this->assertEquals(3, $redis->zscore('output3', 'jeffrey'));\n- $this->assertEquals(6, $redis->zscore('output3', 'matt'));\n- $this->assertEquals(9, $redis->zscore('output3', 'taylor'));\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_returns_range_by_score_in_sorted_set($redis)\n+ {\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n+ $this->assertEquals(['jeffrey'], $redis->zrangebyscore('set', 0, 3));\n+ $this->assertEquals(['matt' => 5, 'taylor' => 10], $redis->zrangebyscore('set', 0, 11, [\n+ 'withscores' => true,\n+ 'limit' => [\n+ 'offset' => 1,\n+ 'count' => 2,\n+ ],\n+ ]));\n+\n+ $redis->flushall();\n+ }\n \n- $redis->flushall();\n- }\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_returns_rev_range_by_score_in_sorted_set($redis)\n+ {\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n+ $this->assertEquals(['taylor'], $redis->ZREVRANGEBYSCORE('set', 10, 6));\n+ $this->assertEquals(['matt' => 5, 'jeffrey' => 1], $redis->ZREVRANGEBYSCORE('set', 10, 0, [\n+ 'withscores' => true,\n+ 'limit' => [\n+ 'offset' => 1,\n+ 'count' => 2,\n+ ],\n+ ]));\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_returns_range_in_sorted_set()\n+ public function it_returns_rank_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n- $this->assertEquals(['jeffrey', 'matt'], $redis->zrange('set', 0, 1));\n- $this->assertEquals(['jeffrey', 'matt', 'taylor'], $redis->zrange('set', 0, -1));\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n \n- $this->assertEquals(['jeffrey' => 1, 'matt' => 5], $redis->zrange('set', 0, 1, 'withscores'));\n+ $this->assertEquals(0, $redis->zrank('set', 'jeffrey'));\n+ $this->assertEquals(2, $redis->zrank('set', 'taylor'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_returns_rev_range_in_sorted_set()\n+ public function it_returns_score_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n- $this->assertEquals(['taylor', 'matt'], $redis->ZREVRANGE('set', 0, 1));\n- $this->assertEquals(['taylor', 'matt', 'jeffrey'], $redis->ZREVRANGE('set', 0, -1));\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n \n- $this->assertEquals(['matt' => 5, 'taylor' => 10], $redis->ZREVRANGE('set', 0, 1, 'withscores'));\n+ $this->assertEquals(1, $redis->zscore('set', 'jeffrey'));\n+ $this->assertEquals(10, $redis->zscore('set', 'taylor'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_returns_range_by_score_in_sorted_set()\n+ public function it_removes_members_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n- $this->assertEquals(['jeffrey'], $redis->zrangebyscore('set', 0, 3));\n- $this->assertEquals(['matt' => 5, 'taylor' => 10], $redis->zrangebyscore('set', 0, 11, [\n- 'withscores' => true,\n- 'limit' => [\n- 'offset' => 1,\n- 'count' => 2,\n- ],\n- ]));\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10, 'adam' => 11]);\n \n- $redis->flushall();\n- }\n+ $redis->zrem('set', 'jeffrey');\n+ $this->assertEquals(3, $redis->zcard('set'));\n+\n+ $redis->zrem('set', 'matt', 'adam');\n+ $this->assertEquals(1, $redis->zcard('set'));\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_returns_rev_range_by_score_in_sorted_set()\n+ public function it_removes_members_by_score_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n- $this->assertEquals(['taylor'], $redis->ZREVRANGEBYSCORE('set', 10, 6));\n- $this->assertEquals(['matt' => 5, 'jeffrey' => 1], $redis->ZREVRANGEBYSCORE('set', 10, 0, [\n- 'withscores' => true,\n- 'limit' => [\n- 'offset' => 1,\n- 'count' => 2,\n- ],\n- ]));\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10, 'adam' => 11]);\n+ $redis->ZREMRANGEBYSCORE('set', 5, '+inf');\n+ $this->assertEquals(1, $redis->zcard('set'));\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_returns_rank_in_sorted_set()\n+ public function it_removes_members_by_rank_in_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10, 'adam' => 11]);\n+ $redis->ZREMRANGEBYRANK('set', 1, -1);\n+ $this->assertEquals(1, $redis->zcard('set'));\n \n- $this->assertEquals(0, $redis->zrank('set', 'jeffrey'));\n- $this->assertEquals(2, $redis->zrank('set', 'taylor'));\n-\n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_returns_score_in_sorted_set()\n+ public function it_scans_sorted_set($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10]);\n+ $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'matthew' => 6, 'taylor' => 10, 'dave' => 12]);\n \n- $this->assertEquals(1, $redis->zscore('set', 'jeffrey'));\n- $this->assertEquals(10, $redis->zscore('set', 'taylor'));\n+ $result = $redis->zscan('set', 0);\n+ $this->assertCount(2, $result);\n+ $this->assertEquals(0, $result[0]);\n+ $this->assertCount(5, $result[1]);\n \n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_removes_members_in_sorted_set()\n+ public function it_scans_sorted_set_with_options($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10, 'adam' => 11]);\n+ for ($x = 0; $x < 1000; $x++) {\n+ $set[$x] = $x * rand(0, 1000);\n+ }\n \n- $redis->zrem('set', 'jeffrey');\n- $this->assertEquals(3, $redis->zcard('set'));\n+ $redis->zadd('set', $set);\n \n- $redis->zrem('set', 'matt', 'adam');\n- $this->assertEquals(1, $redis->zcard('set'));\n+ $result = $redis->zscan('set', 0, ['COUNT' => 10]);\n+ $this->assertCount(2, $result);\n+ $this->assertGreaterThan(0, $result[0]);\n+ $this->assertGreaterThanOrEqual(10, count($result[1]));\n \n- $redis->flushall();\n- }\n+ $redis->zadd('set2', ['jeffrey' => 1, 'matt' => 5, 'matthew' => 6, 'taylor' => 10, 'dave' => 12]);\n+\n+ $result = $redis->zscan('set2', 0, ['mAtCh' => 'matt*']);\n+ $this->assertEquals(['matt' => '5', 'matthew' => 6], $result[1]);\n+\n+ $result = $redis->zscan('set2', 0, ['MaTcH' => 'dave']);\n+ $this->assertEquals(['dave' => 12], $result[1]);\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_removes_members_by_score_in_sorted_set()\n+ public function it_sets_multiple_hash_fields($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10, 'adam' => 11]);\n- $redis->ZREMRANGEBYSCORE('set', 5, '+inf');\n- $this->assertEquals(1, $redis->zcard('set'));\n+ $redis->hmset('hash', ['name' => 'mohamed', 'hobby' => 'diving']);\n+ $this->assertEquals(['name' => 'mohamed', 'hobby' => 'diving'], $redis->hgetall('hash'));\n \n- $redis->flushall();\n- }\n+ $redis->hmset('hash2', 'name', 'mohamed', 'hobby', 'diving');\n+ $this->assertEquals(['name' => 'mohamed', 'hobby' => 'diving'], $redis->hgetall('hash2'));\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_removes_members_by_rank_in_sorted_set()\n+ public function it_gets_multiple_hash_fields($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->zadd('set', ['jeffrey' => 1, 'matt' => 5, 'taylor' => 10, 'adam' => 11]);\n- $redis->ZREMRANGEBYRANK('set', 1, -1);\n- $this->assertEquals(1, $redis->zcard('set'));\n+ $redis->hmset('hash', ['name' => 'mohamed', 'hobby' => 'diving']);\n \n- $redis->flushall();\n- }\n+ $this->assertEquals(['mohamed', 'diving'],\n+ $redis->hmget('hash', 'name', 'hobby')\n+ );\n+\n+ $this->assertEquals(['mohamed', 'diving'],\n+ $redis->hmget('hash', ['name', 'hobby'])\n+ );\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_sets_multiple_hash_fields()\n+ public function it_scans_hash_fields($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->hmset('hash', ['name' => 'mohamed', 'hobby' => 'diving']);\n- $this->assertEquals(['name' => 'mohamed', 'hobby' => 'diving'], $redis->hgetall('hash'));\n+ $redis->hmset('hash', ['foo' => 'bar', 'foobar' => 'baz']);\n \n- $redis->hmset('hash2', 'name', 'mohamed', 'hobby', 'diving');\n- $this->assertEquals(['name' => 'mohamed', 'hobby' => 'diving'], $redis->hgetall('hash2'));\n+ $this->assertEquals([0, ['foo' => 'bar', 'foobar' => 'baz']],\n+ $redis->hscan('hash', 0)\n+ );\n \n- $redis->flushall();\n- }\n+ $this->assertEquals([0, []],\n+ $redis->hscan('hash_none', 0)\n+ );\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_gets_multiple_hash_fields()\n+ public function it_scans_hash_fields_with_options($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->hmset('hash', ['name' => 'mohamed', 'hobby' => 'diving']);\n+ for ($x = 0; $x < 1000; $x++) {\n+ $hash[$x] = $x;\n+ }\n \n- $this->assertEquals(['mohamed', 'diving'],\n- $redis->hmget('hash', 'name', 'hobby')\n- );\n+ $redis->hmset('hash', $hash);\n \n- $this->assertEquals(['mohamed', 'diving'],\n- $redis->hmget('hash', ['name', 'hobby'])\n- );\n+ $result = $redis->hscan('hash', 0, ['COUNT' => 10]);\n+ $this->assertCount(2, $result);\n+ $this->assertGreaterThan(0, $result[0]);\n+ $this->assertGreaterThanOrEqual(10, count($result[1]));\n \n- $redis->flushall();\n- }\n+ $redis->hmset('hash2', ['foo' => 'bar', 'foobar' => 'baz', 'bar' => 'baz']);\n+\n+ $result = $redis->hscan('hash2', 0, ['mAtCh' => 'foo*']);\n+ $this->assertEquals(['foo' => 'bar', 'foobar' => 'baz'], $result[1]);\n+\n+ $result = $redis->hscan('hash2', 0, ['MaTcH' => 'foo']);\n+ $this->assertEquals(['foo' => 'bar'], $result[1]);\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_runs_eval()\n+ public function it_scans_unsorted_sets($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->eval('redis.call(\"set\", KEYS[1], ARGV[1])', 1, 'name', 'mohamed');\n- $this->assertEquals('mohamed', $redis->get('name'));\n+ $redis->sadd('set', 'foo');\n+ $redis->sadd('set', 'bar');\n+ $redis->sadd('set', 'foobar');\n+ $redis->sadd('set', 'baz');\n \n- $redis->flushall();\n- }\n+ $result = $redis->sscan('set', 0);\n+\n+ $this->assertCount(2, $result);\n+ $this->assertEquals(0, $result[0]);\n+ $this->assertCount(4, $result[1]);\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_runs_pipes()\n+ public function it_scans_unsorted_sets_with_options($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $result = $redis->pipeline(function ($pipe) {\n- $pipe->set('test:pipeline:1', 1);\n- $pipe->get('test:pipeline:1');\n- $pipe->set('test:pipeline:2', 2);\n- $pipe->get('test:pipeline:2');\n- });\n+ $redis->sadd('set', ...range(0, 1000));\n \n- $this->assertCount(4, $result);\n- $this->assertEquals(1, $result[1]);\n- $this->assertEquals(2, $result[3]);\n+ $result = $redis->sscan('set', 0, ['count' => 10]);\n+ $this->assertCount(2, $result);\n+ $this->assertGreaterThan(0, $result[0]);\n+ $this->assertLessThan(1000, count($result[1]));\n+ $this->assertGreaterThanOrEqual(10, count($result[1]));\n \n- $redis->flushall();\n- }\n+ $redis->sadd('set2', 'jeffrey', 'matt', 'taylor', 'dave', 'david');\n+\n+ $result = $redis->sscan('set2', 0, ['mAtCh' => 'd*']);\n+ $this->assertEquals(['dave', 'david'], $result[1]);\n+\n+ $result = $redis->sscan('set2', 0, ['MaTcH' => 'dave']);\n+ $this->assertEquals(['dave'], $result[1]);\n+\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_runs_transactions()\n+ public function it_runs_eval($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $result = $redis->transaction(function ($pipe) {\n- $pipe->set('test:transaction:1', 1);\n- $pipe->get('test:transaction:1');\n- $pipe->set('test:transaction:2', 2);\n- $pipe->get('test:transaction:2');\n- });\n+ $redis->eval('redis.call(\"set\", KEYS[1], ARGV[1])', 1, 'name', 'mohamed');\n+ $this->assertEquals('mohamed', $redis->get('name'));\n \n- $this->assertCount(4, $result);\n- $this->assertEquals(1, $result[1]);\n- $this->assertEquals(2, $result[3]);\n-\n- $redis->flushall();\n- }\n+ $redis->flushall();\n }\n \n /**\n * @test\n+ * @dataProvider redisConnections\n */\n- public function it_runs_raw_command()\n+ public function it_runs_pipes($redis)\n {\n- foreach ($this->connections() as $redis) {\n- $redis->executeRaw(['SET', 'test:raw:1', '1']);\n-\n- $this->assertEquals(\n- 1, $redis->executeRaw(['GET', 'test:raw:1'])\n- );\n-\n- $redis->flushall();\n- }\n+ $result = $redis->pipeline(function ($pipe) {\n+ $pipe->set('test:pipeline:1', 1);\n+ $pipe->get('test:pipeline:1');\n+ $pipe->set('test:pipeline:2', 2);\n+ $pipe->get('test:pipeline:2');\n+ });\n+\n+ $this->assertCount(4, $result);\n+ $this->assertEquals(1, $result[1]);\n+ $this->assertEquals(2, $result[3]);\n+\n+ $redis->flushall();\n }\n \n- public function connections()\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_runs_transactions($redis)\n {\n- $connections = [\n- $this->redis['predis']->connection(),\n- $this->redis['phpredis']->connection(),\n- ];\n-\n- if (extension_loaded('redis')) {\n- $host = getenv('REDIS_HOST') ?: '127.0.0.1';\n- $port = getenv('REDIS_PORT') ?: 6379;\n+ $result = $redis->transaction(function ($pipe) {\n+ $pipe->set('test:transaction:1', 1);\n+ $pipe->get('test:transaction:1');\n+ $pipe->set('test:transaction:2', 2);\n+ $pipe->get('test:transaction:2');\n+ });\n+\n+ $this->assertCount(4, $result);\n+ $this->assertEquals(1, $result[1]);\n+ $this->assertEquals(2, $result[3]);\n+\n+ $redis->flushall();\n+ }\n \n- $prefixedPhpredis = new RedisManager('phpredis', [\n- 'cluster' => false,\n- 'default' => [\n- 'host' => $host,\n- 'port' => $port,\n- 'database' => 5,\n- 'options' => ['prefix' => 'laravel:'],\n- 'timeout' => 0.5,\n- ],\n- ]);\n+ /**\n+ * @test\n+ * @dataProvider redisConnections\n+ */\n+ public function it_runs_raw_command($redis)\n+ {\n+ $redis->executeRaw(['SET', 'test:raw:1', '1']);\n \n- $connections[] = $prefixedPhpredis->connection();\n- }\n+ $this->assertEquals(\n+ 1, $redis->executeRaw(['GET', 'test:raw:1'])\n+ );\n \n- return $connections;\n+ $redis->flushall();\n }\n }", "filename": "tests/Redis/RedisConnectionTest.php", "status": "modified" } ] }
{ "body": "In L5.5, 5.6 I experience an issue with _resolving_ callbacks on dependencies registered in the container with an interface class as abstract. A demonstration:\r\n\r\nHaving some interface \r\n\r\n```php\r\nIBar {}\r\n```\r\n\r\nand an implementation \r\n\r\n```php\r\nFoo implements IBar {}\r\n```\r\n\r\nregistered (here as a singleton) in the container \r\n\r\n```php\r\napp()->singleton( IBar::class, Foo::class );\r\n```\r\n\r\nwith a _resolving_ callback \r\n\r\n```php\r\napp()->resolving( IBar::class, $callback );\r\n```\r\n\r\nfires `$callback` **twice** when the abstract is resolved!\r\n\r\nThis is probably because:\r\n\r\n1. When the abstract `IBar` resolves, it triggers the callback\r\n2. To resolve `IBar`, `Foo` must be constructed. As `Foo` implements `IBar`, it triggers the `resolving` event too! \r\n\r\nThis problem can be omitted when avoiding Laravel's container to build Foo by registering a callback instead:\r\n\r\n```php\r\napp()->singleton( IBar::class, f(){ return new Foo; } )\r\n```\r\n\r\nBut this abolishes the ease of automatic dependency injection. \r\n\r\nSo... can we solve this issue by not firing the `resolving()` callback when we are building the implementation of an interface that the callback is registered for? ", "comments": [ { "body": "There has been some attempts to fix this previously in https://github.com/laravel/framework/pull/23290 but it wasn't merged. Perhaps send a PR with your suggested changes?", "created_at": "2018-03-26T12:39:54Z" }, { "body": "Fine, I'll submit a PR these days that will address this issue. \r\n\r\nThis test triggers the problem:\r\n\r\n```php\r\n public function testResolvingCallbacksAreCalledOnceForImplementations()\r\n {\r\n $invocations = 0;\r\n $container = new Container;\r\n $container->resolving( IContainerContractStub::class, function( ) use ( &$invocations ) {\r\n $invocations++;\r\n } );\r\n $container->bind(IContainerContractStub::class, ContainerImplementationStub::class );\r\n\r\n $this->assertEquals( 0, $invocations );\r\n $container->make( IContainerContractStub::class );\r\n $this->assertEquals( 1, $invocations );\r\n }\r\n```", "created_at": "2018-03-26T12:46:58Z" }, { "body": "\"... these days...\"\r\n#23701 ", "created_at": "2018-03-26T14:15:42Z" }, { "body": "Fixed in 5.8.", "created_at": "2019-01-10T15:13:14Z" }, { "body": "The bug is still in 5.8.12", "created_at": "2019-04-21T16:26:57Z" } ], "number": 23699, "title": "resolving() events on interfaces are called twice " }
{ "body": "Fixes #23699 by tracking abstracts that are currently being resolved. \r\nIf an object is built that is an `instanceof` of an object that is already on the stack, firing the resolving() callbacks is inhibited. \r\nThese callbacks are fired eventually when the `instanceof` object is resolved. ", "number": 23701, "review_comments": [], "title": "[5.7] Track abstracts being resolved, fire resolving events once" }
{ "commits": [ { "message": "Test resolving() callbacks being fired once for implementations" }, { "message": "Track abstract resolve stack and inhibit resolving callback when is already on this stack" }, { "message": "StyleCI" }, { "message": "Missing array_pop" }, { "message": "Check if resolve is pending when firing callbacks" }, { "message": "More extensive test" } ], "files": [ { "diff": "@@ -82,6 +82,13 @@ class Container implements ArrayAccess, ContainerContract\n */\n protected $buildStack = [];\n \n+ /**\n+ * The stack of de-aliased abstractions currently being resolved.\n+ *\n+ * @var array\n+ */\n+ protected $resolveStack = [];\n+\n /**\n * The parameter override stack.\n *\n@@ -624,6 +631,8 @@ protected function resolve($abstract, $parameters = [])\n {\n $abstract = $this->getAlias($abstract);\n \n+ $this->resolveStack[] = $abstract;\n+\n $needsContextualBuild = ! empty($parameters) || ! is_null(\n $this->getContextualConcrete($abstract)\n );\n@@ -632,6 +641,8 @@ protected function resolve($abstract, $parameters = [])\n // just return an existing instance instead of instantiating new instances\n // so the developer can keep using the same objects instance every time.\n if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {\n+ array_pop($this->resolveStack);\n+\n return $this->instances[$abstract];\n }\n \n@@ -670,6 +681,7 @@ protected function resolve($abstract, $parameters = [])\n $this->resolved[$abstract] = true;\n \n array_pop($this->with);\n+ array_pop($this->resolveStack);\n \n return $object;\n }\n@@ -1036,7 +1048,7 @@ protected function getCallbacksForType($abstract, $object, array $callbacksPerTy\n $results = [];\n \n foreach ($callbacksPerType as $type => $callbacks) {\n- if ($type === $abstract || $object instanceof $type) {\n+ if (! $this->pendingInResolveStack($object) && ($type === $abstract || $object instanceof $type)) {\n $results = array_merge($results, $callbacks);\n }\n }\n@@ -1058,6 +1070,24 @@ protected function fireCallbackArray($object, array $callbacks)\n }\n }\n \n+ /**\n+ * Check if object or a generalisation is pending in the resolve stack.\n+ *\n+ * @param object $object\n+ *\n+ * @return bool\n+ */\n+ protected function pendingInResolveStack($object)\n+ {\n+ foreach ($this->resolveStack as $resolving) {\n+ if ($resolving !== end($this->resolveStack) && $object instanceof $resolving) {\n+ return true;\n+ }\n+ }\n+\n+ return false;\n+ }\n+\n /**\n * Get the container's bindings.\n *", "filename": "src/Illuminate/Container/Container.php", "status": "modified" }, { "diff": "@@ -378,6 +378,64 @@ public function testResolvingCallbacksAreCalledForType()\n $this->assertEquals('taylor', $instance->name);\n }\n \n+ public function testResolvingCallbacksAreCalledOnceForImplementations()\n+ {\n+ $container = new Container;\n+ $resolving_contract_invocations = 0;\n+ $after_resolving_contract_invocations = 0;\n+ $resolving_implementation_invocations = 0;\n+ $after_resolving_implementation_invocations = 0;\n+\n+ $container->resolving(IContainerContractStub::class, function () use (&$resolving_contract_invocations) {\n+ $resolving_contract_invocations++;\n+ });\n+ $container->afterResolving(IContainerContractStub::class, function () use (&$after_resolving_contract_invocations) {\n+ $after_resolving_contract_invocations++;\n+ });\n+ $container->resolving(ContainerImplementationStub::class, function () use (&$resolving_implementation_invocations) {\n+ $resolving_implementation_invocations++;\n+ });\n+ $container->afterResolving(ContainerImplementationStub::class, function () use (&$after_resolving_implementation_invocations) {\n+ $after_resolving_implementation_invocations++;\n+ });\n+ $container->bind(IContainerContractStub::class, ContainerImplementationStub::class);\n+ $container->make(IContainerContractStub::class);\n+\n+ $this->assertEquals(1, $resolving_contract_invocations);\n+ $this->assertEquals(1, $after_resolving_contract_invocations);\n+ $this->assertEquals(1, $resolving_implementation_invocations);\n+ $this->assertEquals(1, $after_resolving_implementation_invocations);\n+ }\n+\n+ public function testResolvingCallbacksAreCalledForNestedDependencies()\n+ {\n+ $container = new Container;\n+ $resolving_dependency_interface_invocations = 0;\n+ $resolving_dependency_implementation_invocations = 0;\n+ $resolving_dependent_invocations = 0;\n+\n+ $container->bind(IContainerContractStub::class, ContainerImplementationStub::class);\n+\n+ $container->resolving(IContainerContractStub::class, function () use (&$resolving_dependency_interface_invocations) {\n+ $resolving_dependency_interface_invocations++;\n+ });\n+\n+ $container->resolving(ContainerImplementationStub::class, function () use (&$resolving_dependency_implementation_invocations) {\n+ $resolving_dependency_implementation_invocations++;\n+ });\n+\n+ $container->resolving(ContainerNestedDependentStubTwo::class, function () use (&$resolving_dependent_invocations) {\n+ $resolving_dependent_invocations++;\n+ });\n+\n+ $container->make(ContainerNestedDependentStubTwo::class);\n+ $container->make(ContainerNestedDependentStubTwo::class);\n+\n+ $this->assertEquals(4, $resolving_dependency_interface_invocations);\n+ $this->assertEquals(4, $resolving_dependency_implementation_invocations);\n+ $this->assertEquals(2, $resolving_dependent_invocations);\n+ }\n+\n public function testUnsetRemoveBoundInstances()\n {\n $container = new Container;\n@@ -918,6 +976,19 @@ public function testResolvingCallbacksShouldBeFiredWhenCalledWithAliases()\n $this->assertEquals('taylor', $instance->name);\n }\n \n+ public function testInterfaceResolvingCallbacksShouldBeFiredWhenCalledWithAliases()\n+ {\n+ $container = new Container;\n+ $container->alias(IContainerContractStub::class, 'foo');\n+ $container->resolving(IContainerContractStub::class, function ($object) {\n+ return $object->name = 'taylor';\n+ });\n+ $container->bind('foo', ContainerImplementationStub::class);\n+ $instance = $container->make('foo');\n+\n+ $this->assertEquals('taylor', $instance->name);\n+ }\n+\n public function testMakeWithMethodIsAnAliasForMakeMethod()\n {\n $mock = $this->getMockBuilder(Container::class)\n@@ -1070,6 +1141,18 @@ public function __construct(IContainerContractStub $impl)\n }\n }\n \n+class ContainerDependentStubTwo\n+{\n+ public $implA;\n+ public $implB;\n+\n+ public function __construct(IContainerContractStub $implA, IContainerContractStub $implB)\n+ {\n+ $this->implA = $implA;\n+ $this->implB = $implB;\n+ }\n+}\n+\n class ContainerNestedDependentStub\n {\n public $inner;\n@@ -1080,6 +1163,16 @@ public function __construct(ContainerDependentStub $inner)\n }\n }\n \n+class ContainerNestedDependentStubTwo\n+{\n+ public $inner;\n+\n+ public function __construct(ContainerDependentStubTwo $inner)\n+ {\n+ $this->inner = $inner;\n+ }\n+}\n+\n class ContainerDefaultValueStub\n {\n public $stub;", "filename": "tests/Container/ContainerTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.6\r\n- PHP Version: irrelevant\r\n- Database Driver & Version: irrelevant\r\n\r\n### Description:\r\n\r\nThe new redis blocking pop functionality introduced in https://github.com/laravel/framework/pull/22284 has issues if there are problems between the BLPOP and the ZADD. This means that any failures in the worker at this point will lose the jobs that have been popped from the queue. These jobs will not be retried by another worker since they were never pushed to the reserved queue.\r\n\r\nThe problematic code is in RedisQueue::blockingPop. \r\n\r\nhttps://github.com/laravel/framework/blob/63b61080b1383f8570526f85caf09dfea24c146d/src/Illuminate/Queue/RedisQueue.php#L225-L241\r\n", "comments": [ { "body": "So what is the solution?", "created_at": "2018-01-29T14:40:08Z" }, { "body": "Just throwing ideas out there, can we use MULTI and EXEC?", "created_at": "2018-01-29T14:43:37Z" }, { "body": "Apparently not:\r\n\r\n![image](https://user-images.githubusercontent.com/463230/35516150-a2328f14-04d0-11e8-9d2c-d79f1b3e067e.png)\r\n", "created_at": "2018-01-29T14:44:37Z" }, { "body": "Seems like our only option would be to go full Lua script with it.", "created_at": "2018-01-29T14:45:06Z" }, { "body": "Beside documentation, as I mentioned [here](https://github.com/laravel/framework/pull/22284#issuecomment-360881139), the code to fix will need to use `brpoplpush` command. It will add another Redis list key for each queue, it will add 1 or 2 extra requests per pop, and it will reverse the order of jobs in the Redis list.", "created_at": "2018-01-29T16:48:39Z" }, { "body": "Please take a look at https://redis.io/commands/rpoplpush#pattern-reliable-queue", "created_at": "2018-01-29T16:49:55Z" }, { "body": "Ah, hmm, we may need to back this out then if we can't make it reliable. Any thoughts? If we need to use `brpoplpush` that is fine with me. But, it sounds like reversing the order of jobs in the Redis list is a major breaking change? Or we would document that changing from non-blocking to blocking requires you to drain your queues first so the order is correct.", "created_at": "2018-01-29T17:42:47Z" }, { "body": "I personally feel like data loss on a queue is going to be critical in basically 99% of applications.", "created_at": "2018-01-29T17:44:09Z" }, { "body": "If we change the ordering of the queues we should probably change both the blocking and the non-blocking order. I don't think that we should require people to drain their queues just to try out the new features.\r\n\r\nI don't see a huge problem with changing the order of the lists between 5.5 and 5.6. Sure, I can make up some scenarios where it will cause problems, but those involve a mix of Laravel versions pushing and popping to the queue, and not enough workers to ever drain it. And that is a totally different problem anyway.\r\n\r\nI think it's enough to document that we change the order of the redis queue in the upgrade guide. It's an implementation detail and only affects people if they have jobs in the queue _when upgrading_.", "created_at": "2018-01-30T08:06:37Z" }, { "body": "Helper scripts can be provided to do the migration and reverse the orders.", "created_at": "2018-01-30T08:33:05Z" }, { "body": "Looks like I'll just need to document this for 5.6 release I guess.", "created_at": "2018-02-05T15:25:51Z" }, { "body": "Added this warning for now:\r\n\r\n![image](https://user-images.githubusercontent.com/463230/35812598-148b9f0c-0a57-11e8-9dde-0b543063e253.png)\r\n\r\n@halaei do you intend to work on fixing the potential data loss issue or should others try to take a look at it?", "created_at": "2018-02-05T15:29:53Z" }, { "body": "I work on it and send a PR in 2 days.", "created_at": "2018-02-05T16:14:22Z" }, { "body": "An update;\r\n\r\n1. The original PR did a check for a configuration setting of blocking_for > 0 to activate this new feature. That meant it was an opt-in feature.\r\n2. A later [commit](https://github.com/laravel/framework/commit/dbad05599b2d2059e45c480fac8817d1135d5da1) changed this behavior to check for non-null values, allowing a blocking_for = 0.\r\n3. Horizon defaults to a blocking_for=0 in code if the entry is missing in the configuration. This affects all upgraded installations. I have no numbers on how many these are, and it depends on if people updated their `config/queue.php` files to add the blocking_for entry. There is no explicit mention of this in the upgrade guide.\r\n\r\nAll these three factors, _together_, becomes a growing problem of [reported lost/paused jobs](https://github.com/laravel/horizon/issues/292) in Horizon.\r\n\r\nOn an unrelated note, if we're using blocking_for=0 (or any high value), how does that work with the SIGTERM handling to cleanly shut down a worker? I imagine that the signal is sent, but it isn't processed until the BLPOP returns. However, if this takes too long time, then supervisor would have issued a SIGKILL to forcefully shut down the worker. \r\n\r\n1. Assuming it happens during the BLPOP ; does redis know that the call was interrupted or would it still pop a job, send it away, and perhaps realize the connection is dead too late? Do we know what happens here?\r\n2. If this happens between the BLPOP and the ZADD, the job is lost. This is basically a form of the reported problem.\r\n3. If it happens after ZADD the job is retried later.\r\n\r\nThere are several questions about the current implementation, but there is a new PR that uses BRPOPLPUSH at https://github.com/laravel/framework/pull/23057 that may fix this. I'm not knowledgeable enough about BRPOPLPUSH to evaluate that approach, do we have any takers that can review that PR and add some input?", "created_at": "2018-02-10T10:51:02Z" }, { "body": "I wrote a Redis module to fix this issue and add some other values. Please check [lqrm](https://github.com/halaei/lqrm) and its [php driver](https://github.com/halaei/lqrm-php). Here is an intro digest:\r\n\r\n> This is a Redis module that implements a laravel compatible queue driver for redis with the following improvements over the original Laravel 5.7 PHP-Lua driver:\r\n 1. Blocking` pop is now more reliable than before.\r\n 2. Blocking pop now works on delayed and reserved jobs as well.\r\n 3. Timer for delayed and reserved jobs is server side, with milliseconds precision. This means you don't need to worry about syncing your php and redis servers, in case your projects are distributed accross different servers. Moreover, this makes retry_after and block_for configurations independent of each other.\r\n 4. Laravel queue can now be available for other programming languages and frameworks as well. Feel free to port it to your favorite ones.\r\n\r\nWill be great if you give it a try and/or send feedback - it might still have some bugs though.", "created_at": "2018-10-08T12:42:47Z" }, { "body": "There is a pretty simple solution that I think will work. It's explained in the redis docs [here](https://redis.io/commands/blpop#pattern-event-notification).\r\n\r\nBasically when we push a job we also push a notification key:\r\n\r\n```\r\nMULTI\r\nRPUSH queues:default '{\"id\":12345,\"attempts\":1,\"job\":\"say_hello\",\"data\":{\"name\":\"Matt\"}}'\r\nRPUSH queues:default:notify x\r\nEXEC\r\n```\r\n\r\nThe worker does a blocking pop on the notification key. Once the notification key returns an element we know a job is ready. Once a job is ready we use the existing Lua script and get all of the same atomicity guarantees.\r\n\r\n```\r\nLOOP forever\r\n WHILE EVAL(pop.lua, queues:default, queues:default:reserved, expiration) returns elements\r\n ... process elements ...\r\n END\r\n BRPOP queues:default:notify\r\nEND\r\n```\r\n\r\nIn this example `queues:default:notify` is a new list used only for notifying workers a new job was pushed. There would be a new list for each queue using the pattern `queues:{{name}}:notify`.\r\n\r\nThere is a chance the worker might crash between popping the notification element and popping the job onto the reserved queue. That is ok - once the worker restarts it will attempt to pop the job again and nothing important is lost.\r\n\r\nThe only downside I can think of with this approach is it will take some care when upgrading. If you update the workers before the producers they will be blocking waiting for a notification key that is never set. The worker will _eventually_ work the job once `block_for` times out, so job processing won't stop completely. I think in most cases you would upgrade all of your servers at the same time, so this would be a rare edge case.", "created_at": "2019-01-17T16:15:55Z" }, { "body": "This will be fixed in 5.8: https://github.com/laravel/framework/pull/27336\r\n\r\nThanks for everyone's help with this!", "created_at": "2019-02-12T14:44:45Z" } ], "number": 22939, "title": "[5.6] The new blocking pop feature for redis queues can lose jobs in case of worker failures" }
{ "body": "Fixing #22939\r\n### Changes:\r\n1. The order of jobs in Redis queue is reversed.\r\n2. A new Redis list is added for each queue, prefiex ':front'.\r\n3. brpoplpush command is used for blocking pop.\r\n4. `LuaScripts::migrateExpiredJobs()` Migrates up to 100 jobs from reserved and delayed queues. It is not a good to eval lua scripts that are possible to take super-linear time. I think a PR may be sent to previous versions of Laravel with this regard.\r\n### Tests:\r\n1. I added a test for migrating more than 100 jobs, since the ordering was a bit confusing to me.\r\n2. A test is added for blocking pop. It requires `pcntl_fork()`.\r\n", "number": 23057, "review_comments": [ { "body": "incorrect type doc", "created_at": "2018-02-13T20:46:47Z" }, { "body": "?", "created_at": "2018-02-13T20:47:01Z" }, { "body": "invalid syntax", "created_at": "2018-02-13T20:47:16Z" }, { "body": "In order to test blocking pop, there should be a process (child) to push into queue while the worker process (parent) is waiting. After push the child process is done so it dies.", "created_at": "2018-02-14T08:44:37Z" }, { "body": "If it doesn't matter, please use `exit(\"explaining why\");`, think this is helpful for \"the next developer\". Alternatively, a comment in the source is welcome too. IMHO 😄 ", "created_at": "2018-02-14T09:37:52Z" } ], "title": "[5.6] brpoplpush for redis queues" }
{ "commits": [ { "message": "reverse ordering of jobs in redis queue, add :front list, and use brpoplpush" }, { "message": "fix phpdocs" } ], "files": [ { "diff": "@@ -8,23 +8,25 @@ class LuaScripts\n * Get the Lua script for computing the size of queue.\n *\n * KEYS[1] - The name of the primary queue\n- * KEYS[2] - The name of the \"delayed\" queue\n- * KEYS[3] - The name of the \"reserved\" queue\n+ * KEYS[2] - The name of the \"front\" queue\n+ * KEYS[3] - The name of the \"delayed\" queue\n+ * KEYS[4] - The name of the \"reserved\" queue\n *\n * @return string\n */\n public static function size()\n {\n return <<<'LUA'\n-return redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])\n+return redis.call('llen', KEYS[1]) + redis.call('llen', KEYS[2]) + redis.call('zcard', KEYS[3]) + redis.call('zcard', KEYS[4])\n LUA;\n }\n \n /**\n * Get the Lua script for popping the next job off of the queue.\n *\n * KEYS[1] - The queue to pop jobs from, for example: queues:foo\n- * KEYS[2] - The queue to place reserved jobs on, for example: queues:foo:reserved\n+ * KEYS[2] - The front of the queue to pop jobs from, for example: queue:foo:front\n+ * KEYS[3] - The queue to place reserved jobs on, for example: queues:foo:reserved\n * ARGV[1] - The time at which the reserved job will expire\n *\n * @return string\n@@ -33,15 +35,18 @@ public static function pop()\n {\n return <<<'LUA'\n -- Pop the first job off of the queue...\n-local job = redis.call('lpop', KEYS[1])\n+local job = redis.call('rpop', KEYS[2])\n+if(job == false) then\n+ job = redis.call('rpop', KEYS[1])\n+end\n local reserved = false\n \n if(job ~= false) then\n -- Increment the attempt count and place job on the reserved queue...\n reserved = cjson.decode(job)\n reserved['attempts'] = reserved['attempts'] + 1\n reserved = cjson.encode(reserved)\n- redis.call('zadd', KEYS[2], ARGV[1], reserved)\n+ redis.call('zadd', KEYS[3], ARGV[1], reserved)\n end\n \n return {job, reserved}\n@@ -83,18 +88,15 @@ public static function release()\n public static function migrateExpiredJobs()\n {\n return <<<'LUA'\n--- Get all of the jobs with an expired \"score\"...\n-local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])\n+-- Get up to 100 jobs with an expired \"score\".\n+local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, 100)\n \n -- If we have values in the array, we will remove them from the first queue\n--- and add them onto the destination queue in chunks of 100, which moves\n--- all of the appropriate jobs onto the destination queue very safely.\n+-- and add them onto the destination queue.\n if(next(val) ~= nil) then\n redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)\n \n- for i = 1, #val, 100 do\n- redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))\n- end\n+ redis.call('lpush', KEYS[2], unpack(val))\n end\n \n return val", "filename": "src/Illuminate/Queue/LuaScripts.php", "status": "modified" }, { "diff": "@@ -74,7 +74,7 @@ public function size($queue = null)\n $queue = $this->getQueue($queue);\n \n return $this->getConnection()->eval(\n- LuaScripts::size(), 3, $queue, $queue.':delayed', $queue.':reserved'\n+ LuaScripts::size(), 4, $queue, $queue.':front', $queue.':delayed', $queue.':reserved'\n );\n }\n \n@@ -101,7 +101,7 @@ public function push($job, $data = '', $queue = null)\n */\n public function pushRaw($payload, $queue = null, array $options = [])\n {\n- $this->getConnection()->rpush($this->getQueue($queue), $payload);\n+ $this->getConnection()->lpush($this->getQueue($queue), $payload);\n \n return json_decode($payload, true)['id'] ?? null;\n }\n@@ -209,41 +209,41 @@ public function migrateExpiredJobs($from, $to)\n */\n protected function retrieveNextJob($queue)\n {\n- if (! is_null($this->blockFor)) {\n- return $this->blockingPop($queue);\n+ $job = $this->nonBlockingPop($queue);\n+ if ($job[0]) {\n+ return $job;\n }\n \n+ if (! is_null($this->blockFor) && $this->block($queue)) {\n+ return $this->nonBlockingPop($queue);\n+ }\n+\n+ return [null, null];\n+ }\n+\n+ /**\n+ * Retrieve the next job without blocking.\n+ *\n+ * @param string $queue\n+ * @return mixed\n+ */\n+ protected function nonBlockingPop($queue)\n+ {\n return $this->getConnection()->eval(\n- LuaScripts::pop(), 2, $queue, $queue.':reserved',\n+ LuaScripts::pop(), 3, $queue, $queue.':front', $queue.':reserved',\n $this->availableAt($this->retryAfter)\n );\n }\n \n /**\n- * Retrieve the next job by blocking-pop.\n+ * Block for the next job.\n *\n * @param string $queue\n- * @return array\n+ * @return string|null\n */\n- protected function blockingPop($queue)\n+ protected function block($queue)\n {\n- $rawBody = $this->getConnection()->blpop($queue, $this->blockFor);\n-\n- if (! is_null($rawBody)) {\n- $payload = json_decode($rawBody[1], true);\n-\n- $payload['attempts']++;\n-\n- $reserved = json_encode($payload);\n-\n- $this->getConnection()->zadd($queue.':reserved', [\n- $reserved => $this->availableAt($this->retryAfter),\n- ]);\n-\n- return [$rawBody[1], $reserved];\n- }\n-\n- return [null, null];\n+ return $this->getConnection()->brpoplpush($queue, $queue.':front', $this->blockFor);\n }\n \n /**", "filename": "src/Illuminate/Queue/RedisQueue.php", "status": "modified" }, { "diff": "@@ -17,7 +17,7 @@ public function testPushProperlyPushesJobOntoRedis()\n $queue = $this->getMockBuilder('Illuminate\\Queue\\RedisQueue')->setMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock('Illuminate\\Contracts\\Redis\\Factory'), 'default'])->getMock();\n $queue->expects($this->once())->method('getRandomId')->will($this->returnValue('foo'));\n $redis->shouldReceive('connection')->once()->andReturn($redis);\n- $redis->shouldReceive('rpush')->once()->with('queues:default', json_encode(['displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0]));\n+ $redis->shouldReceive('lpush')->once()->with('queues:default', json_encode(['displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0]));\n \n $id = $queue->push('foo', ['data']);\n $this->assertEquals('foo', $id);", "filename": "tests/Queue/QueueRedisQueueTest.php", "status": "modified" }, { "diff": "@@ -65,6 +65,49 @@ public function testExpiredJobsArePopped($driver)\n $this->assertEquals(3, $this->redis[$driver]->connection()->zcard('queues:default:reserved'));\n }\n \n+ /**\n+ * @dataProvider redisDriverProvider\n+ *\n+ * @param string $driver\n+ */\n+ public function testMigrateMoreThan100Jobs($driver)\n+ {\n+ $this->setQueue($driver);\n+\n+ for ($i = -1; $i >= -201; $i--) {\n+ $this->queue->later($i, new RedisQueueIntegrationTestJob($i));\n+ }\n+\n+ for ($i = -201; $i <= -1; $i++) {\n+ $this->assertEquals($i, unserialize(json_decode($this->queue->pop()->getRawBody())->data->command)->i);\n+ }\n+ }\n+\n+ /**\n+ * @dataProvider redisDriverProvider\n+ *\n+ * @param string $driver\n+ *\n+ * @throws \\Exception\n+ */\n+ public function testBlockingPop($driver)\n+ {\n+ $this->tearDownRedis();\n+ if ($pid = pcntl_fork() > 0) {\n+ $this->setUpRedis();\n+ $this->setQueue($driver, 10);\n+ $this->assertEquals(12, unserialize(json_decode($this->queue->pop()->getRawBody())->data->command)->i);\n+ } elseif ($pid == 0) {\n+ $this->setUpRedis();\n+ $this->setQueue('predis');\n+ sleep(1);\n+ $this->queue->push(new RedisQueueIntegrationTestJob(12));\n+ die;\n+ } else {\n+ $this->fail('Cannot fork');\n+ }\n+ }\n+\n /**\n * @dataProvider redisDriverProvider\n *\n@@ -335,10 +378,11 @@ public function testSize($driver)\n \n /**\n * @param string $driver\n+ * @param null $blockFor\n */\n- private function setQueue($driver)\n+ private function setQueue($driver, $blockFor = null)\n {\n- $this->queue = new RedisQueue($this->redis[$driver]);\n+ $this->queue = new RedisQueue($this->redis[$driver], 'default', null, 60, $blockFor);\n $this->queue->setContainer(m::mock(Container::class));\n }\n }", "filename": "tests/Queue/RedisQueueIntegrationTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.4\r\n- PHP Version: 7.0\r\n- Database Driver & Version: MySQL (MariaDB 10.1)\r\n\r\n### Description:\r\nIncorrect work pagination Eloquent from join\r\n\r\n### Steps To Reproduce:\r\nElse run code\r\n```\r\nEloquent::query()->distinct()\r\n ->select('table_one.*')\r\n ->join('table_two', 'table_two.owner_id', '=', 'table_one.id', 'LEFT OUTER')\r\n->paginate(20,['table_one.id'])\r\n```\r\nthen two queries will execute\r\n```\r\nselect count(*) as aggregate from `table_one` LEFT OUTER join `table_two` on `table_two`.`owner_id` = `table_two`.`id`\r\n```\r\nand\r\n```\r\nselect distinct `table_one`.* from `table_one` LEFT OUTER join `table_two` on `table_two`.`owner_id` = `table_two`.`id`\r\n```\r\nas the first request is incorrect, it should be of the form\r\n```\r\nselect count(distinct table_one.id) as aggregate from `table_one` LEFT OUTER join `table_two` on `table_two`.`owner_id` = `table_two`.`id`\r\n```", "comments": [ { "body": "Why would it be a count?", "created_at": "2017-09-19T11:05:05Z" }, { "body": "A count query is required to calculate the total number of rows. The second query fetches the actual data for the page. The second query looks like it is missing a LIMIT clause in this issue, but I think that is a authoring issue and not related to the reported issue.\r\n\r\nThe issue seems to be the logic that rewrites the query `SELECT DISTINCT *` into a `SELECT COUNT(*)` instead of understanding that it needs to keep the DISTINCT part.\r\n\r\nRelated: [Builder::runPaginationCountQuery](https://github.com/laravel/framework/blob/997e67cc2001006a43b73eaedf17fa1a2555fd66/src/Illuminate/Database/Query/Builder.php#L1785-L1791)", "created_at": "2017-09-19T14:48:47Z" }, { "body": "@Dylan-DPC if there are 2 lines in the second table, the first request for count will return 2, but the second query will return 1 model.\r\ncompare the two functions and understand that there is a mistake\r\nQuery Builder\r\nhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Query/Builder.php#L1718\r\nEloquent Query Builder\r\nhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Builder.php#L683", "created_at": "2017-09-20T03:45:03Z" }, { "body": "I don't see this as a bug actually. It can be enhanced/improved though. Feel free to send in a PR or make a proposal on laravel/internals.", "created_at": "2017-09-20T15:34:39Z" }, { "body": "Well, it returns wrong values. Can we update the docs and state that paginate() does not support joins/distinct/whatever it is in this case that is messing with the result?", "created_at": "2017-09-20T15:38:30Z" }, { "body": "yeah that's better @sisve ", "created_at": "2017-09-20T15:47:26Z" }, { "body": "it is distinct that breaks this\r\n\r\nit looks like the regular query builder paginate method allows for passing fields to count on, but the eloquent builder always does count(*)\r\n\r\nit looks like a fairly simple fix to mirror the behaviour of query builder (not completely sure why it isnt just delegating to that anyway tbh), but guessing changing behaviour of eloquent methods is breaking change, even if it is actually fixing a bug\r\n\r\nhttps://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Query/Builder.php#L1722\r\nhttps://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Eloquent/Builder.php#L708\r\n\r\n@Dylan-DPC not really sure how this isnt a bug. paginator is getting the wrong value for total count, which then causes it to generate links for more pages than there are results for\r\n\r\n\r\n", "created_at": "2017-10-30T15:31:48Z" }, { "body": "Paginator isn't expected to work with joins/distincts, etc. May be it isn't documented enough. ", "created_at": "2017-10-30T15:42:50Z" }, { "body": "A PR that would fix this was merged into the master branch. This will be released in the next version of Laravel.", "created_at": "2019-06-13T14:01:31Z" } ], "number": 21242, "title": "Incorrect work pagination Eloquent" }
{ "body": "fixes #21242\r\n\r\nif distinct is being used in the query, then it will count the models primary key rather than * to avoid counting the same row multiple times and generating links to pages which dont exist", "number": 21899, "review_comments": [], "title": "Fix pagination when using distinct" }
{ "commits": [ { "message": "Fix pagination when using distinct\n\nfixes #21242\r\n\r\nif distinct is being used in the query, then it will count the models primary key rather than * to avoid counting the same row multiple times and generating links to pages which dont exist" }, { "message": "fix styling" }, { "message": "style ci" } ], "files": [ { "diff": "@@ -705,7 +705,13 @@ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page',\n \n $perPage = $perPage ?: $this->model->getPerPage();\n \n- $results = ($total = $this->toBase()->getCountForPagination())\n+ $query = $this->toBase();\n+\n+ $count = $query->distinct\n+ ? [sprintf('%s.%s', $this->model->getTable(), $this->model->getKeyName())]\n+ : $columns;\n+\n+ $results = ($total = $query->getCountForPagination($count))\n ? $this->forPage($page, $perPage)->get($columns)\n : $this->model->newCollection();\n ", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.5.7 and before\r\n- PHP Version: 7.1\r\n- Database Driver & Version: MySQL 5.6.3\r\n\r\n### Description:\r\nThis is a really basic example, but here goes.\r\n\r\nSay you have a `users` table and an `orders` table, and you have a feature where I can refer a friend to order a product, on the `orders` table you may have `referrer_id` column which stores the `user_id` of the user that initiated the referral.\r\n\r\nGiven that scenario, you could potentially have a relationship on the `User` model that looks like this\r\n\r\n```php\r\npublic function referrals()\r\n{\r\n return $this->hasManyThrough(self::class, Order::class, 'referrer_id', 'id');\r\n}\r\n```\r\n\r\nThen, you may do something like this to get all Users that have referred someone...\r\n\r\n```php\r\n$users_that_have_referred = User::has('referrals')->get();\r\n```\r\n\r\nThis will return incorrect results, it will just return **all** users.\r\n\r\nThe SQL generated looks like this...\r\n\r\n```sql\r\nselect * from `users` where exists (select * from `users` inner join `orders` on `orders`.`id` = `users`.`id` where `users`.`id` = `orders`.`referrer_id`)\r\n```\r\n\r\nThe problem with this is that the outer query `users` table conflicts with the inner query's `users` table.\r\n\r\nTo get that query to actually work, you would need to something like aliasing the outer table name like this....\r\n```sql\r\nselect * from `users` as `users_outer` where exists (select * from `users` inner join `orders` on `orders`.`id` = `users`.`id` where `users_outer`.`id` = `orders`.`referrer_id`)\r\n```\r\n\r\n### Steps To Reproduce:\r\nI have setup a repo with this all setup ready for testing, it just dumps the results from the `web.php` route file.\r\n```shell\r\ngit clone https://github.com/JayBizzle/HasManyThroughBug.git\r\ncd HasManyThroughBug\r\ncomposer install\r\nphp artisan key:generate\r\nphp artisan migrate\r\nphp artisan serve\r\n```", "comments": [ { "body": "Same problem over here with a different database structure.\r\n\r\nWhen using a `BelongsTo` relation on itself, it doesn't alias the related table. \r\n\r\n```\r\npublic function parent()\r\n{\r\n return $this->belongsTo(self::class, 'entity_id');\r\n}\r\n```\r\n\r\nWhen using the given relation on a table (id, entity_id, flag, slug, timestamps), in combination with this: `$model->doesntHave('parent')`, it returns an error:\r\n\r\n```\r\nSQLSTATE[42S22]: Column not found: 1054 Unknown column 'laravel_reserved_0.id' in 'where clause' (SQL: select * from `entities` where `flag` = leaflet_category and not exists (select * from `entities` where updated_at >= 1970-01-01 01:00:00 and `laravel_reserved_0`.`id` = `entities`.`entity_id` and `laravel_reserved_0`.`deleted_at` is null) and `entities`.`deleted_at` is null)\r\n```\r\n\r\nLooks like it's not giving the subquery the alias it needs to the table.", "created_at": "2017-09-25T09:12:20Z" }, { "body": "I've updated the sample repo to make the issue a little more obvious (see above for details on how to replicate the issue)\r\n\r\nhttps://github.com/JayBizzle/HasManyThroughBug\r\n\r\n@themsaid Would like the hear your thoughts on this? Either just to know if it is possible to fix, or if it is a `no-fix` issue.\r\n\r\nThanks", "created_at": "2017-10-18T21:28:08Z" }, { "body": "Not quite sure but I think it's worth an attempt, feel free to open a PR with the idea of aliasing when you get the chance.", "created_at": "2017-10-20T12:29:04Z" }, { "body": "Thanks! I'll try take a look when I get the chance to sit down and get my head around it. Unfortunately, the query builder is one of my weakest Laravel knowledge areas.", "created_at": "2017-10-20T20:11:45Z" }, { "body": "Gave myself a quick crash course in the query builder and I seem to have fixed this issue. Will take me a couple of days to tidy it up, test it properly and put together a proper PR...watch this space 👍 ", "created_at": "2017-10-20T22:19:46Z" }, { "body": "PR submitted #21792", "created_at": "2017-10-23T19:02:48Z" }, { "body": "Fixed in #21883", "created_at": "2017-11-02T13:53:19Z" } ], "number": 21259, "title": "[Bug] Self-referencing HasManyThrough relationship" }
{ "body": "See #21259 for full-details.\r\n\r\nThis fix has been implemented in a similar way that table aliases are applied when using a self-referencing `BelongsTo` relationship.\r\n\r\nI have targeted this at 5.5, but not sure if this is classed as a breaking change as some people may be relying on the current broken behaviour. If so, I can target this at 5.6 no problem.", "number": 21792, "review_comments": [], "title": "[5.5] Use table aliases when calling a self-referencing HasManyThrough" }
{ "commits": [ { "message": "Use table aliases when calling a self-referencing HasManyThrough relationship" }, { "message": "Add integration test" }, { "message": "add `notifyNow` method to Notifiables (#21795)\n\nallows user to override notifications with the `ShouldQueue` interface, and send them immediately." }, { "message": "Create assertion to determine if a cookie is expired (#21793)\n\nGiven that the `\\Illuminate\\Cookie\\CookieJar::forget` method expires the\r\ngiven cookie to trigger its deletion, this will allow to test those\r\nscenarios.\r\n\r\nThis new assertion will\r\n\r\n- Fail if the cookie is not present at all.\r\n- Fail if the cookie is present, but it is not expired.\r\n- Pass if the cookie is present and is expired." }, { "message": "update v5.5 changelog" }, { "message": "Add assertion to verify that a cookie is missing (#21803)" }, { "message": "Add Type Hint to Model Factory Stub (#21810)\n\nI find myself adding this type hint to every model factory that I\r\ncreate to help IDEs auto complete the $factory object." }, { "message": "Set current user before firing authenticated event (#21790)" }, { "message": "allow the distinct validation rule to optionally ignore case (#21757)\n\nconform to style guide\r\n\r\nadd unicode support\r\n\r\nescape slashes in regular expression" }, { "message": "Minor accessibility improvements (#21817)" }, { "message": "[5.5] fix model refresh with global scopes (#21815)\n\n* fix model refresh with global scopes\r\n\r\n* fix style\r\n\r\n* fix style" }, { "message": "Remove non-existent argument (#21814)" }, { "message": " fix scheduling a non queueable job (#21820)" }, { "message": "version" }, { "message": " update release notes" }, { "message": " update release notes" }, { "message": "Fixed typo in comments of Queue/Worker.php" }, { "message": "Update DatabaseNotificationCollection.php (#21841)\n\nImprove documentation :D" }, { "message": "formatting" }, { "message": "Fix controller does not exist issue (#21844)" }, { "message": "Adds “kin” to uncountable list (#21843)\n\nSigned-off-by: Jesse Schutt <jesse.schutt@zaengle.com>" }, { "message": "Removed uneeded doc" }, { "message": "Fix Resource `collection()` phpdoc return type (#21866)" }, { "message": "update docblock to include the Throwable (#21878)\n\n* update dockblock to include the Throwable\r\n\r\n* Update helpers.php" }, { "message": "Add possible thrown exception to the docblock of function (#21877)\n\n* Add possible thrown exception to the docblock of function\r\n\r\n* Update helpers.php" }, { "message": " add EloquentHasManyThroughTest" }, { "message": "Apply fixes from StyleCI (#21880)" }, { "message": "naming" } ], "files": [ { "diff": "@@ -1,5 +1,24 @@\n # Release Notes for 5.5.x\n \n+## v5.5.19 (2017-10-25)\n+\n+### Added\n+- Added `MakesHttpRequests::followingRedirects()` method ([#21771](https://github.com/laravel/framework/pull/21771))\n+- Added `MakesHttpRequests::from()` method ([#21788](https://github.com/laravel/framework/pull/21788))\n+- Added `notifyNow()` method to notifiables ([#21795](https://github.com/laravel/framework/pull/21795))\n+- Added `TestResponse::assertCookieExpired()` method ([#21793](https://github.com/laravel/framework/pull/21793))\n+- Added `TestResponse::assertCookieMissing()` method ([#21803](https://github.com/laravel/framework/pull/21803))\n+\n+### Changed\n+- Allow the distinct validation rule to optionally ignore case ([#21757](https://github.com/laravel/framework/pull/21757))\n+\n+### Fixed\n+- Excluding `spatial_ref_sys` table from `migrate:fresh` ([#21778](https://github.com/laravel/framework/pull/21778))\n+- Fixed issue with `SessionGuard` setting the logged in user after firing the `Authenticated` event ([#21790](https://github.com/laravel/framework/pull/21790))\n+- Fixed issue with `Model::refresh()` when model has a global scope ([#21815](https://github.com/laravel/framework/pull/21815))\n+- Fixed scheduling a non-queuable job ([#21820](https://github.com/laravel/framework/pull/21820))\n+\n+\n ## v5.5.18 (2017-10-19)\n \n ### Added", "filename": "CHANGELOG-5.5.md", "status": "modified" }, { "diff": "@@ -20,7 +20,7 @@\n <div class=\"navbar-header\">\n \n <!-- Collapsed Hamburger -->\n- <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#app-navbar-collapse\">\n+ <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#app-navbar-collapse\" aria-expanded=\"false\">\n <span class=\"sr-only\">Toggle Navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n@@ -47,11 +47,11 @@\n <li><a href=\"{{ route('register') }}\">Register</a></li>\n @else\n <li class=\"dropdown\">\n- <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-expanded=\"false\">\n+ <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-expanded=\"false\" aria-haspopup=\"true\">\n {{ Auth::user()->name }} <span class=\"caret\"></span>\n </a>\n \n- <ul class=\"dropdown-menu\" role=\"menu\">\n+ <ul class=\"dropdown-menu\">\n <li>\n <a href=\"{{ route('logout') }}\"\n onclick=\"event.preventDefault();", "filename": "src/Illuminate/Auth/Console/stubs/make/views/layouts/app.stub", "status": "modified" }, { "diff": "@@ -127,11 +127,9 @@ public function user()\n // First we will try to load the user using the identifier in the session if\n // one exists. Otherwise we will check for a \"remember me\" cookie in this\n // request, and if one exists, attempt to retrieve the user using that.\n- $user = null;\n-\n if (! is_null($id)) {\n- if ($user = $this->provider->retrieveById($id)) {\n- $this->fireAuthenticatedEvent($user);\n+ if ($this->user = $this->provider->retrieveById($id)) {\n+ $this->fireAuthenticatedEvent($this->user);\n }\n }\n \n@@ -140,17 +138,17 @@ public function user()\n // the application. Once we have a user we can return it to the caller.\n $recaller = $this->recaller();\n \n- if (is_null($user) && ! is_null($recaller)) {\n- $user = $this->userFromRecaller($recaller);\n+ if (is_null($this->user) && ! is_null($recaller)) {\n+ $this->user = $this->userFromRecaller($recaller);\n \n- if ($user) {\n- $this->updateSession($user->getAuthIdentifier());\n+ if ($this->user) {\n+ $this->updateSession($this->user->getAuthIdentifier());\n \n- $this->fireLoginEvent($user, true);\n+ $this->fireLoginEvent($this->user, true);\n }\n }\n \n- return $this->user = $user;\n+ return $this->user;\n }\n \n /**", "filename": "src/Illuminate/Auth/SessionGuard.php", "status": "modified" }, { "diff": "@@ -65,7 +65,7 @@ public function routes(array $attributes = null)\n $attributes = $attributes ?: ['middleware' => ['web']];\n \n $this->app['router']->group($attributes, function ($router) {\n- $router->post('/broadcasting/auth', BroadcastController::class.'@authenticate');\n+ $router->post('/broadcasting/auth', '\\\\'.BroadcastController::class.'@authenticate');\n });\n }\n ", "filename": "src/Illuminate/Broadcasting/BroadcastManager.php", "status": "modified" }, { "diff": "@@ -4,6 +4,7 @@\n \n use Illuminate\\Console\\Application;\n use Illuminate\\Container\\Container;\n+use Illuminate\\Contracts\\Queue\\ShouldQueue;\n use Symfony\\Component\\Process\\ProcessUtils;\n \n class Schedule\n@@ -80,7 +81,13 @@ public function command($command, array $parameters = [])\n public function job($job, $queue = null)\n {\n return $this->call(function () use ($job, $queue) {\n- dispatch(is_string($job) ? resolve($job) : $job)->onQueue($queue);\n+ $job = is_string($job) ? resolve($job) : $job;\n+\n+ if ($job instanceof ShouldQueue) {\n+ dispatch($job)->onQueue($queue);\n+ } else {\n+ dispatch_now($job);\n+ }\n })->name(is_string($job) ? $job : get_class($job));\n }\n ", "filename": "src/Illuminate/Console/Scheduling/Schedule.php", "status": "modified" }, { "diff": "@@ -999,7 +999,9 @@ public function refresh()\n return $this;\n }\n \n- $this->setRawAttributes(static::findOrFail($this->getKey())->attributes);\n+ $this->setRawAttributes(\n+ static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes\n+ );\n \n $this->load(collect($this->relations)->except('pivot')->keys()->toArray());\n ", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -52,6 +52,13 @@ class HasManyThrough extends Relation\n */\n protected $secondLocalKey;\n \n+ /**\n+ * The count of self joins.\n+ *\n+ * @var int\n+ */\n+ protected static $selfJoinCount = 0;\n+\n /**\n * Create a new has many through relationship instance.\n *\n@@ -427,11 +434,46 @@ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery,\n {\n $this->performJoin($query);\n \n+ if ($parentQuery->getQuery()->from == $query->getQuery()->from) {\n+ return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);\n+ }\n+\n return $query->select($columns)->whereColumn(\n $this->getExistenceCompareKey(), '=', $this->getQualifiedFirstKeyName()\n );\n }\n \n+ /**\n+ * Add the constraints for a relationship query on the same table.\n+ *\n+ * @param \\Illuminate\\Database\\Eloquent\\Builder $query\n+ * @param \\Illuminate\\Database\\Eloquent\\Builder $parentQuery\n+ * @param array|mixed $columns\n+ * @return \\Illuminate\\Database\\Eloquent\\Builder\n+ */\n+ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])\n+ {\n+ $parentQuery->select($columns)->from(\n+ $query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()\n+ );\n+\n+ $parentQuery->getModel()->setTable($hash);\n+\n+ return $query->whereColumn(\n+ $hash.'.'.$query->getModel()->getKeyName(), '=', $this->getQualifiedFirstKeyName()\n+ );\n+ }\n+\n+ /**\n+ * Get a relationship join table hash.\n+ *\n+ * @return string\n+ */\n+ public function getRelationCountHash()\n+ {\n+ return 'laravel_reserved_'.static::$selfJoinCount++;\n+ }\n+\n /**\n * Get the key for comparing against the parent key in \"has\" query.\n *", "filename": "src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php", "status": "modified" }, { "diff": "@@ -29,7 +29,7 @@ class Application extends Container implements ApplicationContract, HttpKernelIn\n *\n * @var string\n */\n- const VERSION = '5.5.18';\n+ const VERSION = '5.5.19';\n \n /**\n * The base path for the Laravel installation.", "filename": "src/Illuminate/Foundation/Application.php", "status": "modified" }, { "diff": "@@ -5,6 +5,7 @@\n use Closure;\n use Illuminate\\Support\\Arr;\n use Illuminate\\Support\\Str;\n+use Illuminate\\Support\\Carbon;\n use Illuminate\\Contracts\\View\\View;\n use Illuminate\\Support\\Traits\\Macroable;\n use PHPUnit\\Framework\\Assert as PHPUnit;\n@@ -170,6 +171,45 @@ public function assertCookie($cookieName, $value = null, $encrypted = true)\n return $this;\n }\n \n+ /**\n+ * Asserts that the response contains the given cookie and is expired.\n+ *\n+ * @param string $cookieName\n+ * @return $this\n+ */\n+ public function assertCookieExpired($cookieName)\n+ {\n+ PHPUnit::assertNotNull(\n+ $cookie = $this->getCookie($cookieName),\n+ \"Cookie [{$cookieName}] not present on response.\"\n+ );\n+\n+ $expiresAt = Carbon::createFromTimestamp($cookie->getExpiresTime());\n+\n+ PHPUnit::assertTrue(\n+ $expiresAt->lessThan(Carbon::now()),\n+ \"Cookie [{$cookieName}] is not expired, it expires at [{$expiresAt}].\"\n+ );\n+\n+ return $this;\n+ }\n+\n+ /**\n+ * Asserts that the response does not contains the given cookie.\n+ *\n+ * @param string $cookieName\n+ * @return $this\n+ */\n+ public function assertCookieMissing($cookieName)\n+ {\n+ PHPUnit::assertNull(\n+ $this->getCookie($cookieName),\n+ \"Cookie [{$cookieName}] is present on response.\"\n+ );\n+\n+ return $this;\n+ }\n+\n /**\n * Get the given cookie from the response.\n *", "filename": "src/Illuminate/Foundation/Testing/TestResponse.php", "status": "modified" }, { "diff": "@@ -72,7 +72,7 @@ public static function make(...$parameters)\n * Create new anonymous resource collection.\n *\n * @param mixed $resource\n- * @return mixed\n+ * @return \\Illuminate\\Http\\Resources\\Json\\AnonymousResourceCollection\n */\n public static function collection($resource)\n {", "filename": "src/Illuminate/Http/Resources/Json/Resource.php", "status": "modified" }, { "diff": "@@ -7,7 +7,7 @@\n class DatabaseNotificationCollection extends Collection\n {\n /**\n- * Mark all notification as read.\n+ * Mark all notifications as read.\n *\n * @return void\n */", "filename": "src/Illuminate/Notifications/DatabaseNotificationCollection.php", "status": "modified" }, { "diff": "@@ -18,6 +18,18 @@ public function notify($instance)\n app(Dispatcher::class)->send($this, $instance);\n }\n \n+ /**\n+ * Send the given notification immediately.\n+ *\n+ * @param mixed $instance\n+ * @param array|null $channels\n+ * @return void\n+ */\n+ public function notifyNow($instance, array $channels = null)\n+ {\n+ app(Dispatcher::class)->sendNow($this, $instance, $channels);\n+ }\n+\n /**\n * Get the notification routing information for the given driver.\n *", "filename": "src/Illuminate/Notifications/RoutesNotifications.php", "status": "modified" }, { "diff": "@@ -306,7 +306,7 @@ public function process($connectionName, $job, WorkerOptions $options)\n {\n try {\n // First we will raise the before job event and determine if the job has already ran\n- // over the its maximum attempt limit, which could primarily happen if the job is\n+ // over its maximum attempt limits, which could primarily happen when this job is\n // continually timing out and not actually throwing any exceptions from itself.\n $this->raiseBeforeJobEvent($connectionName, $job);\n ", "filename": "src/Illuminate/Queue/Worker.php", "status": "modified" }, { "diff": "@@ -31,6 +31,7 @@ class Pluralizer\n 'hardware',\n 'information',\n 'jedi',\n+ 'kin',\n 'knowledge',\n 'love',\n 'metadata',", "filename": "src/Illuminate/Support/Pluralizer.php", "status": "modified" }, { "diff": "@@ -1046,6 +1046,7 @@ function tap($value, $callback = null)\n * @param \\Throwable|string $exception\n * @param array ...$parameters\n * @return void\n+ * @throws \\Throwable\n */\n function throw_if($boolean, $exception, ...$parameters)\n {\n@@ -1063,6 +1064,7 @@ function throw_if($boolean, $exception, ...$parameters)\n * @param \\Throwable|string $exception\n * @param array ...$parameters\n * @return void\n+ * @throws \\Throwable\n */\n function throw_unless($boolean, $exception, ...$parameters)\n {", "filename": "src/Illuminate/Support/helpers.php", "status": "modified" }, { "diff": "@@ -528,6 +528,10 @@ public function validateDistinct($attribute, $value, $parameters)\n return $key != $attribute && (bool) preg_match('#^'.$pattern.'\\z#u', $key);\n });\n \n+ if (in_array('ignore_case', $parameters)) {\n+ return empty(preg_grep('/'.preg_quote($value, '/').'/iu', $data));\n+ }\n+\n return ! in_array($value, array_values($data));\n }\n ", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -56,6 +56,13 @@ public function createSchema()\n $table->string('shortname');\n $table->timestamps();\n });\n+\n+ $this->schema()->create('orders', function ($table) {\n+ $table->increments('id');\n+ $table->integer('user_id');\n+ $table->integer('referrer_id')->nullable();\n+ $table->timestamps();\n+ });\n }\n \n /**\n@@ -68,6 +75,7 @@ public function tearDown()\n $this->schema()->drop('users');\n $this->schema()->drop('posts');\n $this->schema()->drop('countries');\n+ $this->schema()->drop('orders');\n }\n \n public function testItLoadsAHasManyThroughRelationWithCustomKeys()\n@@ -183,6 +191,26 @@ public function testEagerLoadingLoadsRelatedModelsCorrectly()\n $this->assertCount(2, $country->posts);\n }\n \n+ public function testSelfReferencingRelation()\n+ {\n+ HasManyThroughTestUser::insert([\n+ ['id' => 1, 'email' => 'taylor@laravel.com', 'country_id' => 1, 'country_short' => 'UK'],\n+ ['id' => 2, 'email' => 'mohammed@laravel.com', 'country_id' => 1, 'country_short' => 'UK'],\n+ ['id' => 3, 'email' => 'mark@laravel.com', 'country_id' => 1, 'country_short' => 'UK'],\n+ ]);\n+\n+ HasManyThroughTestOrder::insert([\n+ ['id' => 1, 'user_id' => 1, 'referrer_id' => 2],\n+ ['id' => 2, 'user_id' => 1, 'referrer_id' => null],\n+ ['id' => 3, 'user_id' => 2, 'referrer_id' => 3],\n+ ]);\n+\n+ $users = HasManyThroughTestUser::has('referrals')->get();\n+\n+ $this->assertCount(2, $users);\n+ $this->assertEquals([2, 3], $users->pluck('id')->toArray());\n+ }\n+\n /**\n * Helpers...\n */\n@@ -279,6 +307,11 @@ public function posts()\n {\n return $this->hasMany(HasManyThroughTestPost::class, 'user_id');\n }\n+\n+ public function referrals()\n+ {\n+ return $this->hasManyThrough(self::class, HasManyThroughTestOrder::class, 'referrer_id', 'id');\n+ }\n }\n \n /**\n@@ -413,3 +446,12 @@ public function users()\n return $this->hasMany(HasManyThroughSoftDeletesTestUser::class, 'country_id');\n }\n }\n+\n+/**\n+ * Eloquent Models...\n+ */\n+class HasManyThroughTestOrder extends Eloquent\n+{\n+ protected $table = 'orders';\n+ protected $guarded = [];\n+}", "filename": "tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php", "status": "modified" }, { "diff": "@@ -17,8 +17,7 @@ public function testBasicCreateDumpsAutoload()\n {\n $command = new MigrateMakeCommand(\n $creator = m::mock('Illuminate\\Database\\Migrations\\MigrationCreator'),\n- $composer = m::mock('Illuminate\\Support\\Composer'),\n- __DIR__.'/vendor'\n+ $composer = m::mock('Illuminate\\Support\\Composer')\n );\n $app = new \\Illuminate\\Foundation\\Application;\n $app->useDatabasePath(__DIR__);\n@@ -33,8 +32,7 @@ public function testBasicCreateGivesCreatorProperArguments()\n {\n $command = new MigrateMakeCommand(\n $creator = m::mock('Illuminate\\Database\\Migrations\\MigrationCreator'),\n- m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing(),\n- __DIR__.'/vendor'\n+ m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing()\n );\n $app = new \\Illuminate\\Foundation\\Application;\n $app->useDatabasePath(__DIR__);\n@@ -48,8 +46,7 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenTableIsSet()\n {\n $command = new MigrateMakeCommand(\n $creator = m::mock('Illuminate\\Database\\Migrations\\MigrationCreator'),\n- m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing(),\n- __DIR__.'/vendor'\n+ m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing()\n );\n $app = new \\Illuminate\\Foundation\\Application;\n $app->useDatabasePath(__DIR__);\n@@ -63,8 +60,7 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenCreateTablePattern\n {\n $command = new MigrateMakeCommand(\n $creator = m::mock('Illuminate\\Database\\Migrations\\MigrationCreator'),\n- m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing(),\n- __DIR__.'/vendor'\n+ m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing()\n );\n $app = new \\Illuminate\\Foundation\\Application;\n $app->useDatabasePath(__DIR__);\n@@ -78,8 +74,7 @@ public function testCanSpecifyPathToCreateMigrationsIn()\n {\n $command = new MigrateMakeCommand(\n $creator = m::mock('Illuminate\\Database\\Migrations\\MigrationCreator'),\n- m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing(),\n- __DIR__.'/vendor'\n+ m::mock('Illuminate\\Support\\Composer')->shouldIgnoreMissing()\n );\n $app = new \\Illuminate\\Foundation\\Application;\n $command->setLaravel($app);", "filename": "tests/Database/DatabaseMigrationMakeCommandTest.php", "status": "modified" }, { "diff": "@@ -16,7 +16,7 @@ public function tearDown()\n \n public function testBasicMigrationsCallMigratorWithProperArguments()\n {\n- $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'), __DIR__.'/vendor');\n+ $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'));\n $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);\n $app->useDatabasePath(__DIR__);\n $command->setLaravel($app);\n@@ -31,7 +31,7 @@ public function testBasicMigrationsCallMigratorWithProperArguments()\n \n public function testMigrationRepositoryCreatedWhenNecessary()\n {\n- $params = [$migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'), __DIR__.'/vendor'];\n+ $params = [$migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator')];\n $command = $this->getMockBuilder('Illuminate\\Database\\Console\\Migrations\\MigrateCommand')->setMethods(['call'])->setConstructorArgs($params)->getMock();\n $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);\n $app->useDatabasePath(__DIR__);\n@@ -48,7 +48,7 @@ public function testMigrationRepositoryCreatedWhenNecessary()\n \n public function testTheCommandMayBePretended()\n {\n- $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'), __DIR__.'/vendor');\n+ $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'));\n $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);\n $app->useDatabasePath(__DIR__);\n $command->setLaravel($app);\n@@ -63,7 +63,7 @@ public function testTheCommandMayBePretended()\n \n public function testTheDatabaseMayBeSet()\n {\n- $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'), __DIR__.'/vendor');\n+ $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'));\n $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);\n $app->useDatabasePath(__DIR__);\n $command->setLaravel($app);\n@@ -78,7 +78,7 @@ public function testTheDatabaseMayBeSet()\n \n public function testStepMayBeSet()\n {\n- $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'), __DIR__.'/vendor');\n+ $command = new MigrateCommand($migrator = m::mock('Illuminate\\Database\\Migrations\\Migrator'));\n $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);\n $app->useDatabasePath(__DIR__);\n $command->setLaravel($app);", "filename": "tests/Database/DatabaseMigrationMigrateCommandTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,79 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\EloquentHasManyThroughTest;\n+\n+use Orchestra\\Testbench\\TestCase;\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Eloquent\\Model;\n+\n+/**\n+ * @group integration\n+ */\n+class EloquentHasManyThroughTest extends TestCase\n+{\n+ protected function getEnvironmentSetUp($app)\n+ {\n+ $app['config']->set('app.debug', 'true');\n+\n+ $app['config']->set('database.default', 'testbench');\n+\n+ $app['config']->set('database.connections.testbench', [\n+ 'driver' => 'sqlite',\n+ 'database' => ':memory:',\n+ 'prefix' => '',\n+ ]);\n+ }\n+\n+ public function setUp()\n+ {\n+ parent::setUp();\n+\n+ Schema::create('users', function ($table) {\n+ $table->increments('id');\n+ $table->integer('team_id')->nullable();\n+ $table->string('name');\n+ });\n+\n+ Schema::create('teams', function ($table) {\n+ $table->increments('id');\n+ $table->integer('owner_id');\n+ });\n+ }\n+\n+ /**\n+ * @test\n+ */\n+ public function basic_create_and_retrieve()\n+ {\n+ $user = User::create(['name' => str_random()]);\n+\n+ $team1 = Team::create(['owner_id' => $user->id]);\n+ $team2 = Team::create(['owner_id' => $user->id]);\n+\n+ $mate1 = User::create(['name' => str_random(), 'team_id' => $team1->id]);\n+ $mate2 = User::create(['name' => str_random(), 'team_id' => $team2->id]);\n+\n+ $notMember = User::create(['name' => str_random()]);\n+\n+ $this->assertEquals([$mate1->id, $mate2->id], $user->teamMates->pluck('id')->toArray());\n+ }\n+}\n+\n+class User extends Model\n+{\n+ public $table = 'users';\n+ public $timestamps = false;\n+ protected $guarded = ['id'];\n+\n+ public function teamMates()\n+ {\n+ return $this->hasManyThrough(self::class, Team::class, 'owner_id', 'team_id');\n+ }\n+}\n+\n+class Team extends Model\n+{\n+ public $table = 'teams';\n+ public $timestamps = false;\n+ protected $guarded = ['id'];\n+}", "filename": "tests/Integration/Database/EloquentHasManyThroughTest.php", "status": "added" }, { "diff": "@@ -0,0 +1,84 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\EloquentModelRefreshTest;\n+\n+use Orchestra\\Testbench\\TestCase;\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Database\\Eloquent\\SoftDeletes;\n+\n+/**\n+ * @group integration\n+ */\n+class EloquentModelRefreshTest extends TestCase\n+{\n+ protected function getEnvironmentSetUp($app)\n+ {\n+ $app['config']->set('app.debug', 'true');\n+\n+ $app['config']->set('database.default', 'testbench');\n+\n+ $app['config']->set('database.connections.testbench', [\n+ 'driver' => 'sqlite',\n+ 'database' => ':memory:',\n+ 'prefix' => '',\n+ ]);\n+ }\n+\n+ public function setUp()\n+ {\n+ parent::setUp();\n+\n+ Schema::create('posts', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('title');\n+ $table->timestamps();\n+ $table->softDeletes();\n+ });\n+ }\n+\n+ /**\n+ * @test\n+ */\n+ public function it_refreshes_model_excluded_by_global_scope()\n+ {\n+ $post = Post::create(['title' => 'mohamed']);\n+\n+ $post->refresh();\n+ }\n+\n+ /**\n+ * @test\n+ */\n+ public function it_refreshes_a_soft_deleted_model()\n+ {\n+ $post = Post::create(['title' => 'said']);\n+\n+ Post::find($post->id)->delete();\n+\n+ $this->assertFalse($post->trashed());\n+\n+ $post->refresh();\n+\n+ $this->assertTrue($post->trashed());\n+ }\n+}\n+\n+class Post extends Model\n+{\n+ public $table = 'posts';\n+ public $timestamps = true;\n+ protected $guarded = ['id'];\n+\n+ use SoftDeletes;\n+\n+ protected static function boot()\n+ {\n+ parent::boot();\n+\n+ static::addGlobalScope('age', function ($query) {\n+ $query->where('title', '!=', 'mohamed');\n+ });\n+ }\n+}", "filename": "tests/Integration/Database/EloquentModelRefreshTest.php", "status": "added" }, { "diff": "@@ -28,6 +28,19 @@ public function testNotificationCanBeDispatched()\n $notifiable->notify($instance);\n }\n \n+ public function testNotificationCanBeSentNow()\n+ {\n+ $container = new Container;\n+ $factory = Mockery::mock(Dispatcher::class);\n+ $container->instance(Dispatcher::class, $factory);\n+ $notifiable = new RoutesNotificationsTestInstance;\n+ $instance = new stdClass;\n+ $factory->shouldReceive('sendNow')->with($notifiable, $instance, null);\n+ Container::setInstance($container);\n+\n+ $notifiable->notifyNow($instance);\n+ }\n+\n public function testNotificationOptionRouting()\n {\n $instance = new RoutesNotificationsTestInstance;", "filename": "tests/Notifications/NotificationRoutesNotificationsTest.php", "status": "modified" }, { "diff": "@@ -1477,12 +1477,24 @@ public function testValidateDistinct()\n $v = new Validator($trans, ['foo' => ['foo', 'foo']], ['foo.*' => 'distinct']);\n $this->assertFalse($v->passes());\n \n+ $v = new Validator($trans, ['foo' => ['à', 'À']], ['foo.*' => 'distinct:ignore_case']);\n+ $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, ['foo' => ['f/oo', 'F/OO']], ['foo.*' => 'distinct:ignore_case']);\n+ $this->assertFalse($v->passes());\n+\n $v = new Validator($trans, ['foo' => ['foo', 'bar']], ['foo.*' => 'distinct']);\n $this->assertTrue($v->passes());\n \n $v = new Validator($trans, ['foo' => ['bar' => ['id' => 1], 'baz' => ['id' => 1]]], ['foo.*.id' => 'distinct']);\n $this->assertFalse($v->passes());\n \n+ $v = new Validator($trans, ['foo' => ['bar' => ['id' => 'qux'], 'baz' => ['id' => 'QUX']]], ['foo.*.id' => 'distinct']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['foo' => ['bar' => ['id' => 'qux'], 'baz' => ['id' => 'QUX']]], ['foo.*.id' => 'distinct:ignore_case']);\n+ $this->assertFalse($v->passes());\n+\n $v = new Validator($trans, ['foo' => ['bar' => ['id' => 1], 'baz' => ['id' => 2]]], ['foo.*.id' => 'distinct']);\n $this->assertTrue($v->passes());\n ", "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": "When using the `assertAuthenticatedAs` method, if the user is not logged, the output message was strange. This PR introduce a new check to ensure the user is logged.\r\n\r\nBefore :\r\n```\r\nTests\\Feature\\RegisterControllerTest::testRegisterWithSpecificRole with data set #3 (5)\r\nThe currently authenticated user is not who was expected\r\nFailed asserting that Act\\User Object (...) is an instance of class \"Illuminate\\Foundation\\Testing\\TestCase\".\r\n```\r\n\r\nAfter :\r\n```\r\nTests\\Feature\\RegisterControllerTest::testRegisterWithSpecificRole with data set #3 (5)\r\nThe current user is not authenticated.\r\n```", "number": 21377, "review_comments": [], "title": "[5.5] Ensure user is logged before expecting user instance type." }
{ "commits": [ { "message": "Ensure user is logged.\n\nCheck the user is logged before expecting instance type." }, { "message": "Update InteractsWithAuthentication.php" } ], "files": [ { "diff": "@@ -82,6 +82,8 @@ public function assertAuthenticatedAs($user, $guard = null)\n {\n $expected = $this->app->make('auth')->guard($guard)->user();\n \n+ $this->assertNotNull($expected, 'The current user is not authenticated.');\n+\n $this->assertInstanceOf(\n get_class($expected), $user,\n 'The currently authenticated user is not who was expected'", "filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.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": "If a custom error handler throws a PHP 7 `Error`, `Handler::formatException()` causes this to happen:\r\n\r\n```\r\nPHP Fatal error: Uncaught TypeError: Argument 1 passed to Illuminate\\Exception\\Handler::formatException() must be an instance of Exception, instance of Error given, called in /vagrant/vendor/laravel/framework/src/Illuminate/Exception/Handler.php on line 262 and defined in /vagrant/vendor/laravel/framework/src/Illuminate/Exception/Handler.php:328\r\nStack trace:\r\n#0 /vagrant/vendor/laravel/framework/src/Illuminate/Exception/Handler.php(262): Illuminate\\Exception\\Handler->formatException(Object(Error))\r\n#1 /vagrant/vendor/laravel/framework/src/Illuminate/Exception/Handler.php(147): Illuminate\\Exception\\Handler->callCustomHandlers(Object(Error))\r\n#2 /vagrant/vendor/laravel/framework/src/Illuminate/Exception/Handler.php(171): Illuminate\\Exception\\Handler->handleException(Object(Error))\r\n#3 [internal function]: Illuminate\\Exception\\Handler->handleUncaughtException(Object(Error))\r\n#4 {main}\r\n thrown in /vagrant/vendor/laravel/framework/src/Illuminate/Exception/Handler.php on line 328\r\n```\r\n\r\nmasking what the actual `Error` that happened was. Simplest solution seemed to be to wrap the `Throwable` in `FatalThrowableError` before passing it along. That seemed go along with what @GrahamCampbell mentioned in #15994, though that was a different situation.", "number": 21208, "review_comments": [], "title": "[4.2] Wrap Throwables thrown from custom handlers in FatalThrowableError." }
{ "commits": [ { "message": "Wrap Throwables thrown from custom handlers in FatalThrowableError." } ], "files": [ { "diff": "@@ -259,6 +259,7 @@ protected function callCustomHandlers($exception, $fromConsole = false)\n \t\t\t}\n \t\t\tcatch (\\Throwable $e)\n \t\t\t{\n+\t\t\t\t$e = new FatalThrowableError($e);\n \t\t\t\t$response = $this->formatException($e);\n \t\t\t}\n ", "filename": "src/Illuminate/Exception/Handler.php", "status": "modified" }, { "diff": "@@ -41,4 +41,17 @@ public function testHandleErrorOptionalArguments()\n \t\t$this->assertSame('', $error->getFile(), 'error handler should use correct default path');\n \t\t$this->assertSame(0, $error->getLine(), 'error handler should use correct default line');\n \t}\n+\n+\tpublic function testHandleErrorThrowableThrownDuringCustomHandler()\n+\t{\n+\t\t// Regirster a handler that handles all errors and causes a new PHP 7\n+\t\t// Error to be thrown.\n+\t\t$this->handler->error(function () {\n+\t\t\tthrow new \\Error('No cookies for you!');\n+\t\t});\n+\n+\t\t$this->responsePreparer->shouldReceive('prepareResponse')->andReturn('Handled that!');\n+\t\t$result = $this->handler->handleException(new \\Error('PHP 7 Failure'));\n+\t\t$this->assertSame('Handled that!', $result);\n+\t}\n }", "filename": "tests/Exception/HandlerTest.php", "status": "modified" } ] }
{ "body": "In Laravel 5.2.39, my app has\n\n.env\n\n```\nAPP_URL=http://dev.env/smartbots\n```\n\nconfig/app.php\n\n```\n'url' => env('APP_URL'),\n```\n\napp/Http/routes.php\n\n```\nRoute::get('test', function () {\n dd(route('twilioVoiceRequest'));\n});\n\nRoute::get('/twilio-voice-request', function() {\n})->name('twilioVoiceRequest');\n```\n\nArtisan command (twilio:setup)\n\n```\npublic function handle()\n{\n dd(route('twilioVoiceRequest'));\n}\n```\n\nThis is what i got from test route\n![untitled](https://cloud.githubusercontent.com/assets/12293622/16362615/113bf142-3bde-11e6-8b24-a5c6c3950be1.png)\n\nand from php artisan twilio:setup\n![untitled2](https://cloud.githubusercontent.com/assets/12293622/16362620/28f9a612-3bde-11e6-9e68-78272f6bebf0.png)\n", "comments": [ { "body": "Try adding a trailing slash to the URL and/or running `php artisan config:cache`.\n", "created_at": "2016-06-26T15:07:45Z" }, { "body": "i tried it before, still the same result\n", "created_at": "2016-06-26T15:55:36Z" }, { "body": "This is definitely due to an out of date config cache otherwise the cli would have just generated localhost.\n", "created_at": "2016-06-26T15:59:33Z" }, { "body": "APP URL only work on domain level, right?\n", "created_at": "2016-06-26T16:03:18Z" }, { "body": "It should be defining the base URI?\n", "created_at": "2016-06-26T16:29:52Z" }, { "body": "We definitely don't recommend you run apps on sub-folders though.\n", "created_at": "2016-06-26T16:30:11Z" }, { "body": "`route()` helper use `toRoute()` and `getRouteDomain()` https://github.com/laravel/framework/blob/5.2/src/Illuminate/Routing/UrlGenerator.php#L324\n\nIs this a bug?\n", "created_at": "2016-06-26T16:58:19Z" }, { "body": "Yeh, I'd say so.\n", "created_at": "2016-06-27T15:07:48Z" }, { "body": "With support @GrahamCampbell I would suggest, leave a slash at trail,laravel will auto handle your route.\n", "created_at": "2016-07-02T11:07:33Z" }, { "body": "Changing `$this->request->root()` with `$this->request->url()` [here](https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/UrlGenerator.php#L619) seems to fix this issue. \n\nWould that be an acceptable solution for you @GrahamCampbell ? I've run the unit tests and nothing seems to break but I didn't have time yet to check if this part is covered on the tests yet.\n", "created_at": "2016-09-22T19:21:14Z" }, { "body": "Ok, after further testing the above is not the solution when not using the console. We'll have to find a different fix (and ideally add some test to cover this code).\n", "created_at": "2016-09-22T21:53:22Z" }, { "body": "The problem seems to come all the way from `Symfony\\Component\\HttpFoundation\\SymfonyRequest`, in order to get the baseUrl of the request, `SymfonyRequest` compares the values of `$_SERVER['SCRIPT_NAME']` and `$_SERVER['SCRIPT_FILENAME']`, and those aren't being set by `Illuminate\\Foundation\\Bootstrap\\SetRequestForConsole`.\n", "created_at": "2016-09-26T13:16:25Z" }, { "body": "I can't recreate this issue: http://d.pr/i/1bqOj\n", "created_at": "2016-09-28T18:21:24Z" }, { "body": "I don't think you understood well what the issue is.\n\nWhen the config value of `app.url` is set ot something else than a base domain (like `http://some-random-url.com/somethingelse/`), all the routes generated from console by the UrlGenerator remove the path. On the other hand, if your app is set to be accessed through that same path, the UrlGenerator creates correct paths.\n\nNow, in order to recreate it you'll have to add some path to your base url.\n", "created_at": "2016-09-28T19:47:02Z" }, { "body": "config('app.url');\nusing the config helper function works fine\n\nI had this issue with the Queues The url helper returns http://localhost \n", "created_at": "2016-10-06T18:17:30Z" }, { "body": "@engAhmad , if you don't have http[s]?:// prefix to your environment url laravel will not detect it and overwrite it with http://localhost.\n", "created_at": "2016-10-07T13:42:05Z" }, { "body": "Until the situation is improved, as a workaround you could add this line early:\r\n\r\n```php\r\nurl()->forceRootUrl(config('app.url'));\r\n```", "created_at": "2016-11-25T21:33:34Z" }, { "body": "Basically the autodetection doesn't work in CLI, and we do have to pass the base URL to the UrlGenerator. I'm posting a few suggestions in #15608.", "created_at": "2016-11-25T22:17:40Z" }, { "body": "I think the reason because some functions use the root as it is calculated by symphony and not based on the env setting.\r\n\r\nI think the reason is this line: https://github.com/laravel/framework/blob/5.3/src/Illuminate/Http/Request.php#L87", "created_at": "2017-01-18T10:06:59Z" }, { "body": "Hence the 2 possible fixes I posted in #15608, which make use of `forcedRoot` in [UrlGenerator](https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/UrlGenerator.php).\r\n\r\nWe are in CLI so it's normal the request doesn't have an URL. Modifying the request doesn't sound right, while using `forcedRoot` of the UrlGenerator seems much more appropriate.", "created_at": "2017-01-18T11:32:30Z" }, { "body": "You might be right but I ran into this issue in more cases, not in CLI but in the web (actually on local development on homestead). I just think that if we have an APP_URL environment variable, we should use it - no?", "created_at": "2017-01-18T11:43:48Z" }, { "body": "I can't say for homestead… Let's reference issue #17385 you have just created :)", "created_at": "2017-01-18T11:58:27Z" }, { "body": "Thanks.\r\n\r\nBut what do you think about the general idea of: we already have an APP_URL environment variable, why isn't the url helper use it?", "created_at": "2017-01-18T13:05:57Z" }, { "body": "I'd say because it is not configured by default, so using it would require an extra step in new installs, while the autodetection works in most cases.\r\n\r\nAlso, the autodetection is convenient when the app can be accessed through several domains ;) Don't have to dynamically configure the path.", "created_at": "2017-01-18T13:16:32Z" }, { "body": "Yes you are correct. But in that case I think that A) Why is the APP_URL there and why the laravel config uses it? and B) The auto detection should work flawlessly... at least for web requests...", "created_at": "2017-01-18T13:21:18Z" }, { "body": "@amosmos The `APP_URL` is there to simulate requests only when using the console, it is actually explained on the (config file itself)[https://github.com/laravel/laravel/blob/master/config/app.php#L48].\r\nI've never experienced the issue with a web requests, having the installation on a subpath always worked flawlessly for me. Can you better describe your issue with web requests?", "created_at": "2017-01-18T13:46:21Z" }, { "body": "I had the exact same issue running a Artisan command that should generate my `sitemap.xml`.\r\nAll the generation was `Route `based to get routes URLs (and `LaravelLocalization `for translated routes URLs).\r\nWhat I had was wrong generated URL with `http://localhost` instead of full URL path (wich was correct when getting the same method from a HTTP request).\r\n\r\nSo, in my command `__construct()` method, i added:\r\n\r\n`!App::runningInConsole() ?: \\URL::forceRootUrl(\\Config::get('app.url'));`\r\n\r\nAnd URLs generation methods used in my Artisan command was based on the `app.url` value, same value as when fired from a HTTP request on a route. Maybe it's a way to force the URL for specific localy run methods, with Artisan or else.\r\n_(tested on L5.1, Wamp with full URL as `http://localhost/project_name/public/`, error URL from Artisan command was `http://localhost/`, `app.url` as `http://localhost/project_name/public/` - result for the same method fired from a Route GET or a Artisan command)._\r\n\r\nLinks: [pull #15608](https://github.com/laravel/framework/pull/15608), [stack](http://stackoverflow.com/questions/24625528/change-route-domain-to-ip-address-in-laravel)", "created_at": "2017-03-20T19:08:39Z" }, { "body": "I've looked into Symfony to see how they've solved the problem, when route URL is build from CLI and website is located at sub-path and found this:\r\n\r\n* docs: https://symfony.com/doc/current/console/request_context.html\r\n* `RequestContext` class: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/RequestContext.php\r\n* `UrlMatcher` class: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Matcher/UrlMatcher.php\r\n\r\nIt works like this:\r\n\r\n1. in the `app/config/parameters.yml` file you specify 3 settings: `host`, `scheme`, `base_url` (basically what can't be detected in CLI)\r\n2. the `RequestContext` class is created using these settings (see https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Resources/config/routing.xml#L81-L88)\r\n3. when `UrlMatcher` is building route url it's using data from context (see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Matcher/UrlMatcher.php#L257-L260) and also replacing `SCRIPT_FILENAME` and `SCRIPT_NAME` server attributes\r\n\r\nBased on that info and @j3j5 comment (see https://github.com/laravel/framework/issues/14139#issuecomment-249566343) I'm suggesting to change `\\Illuminate\\Foundation\\Bootstrap\\SetRequestForConsole::bootstrap` method like so:\r\n\r\n1. parse url in `app.url` config setting using `parse_url` function (don't use Symfony's Request because we're using it already and it fails in CLI)\r\n2. if the `path` component is found, then replace `SCRIPT_NAME` and `SCRIPT_FILENAME` in server array passed to Request creation later\r\n\r\n**Code before:** \r\n\r\n```php\r\n$app->instance('request', Request::create(\r\n $app->make('config')->get('app.url', 'http://localhost'), 'GET', [], [], [], $_SERVER\r\n));\r\n```\r\n\r\n**Code after:**\r\n\r\n```php\r\n$uri = $app->make('config')->get('app.url', 'http://localhost');\r\n$components = parse_url($uri);\r\n$server = $_SERVER;\r\n\r\nif (isset($components['path'])) {\r\n $server['SCRIPT_FILENAME'] = $components['path'];\r\n $server['SCRIPT_NAME'] = $components['path'];\r\n}\r\n\r\n$app->instance('request', Request::create($uri, 'GET', [], [], [], $server));\r\n```\r\n\r\nI can send a PR if you'd like as a bugfix.", "created_at": "2017-08-18T17:11:55Z" } ], "number": 14139, "title": "route() helper function does not work well in artisan commands" }
{ "body": "Closes #14139", "number": 20788, "review_comments": [], "title": "[5.4] Fixes route urls building from Artisan for websites under sub-path" }
{ "commits": [ { "message": "Fixes route urls building from Artisan for websites under sub-path" } ], "files": [ { "diff": "@@ -15,8 +15,15 @@ class SetRequestForConsole\n */\n public function bootstrap(Application $app)\n {\n- $app->instance('request', Request::create(\n- $app->make('config')->get('app.url', 'http://localhost'), 'GET', [], [], [], $_SERVER\n- ));\n+ $uri = $app->make('config')->get('app.url', 'http://localhost');\n+ $components = parse_url($uri);\n+ $server = $_SERVER;\n+\n+ if (isset($components['path'])) {\n+ $server['SCRIPT_FILENAME'] = $components['path'];\n+ $server['SCRIPT_NAME'] = $components['path'];\n+ }\n+\n+ $app->instance('request', Request::create($uri, 'GET', [], [], [], $server));\n }\n }", "filename": "src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php", "status": "modified" } ] }
{ "body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n", "comments": [ { "body": "OK, Thanks. We'll get it fixed.\n", "created_at": "2013-01-11T16:29:55Z" }, { "body": "Fixed.\n", "created_at": "2013-01-11T19:46:56Z" }, { "body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n", "created_at": "2013-03-06T20:38:47Z" } ], "number": 3, "title": "Migration doesn't account for prefix when checking if migration table exists [bug]" }
{ "body": "When using `pluck` on a collection who's items are `Eloquent` models and some of the fields are casted as `date` an error is thrown: \r\n\r\n```\r\n[2017-06-30 11:20:34] local.ERROR: ErrorException: Illegal offset type in /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Support/Arr.php:365\r\nStack trace:\r\n#0 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Support/Arr.php(365): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'Illegal offset ...', '/var/www/html/t...', 365, Array)\r\n#1 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Support/Collection.php(689): Illuminate\\Support\\Arr::pluck(Array, Array, Array)\r\n#2 /var/www/html/tpt/app/Console/Commands/Test.php(48): Illuminate\\Support\\Collection->pluck('id', 'start_at')\r\n#3 [internal function]: App\\Console\\Commands\\Test->handle()\r\n#4 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)\r\n#5 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()\r\n#6 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Illuminate\\Foundation\\Application), Array, Object(Closure))\r\n#7 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Container/Container.php(531): Illuminate\\Container\\BoundMethod::call(Object(Illuminate\\Foundation\\Application), Array, Array, NULL)\r\n#8 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Console/Command.php(182): Illuminate\\Container\\Container->call(Array)\r\n#9 /var/www/html/tpt/vendor/symfony/console/Command/Command.php(264): Illuminate\\Console\\Command->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))\r\n#10 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Console/Command.php(167): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))\r\n#11 /var/www/html/tpt/vendor/symfony/console/Application.php(835): Illuminate\\Console\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n#12 /var/www/html/tpt/vendor/symfony/console/Application.php(200): Symfony\\Component\\Console\\Application->doRunCommand(Object(App\\Console\\Commands\\Test), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n#13 /var/www/html/tpt/vendor/symfony/console/Application.php(124): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n#14 /var/www/html/tpt/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n#15 /var/www/html/tpt/artisan(35): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n#16 {main} \r\n```\r\n\r\nThis commit is meant to fix this issue.", "number": 19838, "review_comments": [], "title": "[5.4] Arr::pluck - handle situation when itemKey is an object" }
{ "commits": [ { "message": "Arr::pluck - handle situation when itemKey is an object" }, { "message": "Fix StyleCI issues" } ], "files": [ { "diff": "@@ -380,6 +380,10 @@ public static function pluck($array, $value, $key = null)\n } else {\n $itemKey = data_get($item, $key);\n \n+ if (gettype($itemKey) === 'object') {\n+ $itemKey = (string) $itemKey;\n+ }\n+\n $results[$itemKey] = $itemValue;\n }\n }", "filename": "src/Illuminate/Support/Arr.php", "status": "modified" }, { "diff": "@@ -4,6 +4,7 @@\n \n use stdClass;\n use ArrayObject;\n+use Carbon\\Carbon;\n use Illuminate\\Support\\Arr;\n use PHPUnit\\Framework\\TestCase;\n use Illuminate\\Support\\Collection;\n@@ -370,6 +371,15 @@ public function testPluckWithKeys()\n ], $test2);\n }\n \n+ public function testPluckWithCarbonKeys()\n+ {\n+ $array = [\n+ ['start' => new Carbon('2017-07-25 00:00:00'), 'end' => new Carbon('2017-07-30 00:00:00')],\n+ ];\n+ $array = Arr::pluck($array, 'end', 'start');\n+ $this->assertEquals(['2017-07-25 00:00:00' => '2017-07-30 00:00:00'], $array);\n+ }\n+\n public function testPrepend()\n {\n $array = Arr::prepend(['one', 'two', 'three', 'four'], 'zero');", "filename": "tests/Support/SupportArrTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: all\r\n- PHP Version: all\r\n- Database Driver & Version: pgsql\r\n\r\n### Description:\r\n\r\nSame as #13862, but looks like it's not fixed.\r\n\r\nIn class `Database\\Schema\\Grammars\\PostgresGrammar` the `compileColumnListing` does not consider the `table_schema` attribute (like in the `compileTableExists` method). \r\n\r\n### Steps To Reproduce:\r\n\r\nSame as #13862.\r\n", "comments": [ { "body": "Can you list a detailed error stack for this?", "created_at": "2017-06-06T19:31:59Z" }, { "body": "There is no error stack. Only what #13862 describes : \r\n\r\nWhen you have multiple schemas in your database if you have a 'foo' table in a schema with a 'bar' column and in the schema specified in your connection have a 'foo' table **without** a 'bar' column then `Schema::hasColumn('foo', 'bar')` will return true.\r\nBecause of the `compileColumnListing` function, which returns : \r\n\r\n```php\r\n\"select column_name from information_schema.columns where table_name = '$table'\";\r\n```\r\nand not : \r\n\r\n```php\r\n\"select column_name from information_schema.columns where table_name = '$table'\" and table_schema = '$schema'\" ;\r\n```\r\n\r\nThe `table_schema` used in `compileTableExists` but not in `compileColumnListing`", "created_at": "2017-06-06T20:25:04Z" }, { "body": "Feel free to propose a fix and open a PR.", "created_at": "2017-06-07T18:48:02Z" }, { "body": "@KevinHivert make sure you submit to 5.5 since this would be a breaking change.", "created_at": "2017-06-07T18:49:23Z" }, { "body": "@themsaid Why would it be breaking?\r\n@KevinHivert Mate, will you make any PR for?\r\n\r\nPs.: I'd need it on 5.4 version :stuck_out_tongue:", "created_at": "2017-06-07T20:27:10Z" }, { "body": "Because after the change the some checks that used to return true ill return false :)", "created_at": "2017-06-07T20:28:33Z" }, { "body": "@themsaid So they won't tell any lie anymore heh\r\n\r\nBut I'm sure the 5.4 version still can get it :innocent: ", "created_at": "2017-06-07T20:42:29Z" }, { "body": "I will probably open a PR in the next few days (First one on Laravel :muscle:). \r\n\r\n@themsaid Thanks for the advice ;) \r\nSorry, @hakuno 5.5 it will be.", "created_at": "2017-06-07T21:05:46Z" } ], "number": 19496, "title": "Postgresql compileColumnListing method does not consider table_schema" }
{ "body": "PR for fixing issue #19496\r\n\r\n### Reminder\r\n\r\nWhen postgresql database have multiple schemas, if you have the same table name in 2 different schemas then the getColumnListing() method will not return columns of the table that is in the currently used schema bu columns that are in the 2 tables. \r\nThis is due to compileColumnListing() method that does not consider the schema name of the table. \r\n\r\nAccording to what was made in this PR #15535, I only consider the first schema if it's defined as an array in the configuration file.\r\n\r\n### Changes\r\n\r\n- Add getColumnListing() method in Illuminate\\Database\\Schema\\PostgresBuilder.\r\n- Update compileColumnListing() method in Illuminate\\Database\\Schema\\Grammars\\PostgresGrammar to filter listing by schema name too.\r\n", "number": 19553, "review_comments": [], "title": "[5.5] Fix column listing for postgres db driver." }
{ "commits": [ { "message": "Fix column listing for postgres db driver.\n\n- Add getColumnListing() method in Illuminate\\Database\\Schema\\PostgresBuilderto override default.\n- Update compileColumnListing() method in Illuminate\\Database\\Schema\\Grammars\\PostgresGrammar to filter listing by schema name." }, { "message": "Fixing StyleCI\n\n- Replace double quotes." } ], "files": [ { "diff": "@@ -41,12 +41,11 @@ public function compileTableExists()\n /**\n * Compile the query to determine the list of columns.\n *\n- * @param string $table\n * @return string\n */\n- public function compileColumnListing($table)\n+ public function compileColumnListing()\n {\n- return \"select column_name from information_schema.columns where table_name = '$table'\";\n+ return 'select column_name from information_schema.columns where table_schema = ? and table_name = ?';\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php", "status": "modified" }, { "diff": "@@ -58,4 +58,27 @@ protected function getAllTables()\n $this->grammar->compileGetAllTables($this->connection->getConfig('schema'))\n );\n }\n+\n+ /**\n+ * Get the column listing for a given table.\n+ *\n+ * @param string $table\n+ * @return array\n+ */\n+ public function getColumnListing($table)\n+ {\n+ if (is_array($schema = $this->connection->getConfig('schema'))) {\n+ $schema = head($schema);\n+ }\n+\n+ $schema = $schema ? $schema : 'public';\n+\n+ $table = $this->connection->getTablePrefix().$table;\n+\n+ $results = $this->connection->select(\n+ $this->grammar->compileColumnListing(), [$schema, $table]\n+ );\n+\n+ return $this->connection->getPostProcessor()->processColumnListing($results);\n+ }\n }", "filename": "src/Illuminate/Database/Schema/PostgresBuilder.php", "status": "modified" } ] }
{ "body": "", "comments": [], "number": 14994, "title": "[5.1] Revert aggregate changes" }
{ "body": "For ticket #14793, this code was removed to use the numericAggregate function. When it was reverted on ticket #14994 it only replaced sum with returning aggregate even though prior to the initial change this code checked result and returned 0 in case the result was null.\r\n\r\nThis is just reverting back to how the code was prior to being changed to use numericAggregate so that it will return 0 if there is no results returned.", "number": 18685, "review_comments": [ { "body": "Why not this:\r\n\r\n```php\r\nreturn $this->aggregate(__FUNCTION__, [$column]) ?: 0;\r\n```", "created_at": "2017-04-05T22:43:21Z" }, { "body": "This was just done to revert it back to its original state before the reverted code was applied. If Taylor wants, I can do it like this.", "created_at": "2017-04-05T23:29:04Z" } ], "title": "[5.1] Fix sum with no results" }
{ "commits": [ { "message": "Fix sum with no results" } ], "files": [ { "diff": "@@ -1690,7 +1690,9 @@ public function max($column)\n */\n public function sum($column)\n {\n- return $this->aggregate(__FUNCTION__, [$column]);\n+ $result = $this->aggregate(__FUNCTION__, [$column]);\n+\n+ return $result ?: 0;\n }\n \n /**", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" } ] }
{ "body": "", "comments": [], "number": 14994, "title": "[5.1] Revert aggregate changes" }
{ "body": "The `sum` function in the Query Builder should return a numeric value.\r\n\r\nThat is how it is on [5.4](https://github.com/laravel/framework/commit/17e336797c6669d64fa30132e32e017c8e4cda17).\r\nAnd that is how it used to be on [5.1](https://github.com/laravel/framework/blob/092bea01c14f537d3097b4f2df3ddc339b11c29c/src/Illuminate/Database/Query/Builder.php#L1691) before it was [changed](https://github.com/laravel/framework/commit/73ee91b55ecc9f8cd027f983bb4b239cb4f2435d) (and [changed back](https://github.com/laravel/framework/commit/509bef6759766ce7c24d61df52171c89e9288fef), incorrectly)\r\n\r\nThis is related to issues #14793, and #14994", "number": 18657, "review_comments": [], "title": "[5.1] Return numeric from query builder sum" }
{ "commits": [ { "message": "Return a numeric value from sum\n\nIn the Query Builder" }, { "message": "Add a test to confirm sum returns an integer\n\nAnd not a string" }, { "message": "Fix the return type" } ], "files": [ { "diff": "@@ -1686,11 +1686,11 @@ public function max($column)\n * Retrieve the sum of the values of a given column.\n *\n * @param string $column\n- * @return mixed\n+ * @return float|int\n */\n public function sum($column)\n {\n- return $this->aggregate(__FUNCTION__, [$column]);\n+ return $this->numericAggregate(__FUNCTION__, [$column]);\n }\n \n /**", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -883,7 +883,7 @@ public function testAggregateFunctions()\n return $results;\n });\n $results = $builder->from('users')->sum('id');\n- $this->assertEquals(1, $results);\n+ $this->assertSame(1, $results);\n }\n \n public function testSqlServerExists()", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "PHP has some difficult handling dates with a year over 9999 for example if you pass a date like \"11972-04-01\" into DateTime it will return \"2004-08-13\" which is clearly not correct. However, the date validator considers this date to be valid.\n\nMy specific problem comes from pushing that date (which has been validated) into a model which uses the method Carbon::createFromFormat('Y-m-d H:i:s', '11972-04-01') which will throw an InvalidArgumentException.\n\nThe problem with the validateDate is that it is making use of the PHP function date_parse() which is changing the years 11972 to 2002 and 22014 to 2014 which is then being pumped into checkdate() which will validate because date_parse() has \"corrected\" it.\n\nThis is loosely related to issue #329 validateDate could be better.\n", "comments": [ { "body": "Proposed fix?\n", "created_at": "2014-12-17T18:13:56Z" } ], "number": 6329, "title": "[4.2] Added Test To Demonstate A Date Validation With Big Dates" }
{ "body": "PHP has some difficult handling dates with a year over 9999 for example if you pass a date like \"20196-05-25\" into Carbon (and DateTime) it will throw an error. However, the date validator considers this date to be valid.\r\n\r\n```\r\nInvalidArgumentException was thrown! The separation symbol could not be found Unexpected data found. Data missing \r\n#0 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2969): Carbon\\Carbon::createFromFormat('Y-m-d H:i:s', '20196-05-25') \r\n#1 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2923): Illuminate\\Database\\Eloquent\\Model->asDateTime('20196-05-25') \r\n#2 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2878): Illuminate\\Database\\Eloquent\\Model->fromDateTime('20196-05-25') \r\n#3 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(450): Illuminate\\Database\\Eloquent\\Model->setAttribute('date_at', '20196-05-25')\r\n```\r\n\r\nThe problem with the `validateDate` is that it is making use of the PHP function `date_parse()` which is changing the year 20196 to 2006 which is then being pumped into `checkdate()` which will validate because `date_parse()` has \"corrected\" it.\r\n\r\nThis is loosely related to issue #329 validateDate could be better and is me finally fixing the bug #6329 I reported in 2014 (sorry for the delay).", "number": 17762, "review_comments": [], "title": "[5.4] Add Checks for Years greater than 9999" }
{ "commits": [ { "message": "Add Checks for Years greater than 9999\n\nPHP has difficulty handling dates with a year over 9999. The new regex\nchecks to ensure invalid dates no longer pass validation." } ], "files": [ { "diff": "@@ -337,6 +337,10 @@ protected function validateDate($attribute, $value)\n return false;\n }\n \n+ if (is_string($value) && preg_match('#^(\\d{5,}[^\\d]\\d{2}[^\\d]\\d{2}|\\d{2}[^\\d]\\d{2}[^\\d]\\d{5,})$#', $value)) {\n+ return false;\n+ }\n+\n $date = date_parse($value);\n \n return checkdate($date['month'], $date['day'], $date['year']);", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -2117,9 +2117,15 @@ public function testValidateDateAndFormat()\n $v = new Validator($trans, ['x' => '2000-01-01'], ['x' => 'date']);\n $this->assertTrue($v->passes());\n \n+ $v = new Validator($trans, ['x' => '20000-01-01'], ['x' => 'date']);\n+ $this->assertTrue($v->fails());\n+\n $v = new Validator($trans, ['x' => '01/01/2000'], ['x' => 'date']);\n $this->assertTrue($v->passes());\n \n+ $v = new Validator($trans, ['x' => '01/01/20000'], ['x' => 'date']);\n+ $this->assertTrue($v->fails());\n+\n $v = new Validator($trans, ['x' => '1325376000'], ['x' => 'date']);\n $this->assertTrue($v->fails());\n ", "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": "PHP has some difficult handling dates with a year over 9999 for example if you pass a date like \"20196-05-25\" into Carbon (and DateTime) it will throw an error. However, the date validator considers this date to be valid.\r\n\r\n```\r\nInvalidArgumentException was thrown! The separation symbol could not be found Unexpected data found. Data missing \r\n#0 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2969): Carbon\\Carbon::createFromFormat('Y-m-d H:i:s', '20196-05-25') \r\n#1 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2923): Illuminate\\Database\\Eloquent\\Model->asDateTime('20196-05-25') \r\n#2 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2878): Illuminate\\Database\\Eloquent\\Model->fromDateTime('20196-05-25') \r\n#3 ./vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(450): Illuminate\\Database\\Eloquent\\Model->setAttribute('date_at', '20196-05-25')\r\n```\r\n\r\nThe problem with the `validateDate` is that it is making use of the PHP function `date_parse()` which is changing the year 20196 to 2006 which is then being pumped into `checkdate()` which will validate because `date_parse()` has \"corrected\" it.\r\n\r\nThis is loosely related to issue #329 validateDate could be better and is me finally fixing the bug #6329 I reported in 2014 (sorry for the delay).", "number": 17762, "review_comments": [], "title": "[5.4] Add Checks for Years greater than 9999" }
{ "commits": [ { "message": "Add Checks for Years greater than 9999\n\nPHP has difficulty handling dates with a year over 9999. The new regex\nchecks to ensure invalid dates no longer pass validation." } ], "files": [ { "diff": "@@ -337,6 +337,10 @@ protected function validateDate($attribute, $value)\n return false;\n }\n \n+ if (is_string($value) && preg_match('#^(\\d{5,}[^\\d]\\d{2}[^\\d]\\d{2}|\\d{2}[^\\d]\\d{2}[^\\d]\\d{5,})$#', $value)) {\n+ return false;\n+ }\n+\n $date = date_parse($value);\n \n return checkdate($date['month'], $date['day'], $date['year']);", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -2117,9 +2117,15 @@ public function testValidateDateAndFormat()\n $v = new Validator($trans, ['x' => '2000-01-01'], ['x' => 'date']);\n $this->assertTrue($v->passes());\n \n+ $v = new Validator($trans, ['x' => '20000-01-01'], ['x' => 'date']);\n+ $this->assertTrue($v->fails());\n+\n $v = new Validator($trans, ['x' => '01/01/2000'], ['x' => 'date']);\n $this->assertTrue($v->passes());\n \n+ $v = new Validator($trans, ['x' => '01/01/20000'], ['x' => 'date']);\n+ $this->assertTrue($v->fails());\n+\n $v = new Validator($trans, ['x' => '1325376000'], ['x' => 'date']);\n $this->assertTrue($v->fails());\n ", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "Experienced this in 5.0 and 5.1\n\nMySQL version: 5.6\nForge provisioned server.\n\nWe use Galera Cluster for MySQL, but each site reads and writes from only one database. I don't think that would have anything to do with this error. I used `artisan session:table` to create the table so everything is standard schema-wise. Happens quite intermittently, about once per day.\n\n```\nIlluminate\\Database\\QueryExceptionGET /diaz/edit\nSQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4c1698dcfe5da87c5f77c90592855490817e575d' for key 'sessions_id_unique' (SQL: insert into `sessions` (`id`, `payload`, `last_activity`) values (4c1698dcfe5da87c5f77c90592855490817e575d, YTo1OntzOjY6Il90b2tlbiI7czo0MDoid1NLSjlmNGFxUml4RkowRVVkU0M3UjhNdldhWlZEY2hwTDhrbEU3YSI7czo3OiJtZXNzYWdlIjtzOjI2OiJMb2dpbiB0byBlZGl0IHlvdXIgcHJvZmlsZSI7czo1OiJmbGFzaCI7YToyOntzOjM6Im5ldyI7YTowOnt9czozOiJvbGQiO2E6MTp7aTowO3M6NzoibWVzc2FnZSI7fX1zOjk6Il9wcmV2aW91cyI7YToxOntzOjM6InVybCI7czozNzoiaHR0cHM6Ly9tYW5pbGEuZXNjb3J0cy5saWZlL2RpYXovZWRpdCI7fXM6OToiX3NmMl9tZXRhIjthOjM6e3M6MToidSI7aToxNDM0MTY4Njc0O3M6MToiYyI7aToxNDM0MTY4Njc0O3M6MToibCI7czoxOiIwIjt9fQ==, 1434168674))\n```\n", "comments": [ { "body": "Is it possible that insert quieries are not written immediately but with some latency?\n", "created_at": "2015-06-13T13:31:05Z" }, { "body": "yes but not much. I am not caching config.\n", "created_at": "2015-06-13T14:13:54Z" }, { "body": "You probably need to cache config. That fixes most issues I see like this.\n", "created_at": "2015-06-13T14:49:31Z" }, { "body": "I'm using config:cache but I still see this issue every day or so.\nWe still relay on `dotenv` to populate server variables, so this might be the issue.\n", "created_at": "2015-06-13T17:38:06Z" }, { "body": "Why do you think it is a config cache issue?\nI guess there may be some latency between sending response (with session ID) and app termination (when session is being saved to databse).\n\nFor example:\n1. User sends request - session id created (session->exists == false)\n2. User gets response (with generated session id).\n3. Some ajax or another request catches session id (session->exists == false as the first request is not finished - session is not written).\n4. One of requests terminates app ([session written to database with INSERT](https://github.com/laravel/framework/blob/5.1/src/Illuminate/Session/DatabaseSessionHandler.php#L79))\n5. Another request terminates with INSERT statement again (because session->exists is false in both cases)\n\nOtherwise it may be database INSERT query latency so the second request executes SELECT before insert finishes.\n", "created_at": "2015-06-13T18:13:59Z" }, { "body": "Happened to me now after switched to database driver for session .. any idea?\n\nThanks\n\nping @taylorotwell \n", "created_at": "2015-11-09T15:51:08Z" }, { "body": "I am experiencing the issue as well, using the default session build with the DB.\n", "created_at": "2015-11-10T14:55:25Z" }, { "body": ":+1:\n", "created_at": "2015-11-10T15:31:03Z" }, { "body": "@GrahamCampbell why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver -> save method. \n", "created_at": "2016-01-28T23:18:39Z" }, { "body": "This needs reopening.\n\nOn Jan 28, 2016, 5:18 PM -0600, Dean Mnotifications@github.com, wrote:\n\n> @GrahamCampbell(https://github.com/GrahamCampbell)why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver ->save method.\n> \n> —\n> Reply to this email directly orview it on GitHub(https://github.com/laravel/framework/issues/9251#issuecomment-176477099).\n", "created_at": "2016-01-29T00:20:34Z" }, { "body": "Does anyone have a solution?\n\nOn Jan 28, 2016, 5:18 PM -0600, Dean Mnotifications@github.com, wrote:\n\n> @GrahamCampbell(https://github.com/GrahamCampbell)why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver ->save method.\n> \n> —\n> Reply to this email directly orview it on GitHub(https://github.com/laravel/framework/issues/9251#issuecomment-176477099).\n", "created_at": "2016-01-29T00:20:44Z" }, { "body": "Deployed this fix to my environment today. I will let you know if that resolves the issue. \n#12059 \n", "created_at": "2016-01-29T01:13:46Z" }, { "body": "@taylorotwell @GrahamCampbell \n\nLaravel version 5.2.37\n\nI've seen a number of these session integrity issues show up on laracasts, stackoverflow, etc. I ran into the same issue today and able to replicate to some degree. It seems to a session DB related issue vs. session file. To be honest it is not really a bug but a dev issue that can be solved with middleware. That said given the norm of multi device it might be something you want to look into, but unsure if even that applies.\n\nREPLICATE: Let’s say you have a home.blade.php and second page called register.blade.php a route ‘/register’ which yields content from home. If you load /register from lets say from a MAMP stack everything will work fine as expected. Now while you still have that session, open a new browser tab. Make a copy of home.blade.php , lets say debug.blade.php which again yields to the same register.blade.php a route ‘/register’ and now if you load /register it will load register and will create the duplicate session id. Now if you go back to original tab and attempt to load register or you will get a DB session integrity duplicate issue. Which is why a number of bug complaints are login / logout related as I suspect is because they are directing to a different (duplicate) home page while still using the same session. Unsure what is causing the duplicate issue i.e if it is csrf token / session / DB session / home page issue.\n\nHope his helps.\n", "created_at": "2016-06-13T16:52:27Z" }, { "body": "Any solution for this Bug?\n", "created_at": "2016-06-13T20:30:50Z" }, { "body": ":+1:\n", "created_at": "2016-06-13T21:17:57Z" }, { "body": "> Any solution for this Bug?\n\nNot in 3 hours.\n", "created_at": "2016-06-13T21:28:04Z" }, { "body": "fwiw, I noticed I can also replicate it again by breaking a blade template load during ajax requests. For example if I force a blade template fails (e.g. wrong name) while I'm doing an ajax init() data load on vanilla route. \n\n<code>\nRoute::get('/register', [\n 'as' => 'getRegister',\n 'uses' => 'ApiController@getRegister',\n]); \n</code>\n\nbeen trying to debug it further but none of angular / testing tools are giving me any additional insight. I do believe that to @rkgrep summary above that there is a session / queue issue / conflict and might be ajax related. In my case I have a number of angular services init ajax http requests and if the template fails i.e. exception and then attempt to reload . It returns the unencoded JSON with a 200 status code.\n\n```\n javascript?v=1453465343:2050 Uncaught SyntaxError: Unexpected token < \n\nfollowed by a \n\n angular.js:13642 SyntaxError: Unexpected token < in JSON at position 11625. \n```\n\nthe position 11625 is where the html document gets appended to the JSON data. \n\nI think it is worth nothing that I get the following exception if it detects an existing session record, but I get the above silent fail if it has 2 existing session records i.e somehow the DB has written 2 identical session records and if it attempts to write a 3rd it fails silently and sends back JSON data but unencoded.\n\n<code>\nNext exception 'Illuminate\\Database\\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'a26e09eaf0a210a34e58ebab42acd9435681e0a5' for key 'sessions_id_unique' (SQL: insert into `sessions` (`payload`, `last_activity`, `user_id`, `ip_address`, `user_agent`, `id`) values (YTo0OntzOjY6Il90b2tlbiI7czo0MDoiOVE3M3ZLam12YlpFVEhLNDBSOVAwMDdIZWpKeGY0YUFNQVZDRTFJUCI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MzI6Imh0dHA6Ly93d3cuY21vOjg4ODgvYXBpL3BlcnNvbmFzIjt9czo5OiJfc2YyX21ldGEiO2E6Mzp7czoxOiJ1IjtpOjE0NjU5MjE0ODU7czoxOiJjIjtpOjE0NjU5MjE0ODU7czoxOiJsIjtzOjE6IjAiO31zOjU6ImZsYXNoIjthOjI6e3M6Mzoib2xkIjthOjA6e31zOjM6Im5ldyI7YTowOnt9fX0=, 1465921486, , ::1, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36, a26e09eaf0a210a34e58ebab42acd9435681e0a5))' in /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php:713\nStack trace:\n#0 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(669): Illuminate\\Database\\Connection->runQueryCallback('insert into `se...', Array, Object(Closure))\n#1 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(442): Illuminate\\Database\\Connection->run('insert into`se...', Array, Object(Closure))\n#2 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(398): Illuminate\\Database\\Connection->statement('insert into `se...', Array)\n#3 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2039): Illuminate\\Database\\Connection->insert('insert into`se...', Array)\n#4 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php(117): Illuminate\\Database\\Query\\Builder->insert(Array)\n#5 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/Store.php(262): Illuminate\\Session\\DatabaseSessionHandler->write('a26e09eaf0a210a...', 'a:4:{s:6:\"_toke...')\n#6 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(88): Illuminate\\Session\\Store->save()\n#7 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(155): Illuminate\\Session\\Middleware\\StartSession->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))\n#8 /Users/nolros/Documents/cmo/public/index.php(58): Illuminate\\Foundation\\Http\\Kernel->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))\n#9 {main} \n</code>\n\nhere is an example of the ajax request\n\n<code>\n Request URL:http://www.cmo:8888/api/personas\nRequest Method:GET\nStatus Code:200 OK\nRemote Address:[::1]:8888\nResponse Headers\nview source\nCache-Control:no-cache\nConnection:Keep-Alive\nContent-Type:application/json\nDate:Tue, 14 Jun 2016 16:24:45 GMT\nKeep-Alive:timeout=5, max=96\nphpdebugbar-id:b73cf0e58e0f47fd49857463540cbaf3\nServer:Apache\nSet-Cookie:laravel_session=a26e09eaf0a210a34e58ebab42acd9435681e0a5; path=/; httponly\nSet - Cookie:XSRF - TOKEN = eyJpdiI6Ijd2Y0pmN3JCSWRTNGE5dzFnT1FSSFE9PSIsInZhbHVlIjoiNWFubHNNYTVLeGRRc1B4RW9zMGNBQ3NVTFpDeTUrVkdzZWpWWjBRXC9scDlRejQ0TnpwNHQzV3BrUkJlamNUSm5jZjFudmFCM1VLb0dlUEhERHVPN0xRPT0iLCJtYWMiOiJjNTYxZDc3NmM0ZTI5M2MzNGI2ZmM3MDIxZGFjMDZiMzc1MGI1OTM4YWExOGI5NzczNTUzMzJiMmE3ZDkxZmRjIn0 % 3D; expires = Tue, 14 - Jun - 2016 18:24:46 GMT; Max - Age = 7200; path =/\nTransfer-Encoding:chunked\nX-Powered-By:PHP/5.6.10\nRequest Headers\nview source\nAccept:application/json, text/plain, _/_\nAccept-Encoding:gzip, deflate, sdch\nAccept-Language:en-US,en;q=0.8\nCache-Control:no-cache\nConnection:keep-alive\nCookie:cmosolution=eyJpdiI6IlBIYUhCQzJYUUxkMFwvZ0x2RmJraFhnPT0iLCJ2YWx1ZSI6IjVqaXA2ak9WN3laaHdVNkVtRVRPbVJOVThoRTVGV2E0K1RiTHdIcFQ4eGNCTU9nYjRnUnhVWEduODJvS1wvVW15QUlcL1ZyWlp0Z3o0MVhGem1rUzZPZjlLNEY5VTF3eW4zckE0ZXNHTHRCZXlOVVRDWkFoS3NlNHlBRVR3Y3IwdFkiLCJtYWMiOiI1NDcxNmRiZTBiN2NiMmQ5ODcwYTMyZDcxY2ZmYzFkMGU1NmRiNTc0MDAxNTBiMTVhZjNlZjJkMTljNjIyYmFlIn0%3D; remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6Im94R1B6NFwvUnpMQUp2M0VuTDN3cFlnPT0iLCJ2YWx1ZSI6IjNJZUVCSnFhR1IzZ0tVaVNTd3hUb1NcL2FIcHFcL1pJaE9FMGRIc2hQV1NDZzBycmVxN2xUb0s3aUdjWnpRaDFCWlwveHhCXC8xZG1wOE5WdnJpc0RYK094UGVMWDJ1cjNiSFE0R2tMM2VhRkJuVT0iLCJtYWMiOiJhMjMzYTFlNmM2MWIxNDJlNDQwZDJiZTNhNjhhNWFhNzRlZThiYjNhNjc1NDhiY2MxNjI0MTc2MGY3MDgwYWQxIn0%3D; XSRF-TOKEN=eyJpdiI6IlZ5bHZNNlVXM0ZqM0tWd0dheUtJUEE9PSIsInZhbHVlIjoieGdyYzRtOUFHaHptMGVYbUw1ZzNIVU5hTjQ5cDM1QWljNHBWazVWZVVZdXdBRnl1YWFpc1UzVE53Q0tlbGZLQUxVazdLcWZ0enZxWG5vUURGZHVcL2RnPT0iLCJtYWMiOiI3NDIxNDJmN2Q3NWYxYWE2MTY0NDc4MGM4ZWNkMzFiNDY3OWE3ZWExMmNiMDEzZDNiYjU1Njg4NGQ5NzJhZmMxIn0%3D; laravel_session=a26e09eaf0a210a34e58ebab42acd9435681e0a5\nHost:www.cmo:8888\nPragma:no-cache\nReferer:http://www.cmo:8888/register\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36\nX-XSRF-TOKEN:eyJpdiI6IlZ5bHZNNlVXM0ZqM0tWd0dheUtJUEE9PSIsInZhbHVlIjoieGdyYzRtOUFHaHptMGVYbUw1ZzNIVU5hTjQ5cDM1QWljNHBWazVWZVVZdXdBRnl1YWFpc1UzVE53Q0tlbGZLQUxVazdLcWZ0enZxWG5vUURGZHVcL2RnPT0iLCJtYWMiOiI3NDIxNDJmN2Q3NWYxYWE2MTY0NDc4MGM4ZWNkMzFiNDY3OWE3ZWExMmNiMDEzZDNiYjU1Njg4NGQ5NzJhZmMxIn0=\n</code>\n\nThe issue is resolved if I delete the DB session. This probably doesn't help much but I thought I would share anyway.\n", "created_at": "2016-06-14T16:58:11Z" }, { "body": "Any solution?\n", "created_at": "2016-06-14T19:19:29Z" }, { "body": "Is it working on the very latest version?\n", "created_at": "2016-06-14T19:45:17Z" }, { "body": "5.1.*\n", "created_at": "2016-06-14T19:52:25Z" }, { "body": "Please provide the exact version.\n", "created_at": "2016-06-14T20:08:57Z" }, { "body": "Laravel Framework version 5.1.39 (LTS)\n", "created_at": "2016-06-14T20:15:32Z" }, { "body": "@GrahamCampbell fails in version 5.2.37 but no problem in version 5.2.38. I've run all tests and tried all scenarios and pleased to report no problem. Thank you!\n", "created_at": "2016-06-14T21:25:11Z" }, { "body": "Great. ;)\n", "created_at": "2016-06-14T21:44:59Z" }, { "body": "But, if it's still broken on 5.1?\n", "created_at": "2016-06-14T21:45:52Z" }, { "body": "Version 5.1.39 does not work\n", "created_at": "2016-06-14T21:57:59Z" }, { "body": "I made the same change to 5.1 as to 5.2. If there is still a problem please someone make a PR. I am on vacation.\n", "created_at": "2016-06-15T00:18:33Z" }, { "body": "Version 5.1.39 does not work\n", "created_at": "2016-06-15T14:28:30Z" }, { "body": "Someone make a PR to fix please.\n", "created_at": "2016-06-15T23:39:37Z" }, { "body": "I think this was a recent change/update. Have been working on something for a client for months now, and only after a recent composer update did this issue starting showing... Any chance this is a dependency problem?\n\nEdit: For reference, this is happening at least twice a day on a local testbed running MySQL 5.7 and PHP 5.6.19. Switching the server to use 7.0.1 resolves the issue for me.\n\nEdit 2: I could be wrong - was silly and did an update at the same time, so can't confirm what made it work without clearing anything.\n", "created_at": "2016-06-17T15:02:55Z" } ], "number": 9251, "title": "Integrity constraint violation when using database session driver" }
{ "body": "[5.1] Backporting fix of issue #9251 to 5.1 branch. Original commit by Taylor Otwell: d9e0a6a", "number": 17686, "review_comments": [], "title": "[5.1] Backporting fix of issue #9251" }
{ "commits": [ { "message": "Backporting fix of issue #9251 to 5.1 branch. Original commit by Taylor Otwell: d9e0a6a" } ], "files": [ { "diff": "@@ -4,6 +4,7 @@\n \n use Carbon\\Carbon;\n use SessionHandlerInterface;\n+use Illuminate\\Database\\QueryException;\n use Illuminate\\Database\\ConnectionInterface;\n \n class DatabaseSessionHandler implements SessionHandlerInterface, ExistenceAwareInterface\n@@ -95,16 +96,44 @@ public function read($sessionId)\n public function write($sessionId, $data)\n {\n if ($this->exists) {\n- $this->getQuery()->where('id', $sessionId)->update([\n- 'payload' => base64_encode($data), 'last_activity' => time(),\n- ]);\n+ $this->performUpdate($sessionId, $data);\n } else {\n- $this->getQuery()->insert([\n+ $this->performInsert($sessionId, $data);\n+ }\n+\n+ $this->exists = true;\n+ }\n+\n+ /**\n+ * Perform an insert operation on the session ID.\n+ *\n+ * @param string $sessionId\n+ * @param string $data\n+ * @return void\n+ */\n+ protected function performInsert($sessionId, $data)\n+ {\n+ try {\n+ return $this->getQuery()->insert([\n 'id' => $sessionId, 'payload' => base64_encode($data), 'last_activity' => time(),\n ]);\n+ } catch (QueryException $e) {\n+ $this->performUpdate($sessionId, $data);\n }\n+ }\n \n- $this->exists = true;\n+ /**\n+ * Perform an update operation on the session ID.\n+ *\n+ * @param string $sessionId\n+ * @param string $data\n+ * @return int\n+ */\n+ protected function performUpdate($sessionId, $data)\n+ {\n+ return $this->getQuery()->where('id', $sessionId)->update([\n+ 'payload' => base64_encode($data), 'last_activity' => time(),\n+ ]);\n }\n \n /**", "filename": "src/Illuminate/Session/DatabaseSessionHandler.php", "status": "modified" } ] }
{ "body": "Experienced this in 5.0 and 5.1\n\nMySQL version: 5.6\nForge provisioned server.\n\nWe use Galera Cluster for MySQL, but each site reads and writes from only one database. I don't think that would have anything to do with this error. I used `artisan session:table` to create the table so everything is standard schema-wise. Happens quite intermittently, about once per day.\n\n```\nIlluminate\\Database\\QueryExceptionGET /diaz/edit\nSQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4c1698dcfe5da87c5f77c90592855490817e575d' for key 'sessions_id_unique' (SQL: insert into `sessions` (`id`, `payload`, `last_activity`) values (4c1698dcfe5da87c5f77c90592855490817e575d, YTo1OntzOjY6Il90b2tlbiI7czo0MDoid1NLSjlmNGFxUml4RkowRVVkU0M3UjhNdldhWlZEY2hwTDhrbEU3YSI7czo3OiJtZXNzYWdlIjtzOjI2OiJMb2dpbiB0byBlZGl0IHlvdXIgcHJvZmlsZSI7czo1OiJmbGFzaCI7YToyOntzOjM6Im5ldyI7YTowOnt9czozOiJvbGQiO2E6MTp7aTowO3M6NzoibWVzc2FnZSI7fX1zOjk6Il9wcmV2aW91cyI7YToxOntzOjM6InVybCI7czozNzoiaHR0cHM6Ly9tYW5pbGEuZXNjb3J0cy5saWZlL2RpYXovZWRpdCI7fXM6OToiX3NmMl9tZXRhIjthOjM6e3M6MToidSI7aToxNDM0MTY4Njc0O3M6MToiYyI7aToxNDM0MTY4Njc0O3M6MToibCI7czoxOiIwIjt9fQ==, 1434168674))\n```\n", "comments": [ { "body": "Is it possible that insert quieries are not written immediately but with some latency?\n", "created_at": "2015-06-13T13:31:05Z" }, { "body": "yes but not much. I am not caching config.\n", "created_at": "2015-06-13T14:13:54Z" }, { "body": "You probably need to cache config. That fixes most issues I see like this.\n", "created_at": "2015-06-13T14:49:31Z" }, { "body": "I'm using config:cache but I still see this issue every day or so.\nWe still relay on `dotenv` to populate server variables, so this might be the issue.\n", "created_at": "2015-06-13T17:38:06Z" }, { "body": "Why do you think it is a config cache issue?\nI guess there may be some latency between sending response (with session ID) and app termination (when session is being saved to databse).\n\nFor example:\n1. User sends request - session id created (session->exists == false)\n2. User gets response (with generated session id).\n3. Some ajax or another request catches session id (session->exists == false as the first request is not finished - session is not written).\n4. One of requests terminates app ([session written to database with INSERT](https://github.com/laravel/framework/blob/5.1/src/Illuminate/Session/DatabaseSessionHandler.php#L79))\n5. Another request terminates with INSERT statement again (because session->exists is false in both cases)\n\nOtherwise it may be database INSERT query latency so the second request executes SELECT before insert finishes.\n", "created_at": "2015-06-13T18:13:59Z" }, { "body": "Happened to me now after switched to database driver for session .. any idea?\n\nThanks\n\nping @taylorotwell \n", "created_at": "2015-11-09T15:51:08Z" }, { "body": "I am experiencing the issue as well, using the default session build with the DB.\n", "created_at": "2015-11-10T14:55:25Z" }, { "body": ":+1:\n", "created_at": "2015-11-10T15:31:03Z" }, { "body": "@GrahamCampbell why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver -> save method. \n", "created_at": "2016-01-28T23:18:39Z" }, { "body": "This needs reopening.\n\nOn Jan 28, 2016, 5:18 PM -0600, Dean Mnotifications@github.com, wrote:\n\n> @GrahamCampbell(https://github.com/GrahamCampbell)why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver ->save method.\n> \n> —\n> Reply to this email directly orview it on GitHub(https://github.com/laravel/framework/issues/9251#issuecomment-176477099).\n", "created_at": "2016-01-29T00:20:34Z" }, { "body": "Does anyone have a solution?\n\nOn Jan 28, 2016, 5:18 PM -0600, Dean Mnotifications@github.com, wrote:\n\n> @GrahamCampbell(https://github.com/GrahamCampbell)why close this ticket, seems like lots of people are having issues with this problem and continue to have this problem. I think the issue lies in the database driver ->save method.\n> \n> —\n> Reply to this email directly orview it on GitHub(https://github.com/laravel/framework/issues/9251#issuecomment-176477099).\n", "created_at": "2016-01-29T00:20:44Z" }, { "body": "Deployed this fix to my environment today. I will let you know if that resolves the issue. \n#12059 \n", "created_at": "2016-01-29T01:13:46Z" }, { "body": "@taylorotwell @GrahamCampbell \n\nLaravel version 5.2.37\n\nI've seen a number of these session integrity issues show up on laracasts, stackoverflow, etc. I ran into the same issue today and able to replicate to some degree. It seems to a session DB related issue vs. session file. To be honest it is not really a bug but a dev issue that can be solved with middleware. That said given the norm of multi device it might be something you want to look into, but unsure if even that applies.\n\nREPLICATE: Let’s say you have a home.blade.php and second page called register.blade.php a route ‘/register’ which yields content from home. If you load /register from lets say from a MAMP stack everything will work fine as expected. Now while you still have that session, open a new browser tab. Make a copy of home.blade.php , lets say debug.blade.php which again yields to the same register.blade.php a route ‘/register’ and now if you load /register it will load register and will create the duplicate session id. Now if you go back to original tab and attempt to load register or you will get a DB session integrity duplicate issue. Which is why a number of bug complaints are login / logout related as I suspect is because they are directing to a different (duplicate) home page while still using the same session. Unsure what is causing the duplicate issue i.e if it is csrf token / session / DB session / home page issue.\n\nHope his helps.\n", "created_at": "2016-06-13T16:52:27Z" }, { "body": "Any solution for this Bug?\n", "created_at": "2016-06-13T20:30:50Z" }, { "body": ":+1:\n", "created_at": "2016-06-13T21:17:57Z" }, { "body": "> Any solution for this Bug?\n\nNot in 3 hours.\n", "created_at": "2016-06-13T21:28:04Z" }, { "body": "fwiw, I noticed I can also replicate it again by breaking a blade template load during ajax requests. For example if I force a blade template fails (e.g. wrong name) while I'm doing an ajax init() data load on vanilla route. \n\n<code>\nRoute::get('/register', [\n 'as' => 'getRegister',\n 'uses' => 'ApiController@getRegister',\n]); \n</code>\n\nbeen trying to debug it further but none of angular / testing tools are giving me any additional insight. I do believe that to @rkgrep summary above that there is a session / queue issue / conflict and might be ajax related. In my case I have a number of angular services init ajax http requests and if the template fails i.e. exception and then attempt to reload . It returns the unencoded JSON with a 200 status code.\n\n```\n javascript?v=1453465343:2050 Uncaught SyntaxError: Unexpected token < \n\nfollowed by a \n\n angular.js:13642 SyntaxError: Unexpected token < in JSON at position 11625. \n```\n\nthe position 11625 is where the html document gets appended to the JSON data. \n\nI think it is worth nothing that I get the following exception if it detects an existing session record, but I get the above silent fail if it has 2 existing session records i.e somehow the DB has written 2 identical session records and if it attempts to write a 3rd it fails silently and sends back JSON data but unencoded.\n\n<code>\nNext exception 'Illuminate\\Database\\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'a26e09eaf0a210a34e58ebab42acd9435681e0a5' for key 'sessions_id_unique' (SQL: insert into `sessions` (`payload`, `last_activity`, `user_id`, `ip_address`, `user_agent`, `id`) values (YTo0OntzOjY6Il90b2tlbiI7czo0MDoiOVE3M3ZLam12YlpFVEhLNDBSOVAwMDdIZWpKeGY0YUFNQVZDRTFJUCI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MzI6Imh0dHA6Ly93d3cuY21vOjg4ODgvYXBpL3BlcnNvbmFzIjt9czo5OiJfc2YyX21ldGEiO2E6Mzp7czoxOiJ1IjtpOjE0NjU5MjE0ODU7czoxOiJjIjtpOjE0NjU5MjE0ODU7czoxOiJsIjtzOjE6IjAiO31zOjU6ImZsYXNoIjthOjI6e3M6Mzoib2xkIjthOjA6e31zOjM6Im5ldyI7YTowOnt9fX0=, 1465921486, , ::1, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36, a26e09eaf0a210a34e58ebab42acd9435681e0a5))' in /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php:713\nStack trace:\n#0 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(669): Illuminate\\Database\\Connection->runQueryCallback('insert into `se...', Array, Object(Closure))\n#1 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(442): Illuminate\\Database\\Connection->run('insert into`se...', Array, Object(Closure))\n#2 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Connection.php(398): Illuminate\\Database\\Connection->statement('insert into `se...', Array)\n#3 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2039): Illuminate\\Database\\Connection->insert('insert into`se...', Array)\n#4 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php(117): Illuminate\\Database\\Query\\Builder->insert(Array)\n#5 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/Store.php(262): Illuminate\\Session\\DatabaseSessionHandler->write('a26e09eaf0a210a...', 'a:4:{s:6:\"_toke...')\n#6 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(88): Illuminate\\Session\\Store->save()\n#7 /Users/nolros/Documents/cmo/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(155): Illuminate\\Session\\Middleware\\StartSession->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))\n#8 /Users/nolros/Documents/cmo/public/index.php(58): Illuminate\\Foundation\\Http\\Kernel->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))\n#9 {main} \n</code>\n\nhere is an example of the ajax request\n\n<code>\n Request URL:http://www.cmo:8888/api/personas\nRequest Method:GET\nStatus Code:200 OK\nRemote Address:[::1]:8888\nResponse Headers\nview source\nCache-Control:no-cache\nConnection:Keep-Alive\nContent-Type:application/json\nDate:Tue, 14 Jun 2016 16:24:45 GMT\nKeep-Alive:timeout=5, max=96\nphpdebugbar-id:b73cf0e58e0f47fd49857463540cbaf3\nServer:Apache\nSet-Cookie:laravel_session=a26e09eaf0a210a34e58ebab42acd9435681e0a5; path=/; httponly\nSet - Cookie:XSRF - TOKEN = eyJpdiI6Ijd2Y0pmN3JCSWRTNGE5dzFnT1FSSFE9PSIsInZhbHVlIjoiNWFubHNNYTVLeGRRc1B4RW9zMGNBQ3NVTFpDeTUrVkdzZWpWWjBRXC9scDlRejQ0TnpwNHQzV3BrUkJlamNUSm5jZjFudmFCM1VLb0dlUEhERHVPN0xRPT0iLCJtYWMiOiJjNTYxZDc3NmM0ZTI5M2MzNGI2ZmM3MDIxZGFjMDZiMzc1MGI1OTM4YWExOGI5NzczNTUzMzJiMmE3ZDkxZmRjIn0 % 3D; expires = Tue, 14 - Jun - 2016 18:24:46 GMT; Max - Age = 7200; path =/\nTransfer-Encoding:chunked\nX-Powered-By:PHP/5.6.10\nRequest Headers\nview source\nAccept:application/json, text/plain, _/_\nAccept-Encoding:gzip, deflate, sdch\nAccept-Language:en-US,en;q=0.8\nCache-Control:no-cache\nConnection:keep-alive\nCookie:cmosolution=eyJpdiI6IlBIYUhCQzJYUUxkMFwvZ0x2RmJraFhnPT0iLCJ2YWx1ZSI6IjVqaXA2ak9WN3laaHdVNkVtRVRPbVJOVThoRTVGV2E0K1RiTHdIcFQ4eGNCTU9nYjRnUnhVWEduODJvS1wvVW15QUlcL1ZyWlp0Z3o0MVhGem1rUzZPZjlLNEY5VTF3eW4zckE0ZXNHTHRCZXlOVVRDWkFoS3NlNHlBRVR3Y3IwdFkiLCJtYWMiOiI1NDcxNmRiZTBiN2NiMmQ5ODcwYTMyZDcxY2ZmYzFkMGU1NmRiNTc0MDAxNTBiMTVhZjNlZjJkMTljNjIyYmFlIn0%3D; remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6Im94R1B6NFwvUnpMQUp2M0VuTDN3cFlnPT0iLCJ2YWx1ZSI6IjNJZUVCSnFhR1IzZ0tVaVNTd3hUb1NcL2FIcHFcL1pJaE9FMGRIc2hQV1NDZzBycmVxN2xUb0s3aUdjWnpRaDFCWlwveHhCXC8xZG1wOE5WdnJpc0RYK094UGVMWDJ1cjNiSFE0R2tMM2VhRkJuVT0iLCJtYWMiOiJhMjMzYTFlNmM2MWIxNDJlNDQwZDJiZTNhNjhhNWFhNzRlZThiYjNhNjc1NDhiY2MxNjI0MTc2MGY3MDgwYWQxIn0%3D; XSRF-TOKEN=eyJpdiI6IlZ5bHZNNlVXM0ZqM0tWd0dheUtJUEE9PSIsInZhbHVlIjoieGdyYzRtOUFHaHptMGVYbUw1ZzNIVU5hTjQ5cDM1QWljNHBWazVWZVVZdXdBRnl1YWFpc1UzVE53Q0tlbGZLQUxVazdLcWZ0enZxWG5vUURGZHVcL2RnPT0iLCJtYWMiOiI3NDIxNDJmN2Q3NWYxYWE2MTY0NDc4MGM4ZWNkMzFiNDY3OWE3ZWExMmNiMDEzZDNiYjU1Njg4NGQ5NzJhZmMxIn0%3D; laravel_session=a26e09eaf0a210a34e58ebab42acd9435681e0a5\nHost:www.cmo:8888\nPragma:no-cache\nReferer:http://www.cmo:8888/register\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36\nX-XSRF-TOKEN:eyJpdiI6IlZ5bHZNNlVXM0ZqM0tWd0dheUtJUEE9PSIsInZhbHVlIjoieGdyYzRtOUFHaHptMGVYbUw1ZzNIVU5hTjQ5cDM1QWljNHBWazVWZVVZdXdBRnl1YWFpc1UzVE53Q0tlbGZLQUxVazdLcWZ0enZxWG5vUURGZHVcL2RnPT0iLCJtYWMiOiI3NDIxNDJmN2Q3NWYxYWE2MTY0NDc4MGM4ZWNkMzFiNDY3OWE3ZWExMmNiMDEzZDNiYjU1Njg4NGQ5NzJhZmMxIn0=\n</code>\n\nThe issue is resolved if I delete the DB session. This probably doesn't help much but I thought I would share anyway.\n", "created_at": "2016-06-14T16:58:11Z" }, { "body": "Any solution?\n", "created_at": "2016-06-14T19:19:29Z" }, { "body": "Is it working on the very latest version?\n", "created_at": "2016-06-14T19:45:17Z" }, { "body": "5.1.*\n", "created_at": "2016-06-14T19:52:25Z" }, { "body": "Please provide the exact version.\n", "created_at": "2016-06-14T20:08:57Z" }, { "body": "Laravel Framework version 5.1.39 (LTS)\n", "created_at": "2016-06-14T20:15:32Z" }, { "body": "@GrahamCampbell fails in version 5.2.37 but no problem in version 5.2.38. I've run all tests and tried all scenarios and pleased to report no problem. Thank you!\n", "created_at": "2016-06-14T21:25:11Z" }, { "body": "Great. ;)\n", "created_at": "2016-06-14T21:44:59Z" }, { "body": "But, if it's still broken on 5.1?\n", "created_at": "2016-06-14T21:45:52Z" }, { "body": "Version 5.1.39 does not work\n", "created_at": "2016-06-14T21:57:59Z" }, { "body": "I made the same change to 5.1 as to 5.2. If there is still a problem please someone make a PR. I am on vacation.\n", "created_at": "2016-06-15T00:18:33Z" }, { "body": "Version 5.1.39 does not work\n", "created_at": "2016-06-15T14:28:30Z" }, { "body": "Someone make a PR to fix please.\n", "created_at": "2016-06-15T23:39:37Z" }, { "body": "I think this was a recent change/update. Have been working on something for a client for months now, and only after a recent composer update did this issue starting showing... Any chance this is a dependency problem?\n\nEdit: For reference, this is happening at least twice a day on a local testbed running MySQL 5.7 and PHP 5.6.19. Switching the server to use 7.0.1 resolves the issue for me.\n\nEdit 2: I could be wrong - was silly and did an update at the same time, so can't confirm what made it work without clearing anything.\n", "created_at": "2016-06-17T15:02:55Z" } ], "number": 9251, "title": "Integrity constraint violation when using database session driver" }
{ "body": "Backporting fix of issue #9251 to 5.3 branch. Original commit by Taylor Otwell: https://github.com/laravel/framework/commit/d9e0a6a03891d16ed6a71151354445fbdc9e6f50\r\n", "number": 17301, "review_comments": [], "title": "[5.3] Fix integrity constraints for database session driver" }
{ "commits": [ { "message": "Fix integrity constraints for database session driver.\n\nBackporting fix of issue #9251 to 5.3 branch. Originally by Taylor\nOtwell <taylor@laravel.com>.\n\nSigned-off-by: Gleb Golubitsky <sectoid@gnolltech.com>" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n use Carbon\\Carbon;\n use SessionHandlerInterface;\n use Illuminate\\Contracts\\Auth\\Guard;\n+use Illuminate\\Database\\QueryException;\n use Illuminate\\Database\\ConnectionInterface;\n use Illuminate\\Contracts\\Container\\Container;\n \n@@ -112,18 +113,46 @@ public function write($sessionId, $data)\n }\n \n if ($this->exists) {\n- $this->getQuery()->where('id', $sessionId)->update($payload);\n+ $this->performUpdate($sessionId, $payload);\n } else {\n- $payload['id'] = $sessionId;\n-\n- $this->getQuery()->insert($payload);\n+ $this->performInsert($sessionId, $payload);\n }\n \n $this->exists = true;\n \n return true;\n }\n \n+ /**\n+ * Perform an insert operation on the session ID.\n+ *\n+ * @param string $sessionId\n+ * @param string $payload\n+ * @return void\n+ */\n+ protected function performInsert($sessionId, $payload)\n+ {\n+ try {\n+ $payload['id'] = $sessionId;\n+\n+ return $this->getQuery()->insert($payload);\n+ } catch (QueryException $e) {\n+ $this->performUpdate($sessionId, $payload);\n+ }\n+ }\n+\n+ /**\n+ * Perform an update operation on the session ID.\n+ *\n+ * @param string $sessionId\n+ * @param string $payload\n+ * @return int\n+ */\n+ protected function performUpdate($sessionId, $payload)\n+ {\n+ return $this->getQuery()->where('id', $sessionId)->update($payload);\n+ }\n+\n /**\n * Get the default payload for the session.\n *", "filename": "src/Illuminate/Session/DatabaseSessionHandler.php", "status": "modified" } ] }
{ "body": "Original bug found here: https://github.com/illuminate/database/issues/111 - Moved to his repo as per Taylor. Here's the original text:\n\nI spoke with Machuga in IRC - It was suggested I create an issue.\n#### Issue:\n\nError **after** first migration: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Steps to reproduce:\n1. Fresh install of L4\n2. Add a prefix to database in database connection config (MySql)\n3. Create a migration `$ php artisan migrate:make create_users_table --table=users --create`\n4. Fill in some fields, run the migration `$ php artisan migrate`\n5. Attempt a migrate:refresh `$ php artisan migrate:refresh`\n6. ERROR: `SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'up_migrations' already exists`\n#### Relevant files:\n\nI tracked this down to [this file](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L134): `Illuminate\\Database\\MigrationsDatabaseMigrationRepository::repositoryExists()` and specifically within that, the call to `return $schema->hasTable($this->table);` [here](https://github.com/illuminate/database/blob/master/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php#L138)\n\nThe $this->table variable passed to hasTable() does not include the table prefix. `Illuminate\\Database\\Schema\\MySqlBuilder::hasTable($table)` does not check for prefix either.\n\nUnfortunately I'm not yet familiar with the code/convention to know where you'd prefer to look up the prefix. (Not sure what class should have that \"knowledge\")\n", "comments": [ { "body": "OK, Thanks. We'll get it fixed.\n", "created_at": "2013-01-11T16:29:55Z" }, { "body": "Fixed.\n", "created_at": "2013-01-11T19:46:56Z" }, { "body": "I´m having this very same issue and I just downloaded the framework from the site. \nI wonder if the fix was commited to the site version.\n", "created_at": "2013-03-06T20:38:47Z" } ], "number": 3, "title": "Migration doesn't account for prefix when checking if migration table exists [bug]" }
{ "body": "Fix the error when run `php artisan optimize`.\r\n\r\n```\r\n[Symfony\\Component\\Debug\\Exception\\FatalThrowableError] \r\nCall to undefined method Illuminate\\Foundation\\Application::resolveProviderClass()\r\n```\r\n\r\nTrace:\r\n```\r\n[2016-12-20 00:38:59] local.ERROR: Symfony\\Component\\Debug\\Exception\\FatalThrowableError: Call to undefined method Illuminate\\Foundation\\Application::resolveProviderClass() in /path/to/vendor/laravel/framework/src/Illuminate/Support/AggregateServiceProvider.php:45\r\nStack trace:\r\n#0 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php(149): Illuminate\\Support\\AggregateServiceProvider->provides()\r\n#1 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php(60): Illuminate\\Foundation\\ProviderRepository->compileManifest(Array)\r\n#2 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(541): Illuminate\\Foundation\\ProviderRepository->load(Array)\r\n#3 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php(17): Illuminate\\Foundation\\Application->registerConfiguredProviders()\r\n#4 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(206): Illuminate\\Foundation\\Bootstrap\\RegisterProviders->bootstrap(Object(Illuminate\\Foundation\\Application))\r\n#5 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(267): Illuminate\\Foundation\\Application->bootstrapWith(Array)\r\n#6 /path/to/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(113): Illuminate\\Foundation\\Console\\Kernel->bootstrap()\r\n#7 /path/to/artisan(35): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\r\n#8 {main} \r\n```", "number": 16875, "review_comments": [], "title": "[5.4] Fix aggregate service provider resolver method" }
{ "commits": [ { "message": "Fix aggregate service provider resolver method" } ], "files": [ { "diff": "@@ -42,7 +42,7 @@ public function provides()\n $provides = [];\n \n foreach ($this->providers as $provider) {\n- $instance = $this->app->resolveProviderClass($provider);\n+ $instance = $this->app->resolveProvider($provider);\n \n $provides = array_merge($provides, $instance->provides());\n }", "filename": "src/Illuminate/Support/AggregateServiceProvider.php", "status": "modified" } ] }
{ "body": "This PR provides demonstration and fix for issue https://github.com/laravel/framework/issues/5937.\n", "comments": [], "number": 5944, "title": "[4.2] Fix for #5937 Connection::run breaks transaction logic when connection lost inside transaction." }
{ "body": "I am not sure if I apply this to 5.1 as well. The tests and codes changed. Maybe need another PR.\n\nAlso here is a history you may check #5944 #5937\n\nThanks.\n", "number": 15931, "review_comments": [], "title": "[5.3] Allow reconnect in transaction by setting transactions to 0" }
{ "commits": [ { "message": "Allow reconnect in transaction by setting transactions to 0" } ], "files": [ { "diff": "@@ -7,7 +7,6 @@\n use Exception;\n use Throwable;\n use LogicException;\n-use RuntimeException;\n use DateTimeInterface;\n use Illuminate\\Support\\Arr;\n use Illuminate\\Database\\Query\\Expression;\n@@ -985,14 +984,10 @@ public function getReadPdo()\n *\n * @param \\PDO|null $pdo\n * @return $this\n- *\n- * @throws \\RuntimeException\n */\n public function setPdo($pdo)\n {\n- if ($this->transactions >= 1) {\n- throw new RuntimeException(\"Can't swap PDO instance while within transaction.\");\n- }\n+ $this->transactions = 0;\n \n $this->pdo = $pdo;\n ", "filename": "src/Illuminate/Database/Connection.php", "status": "modified" }, { "diff": "@@ -156,14 +156,14 @@ public function testBeginTransactionMethodNeverRetriesIfWithinTransaction()\n }\n }\n \n- public function testCantSwapPDOWithOpenTransaction()\n+ public function testSwapPDOWithOpenTransactionResetsTransactionLevel()\n {\n $pdo = $this->createMock('DatabaseConnectionTestMockPDO');\n $pdo->expects($this->once())->method('beginTransaction')->will($this->returnValue(true));\n $connection = $this->getMockConnection([], $pdo);\n $connection->beginTransaction();\n- $this->setExpectedException('RuntimeException', \"Can't swap PDO instance while within transaction.\");\n $connection->disconnect();\n+ $this->assertEquals(0, $connection->transactionLevel());\n }\n \n public function testBeganTransactionFiresEventsIfSet()\n@@ -240,24 +240,42 @@ public function testTransactionMethodRollsbackAndThrows()\n }\n \n /**\n- * @expectedException RuntimeException\n+ * @expectedException \\Illuminate\\Database\\QueryException\n */\n- public function testTransactionMethodDisallowPDOChanging()\n+ public function testOnLostConnectionPDOIsNotSwappedWithinATransaction()\n {\n- $pdo = $this->getMockBuilder('DatabaseConnectionTestMockPDO')->setMethods(['beginTransaction', 'commit', 'rollBack'])->getMock();\n- $pdo->expects($this->once())->method('beginTransaction');\n- $pdo->expects($this->once())->method('rollBack');\n- $pdo->expects($this->never())->method('commit');\n+ $pdo = m::mock(PDO::class);\n+ $pdo->shouldReceive('beginTransaction')->once();\n+ $statement = m::mock(PDOStatement::class);\n+ $pdo->shouldReceive('prepare')->once()->andReturn($statement);\n+ $statement->shouldReceive('execute')->once()->andThrow(new PDOException('server has gone away'));\n \n- $mock = $this->getMockConnection([], $pdo);\n+ $connection = new \\Illuminate\\Database\\Connection($pdo);\n+ $connection->beginTransaction();\n+ $connection->statement('foo');\n+ }\n \n- $mock->setReconnector(function ($connection) {\n- $connection->setPDO(null);\n- });\n+ public function testOnLostConnectionPDOIsSwappedOutsideTransaction()\n+ {\n+ $pdo = m::mock(PDO::class);\n+\n+ $statement = m::mock(PDOStatement::class);\n+ $statement->shouldReceive('execute')->once()->andThrow(new PDOException('server has gone away'));\n+ $statement->shouldReceive('execute')->once()->andReturn('result');\n+\n+ $pdo->shouldReceive('prepare')->twice()->andReturn($statement);\n \n- $mock->transaction(function ($connection) {\n- $connection->reconnect();\n+ $connection = new \\Illuminate\\Database\\Connection($pdo);\n+\n+ $called = false;\n+\n+ $connection->setReconnector(function ($connection) use (&$called) {\n+ $called = true;\n });\n+\n+ $this->assertEquals('result', $connection->statement('foo'));\n+\n+ $this->assertTrue($called);\n }\n \n public function testRunMethodRetriesOnFailure()", "filename": "tests/Database/DatabaseConnectionTest.php", "status": "modified" } ] }
{ "body": "In Laravel 5.2.39, my app has\n\n.env\n\n```\nAPP_URL=http://dev.env/smartbots\n```\n\nconfig/app.php\n\n```\n'url' => env('APP_URL'),\n```\n\napp/Http/routes.php\n\n```\nRoute::get('test', function () {\n dd(route('twilioVoiceRequest'));\n});\n\nRoute::get('/twilio-voice-request', function() {\n})->name('twilioVoiceRequest');\n```\n\nArtisan command (twilio:setup)\n\n```\npublic function handle()\n{\n dd(route('twilioVoiceRequest'));\n}\n```\n\nThis is what i got from test route\n![untitled](https://cloud.githubusercontent.com/assets/12293622/16362615/113bf142-3bde-11e6-8b24-a5c6c3950be1.png)\n\nand from php artisan twilio:setup\n![untitled2](https://cloud.githubusercontent.com/assets/12293622/16362620/28f9a612-3bde-11e6-9e68-78272f6bebf0.png)\n", "comments": [ { "body": "Try adding a trailing slash to the URL and/or running `php artisan config:cache`.\n", "created_at": "2016-06-26T15:07:45Z" }, { "body": "i tried it before, still the same result\n", "created_at": "2016-06-26T15:55:36Z" }, { "body": "This is definitely due to an out of date config cache otherwise the cli would have just generated localhost.\n", "created_at": "2016-06-26T15:59:33Z" }, { "body": "APP URL only work on domain level, right?\n", "created_at": "2016-06-26T16:03:18Z" }, { "body": "It should be defining the base URI?\n", "created_at": "2016-06-26T16:29:52Z" }, { "body": "We definitely don't recommend you run apps on sub-folders though.\n", "created_at": "2016-06-26T16:30:11Z" }, { "body": "`route()` helper use `toRoute()` and `getRouteDomain()` https://github.com/laravel/framework/blob/5.2/src/Illuminate/Routing/UrlGenerator.php#L324\n\nIs this a bug?\n", "created_at": "2016-06-26T16:58:19Z" }, { "body": "Yeh, I'd say so.\n", "created_at": "2016-06-27T15:07:48Z" }, { "body": "With support @GrahamCampbell I would suggest, leave a slash at trail,laravel will auto handle your route.\n", "created_at": "2016-07-02T11:07:33Z" }, { "body": "Changing `$this->request->root()` with `$this->request->url()` [here](https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/UrlGenerator.php#L619) seems to fix this issue. \n\nWould that be an acceptable solution for you @GrahamCampbell ? I've run the unit tests and nothing seems to break but I didn't have time yet to check if this part is covered on the tests yet.\n", "created_at": "2016-09-22T19:21:14Z" }, { "body": "Ok, after further testing the above is not the solution when not using the console. We'll have to find a different fix (and ideally add some test to cover this code).\n", "created_at": "2016-09-22T21:53:22Z" }, { "body": "The problem seems to come all the way from `Symfony\\Component\\HttpFoundation\\SymfonyRequest`, in order to get the baseUrl of the request, `SymfonyRequest` compares the values of `$_SERVER['SCRIPT_NAME']` and `$_SERVER['SCRIPT_FILENAME']`, and those aren't being set by `Illuminate\\Foundation\\Bootstrap\\SetRequestForConsole`.\n", "created_at": "2016-09-26T13:16:25Z" }, { "body": "I can't recreate this issue: http://d.pr/i/1bqOj\n", "created_at": "2016-09-28T18:21:24Z" }, { "body": "I don't think you understood well what the issue is.\n\nWhen the config value of `app.url` is set ot something else than a base domain (like `http://some-random-url.com/somethingelse/`), all the routes generated from console by the UrlGenerator remove the path. On the other hand, if your app is set to be accessed through that same path, the UrlGenerator creates correct paths.\n\nNow, in order to recreate it you'll have to add some path to your base url.\n", "created_at": "2016-09-28T19:47:02Z" }, { "body": "config('app.url');\nusing the config helper function works fine\n\nI had this issue with the Queues The url helper returns http://localhost \n", "created_at": "2016-10-06T18:17:30Z" }, { "body": "@engAhmad , if you don't have http[s]?:// prefix to your environment url laravel will not detect it and overwrite it with http://localhost.\n", "created_at": "2016-10-07T13:42:05Z" }, { "body": "Until the situation is improved, as a workaround you could add this line early:\r\n\r\n```php\r\nurl()->forceRootUrl(config('app.url'));\r\n```", "created_at": "2016-11-25T21:33:34Z" }, { "body": "Basically the autodetection doesn't work in CLI, and we do have to pass the base URL to the UrlGenerator. I'm posting a few suggestions in #15608.", "created_at": "2016-11-25T22:17:40Z" }, { "body": "I think the reason because some functions use the root as it is calculated by symphony and not based on the env setting.\r\n\r\nI think the reason is this line: https://github.com/laravel/framework/blob/5.3/src/Illuminate/Http/Request.php#L87", "created_at": "2017-01-18T10:06:59Z" }, { "body": "Hence the 2 possible fixes I posted in #15608, which make use of `forcedRoot` in [UrlGenerator](https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/UrlGenerator.php).\r\n\r\nWe are in CLI so it's normal the request doesn't have an URL. Modifying the request doesn't sound right, while using `forcedRoot` of the UrlGenerator seems much more appropriate.", "created_at": "2017-01-18T11:32:30Z" }, { "body": "You might be right but I ran into this issue in more cases, not in CLI but in the web (actually on local development on homestead). I just think that if we have an APP_URL environment variable, we should use it - no?", "created_at": "2017-01-18T11:43:48Z" }, { "body": "I can't say for homestead… Let's reference issue #17385 you have just created :)", "created_at": "2017-01-18T11:58:27Z" }, { "body": "Thanks.\r\n\r\nBut what do you think about the general idea of: we already have an APP_URL environment variable, why isn't the url helper use it?", "created_at": "2017-01-18T13:05:57Z" }, { "body": "I'd say because it is not configured by default, so using it would require an extra step in new installs, while the autodetection works in most cases.\r\n\r\nAlso, the autodetection is convenient when the app can be accessed through several domains ;) Don't have to dynamically configure the path.", "created_at": "2017-01-18T13:16:32Z" }, { "body": "Yes you are correct. But in that case I think that A) Why is the APP_URL there and why the laravel config uses it? and B) The auto detection should work flawlessly... at least for web requests...", "created_at": "2017-01-18T13:21:18Z" }, { "body": "@amosmos The `APP_URL` is there to simulate requests only when using the console, it is actually explained on the (config file itself)[https://github.com/laravel/laravel/blob/master/config/app.php#L48].\r\nI've never experienced the issue with a web requests, having the installation on a subpath always worked flawlessly for me. Can you better describe your issue with web requests?", "created_at": "2017-01-18T13:46:21Z" }, { "body": "I had the exact same issue running a Artisan command that should generate my `sitemap.xml`.\r\nAll the generation was `Route `based to get routes URLs (and `LaravelLocalization `for translated routes URLs).\r\nWhat I had was wrong generated URL with `http://localhost` instead of full URL path (wich was correct when getting the same method from a HTTP request).\r\n\r\nSo, in my command `__construct()` method, i added:\r\n\r\n`!App::runningInConsole() ?: \\URL::forceRootUrl(\\Config::get('app.url'));`\r\n\r\nAnd URLs generation methods used in my Artisan command was based on the `app.url` value, same value as when fired from a HTTP request on a route. Maybe it's a way to force the URL for specific localy run methods, with Artisan or else.\r\n_(tested on L5.1, Wamp with full URL as `http://localhost/project_name/public/`, error URL from Artisan command was `http://localhost/`, `app.url` as `http://localhost/project_name/public/` - result for the same method fired from a Route GET or a Artisan command)._\r\n\r\nLinks: [pull #15608](https://github.com/laravel/framework/pull/15608), [stack](http://stackoverflow.com/questions/24625528/change-route-domain-to-ip-address-in-laravel)", "created_at": "2017-03-20T19:08:39Z" }, { "body": "I've looked into Symfony to see how they've solved the problem, when route URL is build from CLI and website is located at sub-path and found this:\r\n\r\n* docs: https://symfony.com/doc/current/console/request_context.html\r\n* `RequestContext` class: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/RequestContext.php\r\n* `UrlMatcher` class: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Matcher/UrlMatcher.php\r\n\r\nIt works like this:\r\n\r\n1. in the `app/config/parameters.yml` file you specify 3 settings: `host`, `scheme`, `base_url` (basically what can't be detected in CLI)\r\n2. the `RequestContext` class is created using these settings (see https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Resources/config/routing.xml#L81-L88)\r\n3. when `UrlMatcher` is building route url it's using data from context (see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Matcher/UrlMatcher.php#L257-L260) and also replacing `SCRIPT_FILENAME` and `SCRIPT_NAME` server attributes\r\n\r\nBased on that info and @j3j5 comment (see https://github.com/laravel/framework/issues/14139#issuecomment-249566343) I'm suggesting to change `\\Illuminate\\Foundation\\Bootstrap\\SetRequestForConsole::bootstrap` method like so:\r\n\r\n1. parse url in `app.url` config setting using `parse_url` function (don't use Symfony's Request because we're using it already and it fails in CLI)\r\n2. if the `path` component is found, then replace `SCRIPT_NAME` and `SCRIPT_FILENAME` in server array passed to Request creation later\r\n\r\n**Code before:** \r\n\r\n```php\r\n$app->instance('request', Request::create(\r\n $app->make('config')->get('app.url', 'http://localhost'), 'GET', [], [], [], $_SERVER\r\n));\r\n```\r\n\r\n**Code after:**\r\n\r\n```php\r\n$uri = $app->make('config')->get('app.url', 'http://localhost');\r\n$components = parse_url($uri);\r\n$server = $_SERVER;\r\n\r\nif (isset($components['path'])) {\r\n $server['SCRIPT_FILENAME'] = $components['path'];\r\n $server['SCRIPT_NAME'] = $components['path'];\r\n}\r\n\r\n$app->instance('request', Request::create($uri, 'GET', [], [], [], $server));\r\n```\r\n\r\nI can send a PR if you'd like as a bugfix.", "created_at": "2017-08-18T17:11:55Z" } ], "number": 14139, "title": "route() helper function does not work well in artisan commands" }
{ "body": "This change fixes #14139 .\n\nI am not sure where would tests for this belong. Should they go on `tests/Routing/RoutingUrlGeneratorTest.php` or on `tests\\Console\\ConsoleApplicationTest.php`? I think the former is better but I'd like to have somebody else opinion.\n", "number": 15608, "review_comments": [], "title": "[5.3] Change server variables when bootstrapping the app request from artisan." }
{ "commits": [ { "message": "Change server variables when bootstrapping the app request from artisan.\n\nThis change fixes #14139" } ], "files": [ { "diff": "@@ -16,7 +16,11 @@ class SetRequestForConsole\n public function bootstrap(Application $app)\n {\n $url = $app->make('config')->get('app.url', 'http://localhost');\n-\n+ $urlParts = parse_url($url);\n+ if (isset($urlParts['path']) && mb_strlen($urlParts['path']) > 1) {\n+ $_SERVER['SCRIPT_NAME'] = $urlParts['path'].DIRECTORY_SEPARATOR.'index.php';\n+ $_SERVER['SCRIPT_FILENAME'] = getenv('PWD').DIRECTORY_SEPARATOR.$urlParts['path'].DIRECTORY_SEPARATOR.'index.php';\n+ }\n $app->instance('request', Request::create($url, 'GET', [], [], [], $_SERVER));\n }\n }", "filename": "src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php", "status": "modified" } ] }
{ "body": "I tried this under my windows with PHP 7.0 (no way to enable pcntl):\n`php artisan queue:work --timeout=360 --queue=high,low --sleep=3 --tries=3`\nWill get this exception.\n\n```\n [RuntimeException]\n The pcntl extension is required in order to specify job timeouts.\n```\n\nBut same project in my server ( Ubuntu 16.04 with PHP 7.0 enable pcntl), it works fine.\nSo if it is necessary to add in \"Server Requirements\" ?\n", "comments": [ { "body": "Same... \nUnfortunately pcntnl is not available for Windows based systems.\n\nTried to run my queue with\n\n```\nphp artisan queue:work --daemon --sleep=1\n```\n\nand even\n\n```\nphp artisan queue:listen\n```\n\nGetting same error... Documentation said nothing about this change, So we must either run everything under Homestead or downgrade to 5.2...\n\n@taylorotwell What about windows users? Now we cannot use the queue system. \n", "created_at": "2016-08-20T14:58:57Z" }, { "body": "Windows users need to pass `--timeout 0`. We don't want to silently not use the timeout. If you don't want it, explicitly set it to 0 to disable it.\n", "created_at": "2016-08-20T15:55:09Z" }, { "body": "Gah! changing --timeout=0 to --timeout 0 did the trick thanks, it works now\n", "created_at": "2016-08-20T16:02:52Z" }, { "body": "@GrahamCampbell @taylorotwell we should maybe at a note on the docs regarding this issue. \n", "created_at": "2016-08-20T18:01:14Z" }, { "body": "Or we could just update the exception message to say turn the timeout off if you don't want timeouts?\n", "created_at": "2016-08-20T18:02:52Z" }, { "body": "Yeah might be better. \n", "created_at": "2016-08-20T18:09:23Z" }, { "body": "@gholol - I seem to be getting the same message using either syntax:\n\n![image](https://cloud.githubusercontent.com/assets/7282262/18206266/c735d192-711d-11e6-9817-38a4d60f5747.png)\n\nThis is on an 5.2-5.3 upgraded project - I'll try a fresh 5.3 project too.\n\n---\n\nEDIT: Yep - same issue. No error with `php artisan queue:work --timeout 0` however.\n", "created_at": "2016-09-02T14:03:24Z" }, { "body": "@wdmtech It doesn't work with queue listener, you have to use worker. \n\n`php artisan queue:work --daemon --timeout 0`\n", "created_at": "2016-09-02T16:52:46Z" }, { "body": "Thanks @gholol. I got it working that way. \n\nInteresting, any idea why not?\n\nIt has `--timeout` as an option\n\n![image](https://cloud.githubusercontent.com/assets/7282262/18213198/e487c6f8-713e-11e6-846f-145a87654bb1.png)\n", "created_at": "2016-09-02T17:56:17Z" }, { "body": "@wdmtech Since 5.3, there was a change and pcntl extension is now required to handle jobs.\n\nThere's no Pcntl for windows so Graham did make a fix with this pull request https://github.com/laravel/framework/pull/14741 \n\nI suspect he forgot about the listener :grinning: \n", "created_at": "2016-09-02T18:43:27Z" }, { "body": "Yes looks like we just need to handle fix this on the listen command maybe @GrahamCampbell? Can someone send over a PR?\n", "created_at": "2016-09-03T14:53:16Z" }, { "body": "I didn't forget about it as such. I just didn't expect anyone to want to use it.\n", "created_at": "2016-09-03T17:23:41Z" }, { "body": "I mean, we can fix it. :P\n", "created_at": "2016-09-03T17:23:57Z" } ], "number": 14909, "title": "[5.3]PHP have to --enable-pcntl if use queue" }
{ "body": "Fixes #14909 \n", "number": 15393, "review_comments": [ { "body": "Please sort by length.\n", "created_at": "2016-09-11T10:20:37Z" }, { "body": "Missing newline and slash.\n", "created_at": "2016-09-11T15:19:08Z" } ], "title": "[5.3] Fix pcntl extension error for queue" }
{ "commits": [ { "message": "Fix pcntl extension error for queue" } ], "files": [ { "diff": "@@ -2,6 +2,7 @@\n \n namespace Illuminate\\Queue\\Console;\n \n+use RuntimeException;\n use Illuminate\\Queue\\Listener;\n use Illuminate\\Console\\Command;\n use Symfony\\Component\\Console\\Input\\InputOption;\n@@ -47,6 +48,8 @@ public function __construct(Listener $listener)\n * Execute the console command.\n *\n * @return void\n+ *\n+ * @throws \\RuntimeException\n */\n public function fire()\n {\n@@ -63,6 +66,10 @@ public function fire()\n \n $timeout = $this->input->getOption('timeout');\n \n+ if ($timeout && ! function_exists('pcntl_fork')) {\n+ throw new RuntimeException('Timeouts not supported without the pcntl_fork extension.');\n+ }\n+\n // We need to get the right queue for the connection which is set in the queue\n // configuration file for the application. We will pull it based on the set\n // connection being run for the queue operation currently being executed.", "filename": "src/Illuminate/Queue/Console/ListenCommand.php", "status": "modified" } ] }
{ "body": "Check jobs before working to see if they have already been received too many times.\n\nResolves an issue with the `--timeout` feature where jobs the repeatedly timed out would never be marked as `failed`, as the worker process would be killed before\nit could reach the failing logic.\n\nTo maintain compatibility there are now two checks against the number of attempts a job has had, one before working the job and one in the case of an job raising an exception.\n\nsee laravel/framework#15317 for more details.\n", "comments": [ { "body": "Thanks for the PR. :)\n", "created_at": "2016-09-07T11:24:13Z" }, { "body": "Pushed up your suggested style fixes GC. Let me know on any further\n", "created_at": "2016-09-07T11:28:30Z" }, { "body": "I've also noticed the above issue @Landish reported, you cannot just run `php artisan queue:listen` without setting `--tries` to at least `1`\n\nThis could be resolved by changing the conditional on `line 269` of `src/Illuminate/Queue/Worker.php`\n\nfrom \n\n```\nif ($maxTries === 0 || $job->attempts() <= $maxTries) {\n```\n\nto\n\n```\nif ($maxTries == 0 || $job->attempts() <= $maxTries) {\n```\n\nBasically, `$maxTries` comes in as a string so it will always result in false.\n\nI'm going to PR this fix.\n\nAlso @maxbrokman nice work on this PR. Hope all is well.\n", "created_at": "2016-09-11T01:56:10Z" }, { "body": "Looks like a bug. The default was meant to be unlimited retrys.\n", "created_at": "2016-09-11T08:59:10Z" }, { "body": "I have the same problem as @Landish says about the \"markJobAsFailedIfAlreadyExceedsMaxAttempts\" exception.\n", "created_at": "2016-09-13T21:55:33Z" }, { "body": "\"maxTries 0\" bug fixed in 5.3.9, refs #15370 and #15390.\n", "created_at": "2016-09-17T21:14:45Z" }, { "body": "Hi ! My case it is , I think, subtly different. I recently moved from 5.2 to 5.3 and my scheduled commands including these lines\r\n\r\n```\r\napp/Console/Kernel.php:33: $schedule->command('queue:work')->everyFiveMinutes();\r\napp/Console/Kernel.php:34: $schedule->command('queue:work --queue=import')->everyFiveMinutes();\r\n```\r\n\r\nare causing hundred of MySQL never dying processes (quite long Sleep status and mounting up).\r\n\r\nI've searched a lot and the closest issue is this one, but it does not look to be exact the same as, among others, I do not see any exceeded time exception in logs.", "created_at": "2018-03-01T09:39:13Z" } ], "number": 15319, "title": "[5.3] Check attempts before firing queue job." }
{ "body": "Fixes the issue where running `php artisan queue:listen` marks jobs failed unless `--tries=1`\n\nThe issue is referenced in #15319\n", "number": 15390, "review_comments": [], "title": "[5.3] change to loosey comparison to allow queue to run without --tries" }
{ "commits": [ { "message": "change to loosey comparison to allow queue to run without --tries" } ], "files": [ { "diff": "@@ -266,7 +266,7 @@ protected function handleJobException($connectionName, $job, WorkerOptions $opti\n */\n protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $job, $maxTries)\n {\n- if ($maxTries === 0 || $job->attempts() <= $maxTries) {\n+ if ($maxTries == 0 || $job->attempts() <= $maxTries) {\n return;\n }\n ", "filename": "src/Illuminate/Queue/Worker.php", "status": "modified" } ] }
{ "body": "", "comments": [], "number": 14994, "title": "[5.1] Revert aggregate changes" }
{ "body": "A change to the query builder sum function introduced on revert #14994 presents an issues where the sum function would return values other than of numeric type. It is my understanding that the sum() function should always return a numeric type, as before it used to perform a simple return 0 if result was false.\n", "number": 15150, "review_comments": [], "title": "[5.2] Fixed issue introduced on reverting previous aggregate functions" }
{ "commits": [ { "message": "Fixed issue introduced on reverting previous aggregate functions\n\nA change to the query builder sum function introduced issues where the sum function would return values other than of numeric type." } ], "files": [ { "diff": "@@ -1950,11 +1950,11 @@ public function max($column)\n * Retrieve the sum of the values of a given column.\n *\n * @param string $column\n- * @return mixed\n+ * @return float\n */\n public function sum($column)\n {\n- return $this->aggregate(__FUNCTION__, [$column]);\n+ return $this->numericAggregate(__FUNCTION__, [$column]);\n }\n \n /**", "filename": "src/Illuminate/Database/Query/Builder.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": "With latest release, initial `laravel new` and `composer install` always fails, because `$this->dontReport` is set to null ! Simple solution is to ensure dontReport is always an array, or just simply convert it to.\n\nException:\n\n```\nLoading composer repositories with package information\nInstalling dependencies (including require-dev) from lock file\nNothing to install or update\nGenerating autoload files\n> Illuminate\\Foundation\\ComposerScripts::postInstall\n> php artisan optimize\nPHP Fatal error: Uncaught ErrorException: array_merge(): Argument #1 is not an array in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:93\nStack trace:\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'array_merge(): ...', '/opt/c/opt/Code...', 93, Array)\n#1 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(93): array_merge(Array)\n#2 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(61): Illuminate\\Foundation\\Exceptions\\Handler->shouldntReport(Object(ErrorException))\n#3 /opt/c/opt/Code/Laravel/app/Exceptions/Handler.php(35): Illuminate\\Foundation\\Exceptions\\Handler->report(Object(ErrorException))\n#4 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(79): App\\Exceptions\\Handler->report(Object(ErrorException))\n#5 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExcep in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php on line 93\nPHP Fatal error: Uncaught ErrorException: array_merge(): Argument #1 is not an array in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:93\nStack trace:\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'array_merge(): ...', '/opt/c/opt/Code...', 93, Array)\n#1 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(93): array_merge(Array)\n#2 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(61): Illuminate\\Foundation\\Exceptions\\Handler->shouldntReport(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException))\n#3 /opt/c/opt/Code/Laravel/app/Exceptions/Handler.php(35): Illuminate\\Foundation\\Exceptions\\Handler->report(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException))\n#4 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(79): App\\Exceptions\\Handler->report(Object(Symfon in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php on line 93\n```\n", "number": 15029, "review_comments": [], "title": "[5.3] [BUGFIX] Ensure dontReport is array" }
{ "commits": [ { "message": "Ensure dontReport is array\n\non last release, initial `laravel new` and `composer install` always fails, because `$this->dontReport` is set to null ! Simple solution is to ensure dontReport is always an array, or just simply convert it to.\r\n\r\nException:\r\n```\r\nLoading composer repositories with package information\r\nInstalling dependencies (including require-dev) from lock file\r\nNothing to install or update\r\nGenerating autoload files\r\n> Illuminate\\Foundation\\ComposerScripts::postInstall\r\n> php artisan optimize\r\nPHP Fatal error: Uncaught ErrorException: array_merge(): Argument #1 is not an array in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:93\r\nStack trace:\r\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'array_merge(): ...', '/opt/c/opt/Code...', 93, Array)\r\n#1 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(93): array_merge(Array)\r\n#2 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(61): Illuminate\\Foundation\\Exceptions\\Handler->shouldntReport(Object(ErrorException))\r\n#3 /opt/c/opt/Code/Laravel/app/Exceptions/Handler.php(35): Illuminate\\Foundation\\Exceptions\\Handler->report(Object(ErrorException))\r\n#4 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(79): App\\Exceptions\\Handler->report(Object(ErrorException))\r\n#5 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExcep in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php on line 93\r\nPHP Fatal error: Uncaught ErrorException: array_merge(): Argument #1 is not an array in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php:93\r\nStack trace:\r\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'array_merge(): ...', '/opt/c/opt/Code...', 93, Array)\r\n#1 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(93): array_merge(Array)\r\n#2 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(61): Illuminate\\Foundation\\Exceptions\\Handler->shouldntReport(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException))\r\n#3 /opt/c/opt/Code/Laravel/app/Exceptions/Handler.php(35): Illuminate\\Foundation\\Exceptions\\Handler->report(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException))\r\n#4 /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(79): App\\Exceptions\\Handler->report(Object(Symfon in /opt/c/opt/Code/Laravel/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php on line 93\r\n```" } ], "files": [ { "diff": "@@ -90,7 +90,7 @@ public function shouldReport(Exception $e)\n */\n protected function shouldntReport(Exception $e)\n {\n- $dontReport = array_merge($this->dontReport, [HttpResponseException::class]);\n+ $dontReport = array_merge(is_array($this->dontReport) ? $this->dontReport : [], [HttpResponseException::class]);\n \n foreach ($dontReport as $type) {\n if ($e instanceof $type) {", "filename": "src/Illuminate/Foundation/Exceptions/Handler.php", "status": "modified" } ] }
{ "body": "According to the docs (phpDocs and laravel-docs) makeHidden function can be used with a string (for only one attribute) but 45d6abfe makes it fail because array_merge() expects both parameters to be arrays. \n\nThis bug is also present on master.\n", "comments": [], "number": 14852, "title": "[5.2] Fix for Eloquent function makeHidden() when used with a string. " }
{ "body": "Cast only once to array.\n\n---\n\nRelated to #14852 \n", "number": 14857, "review_comments": [], "title": "[5.2] Cast only once to array." }
{ "commits": [ { "message": "Cast only one to array." } ], "files": [ { "diff": "@@ -2148,9 +2148,11 @@ public function makeVisible($attributes)\n */\n public function makeHidden($attributes)\n {\n- $this->visible = array_diff($this->visible, (array) $attributes);\n+ $attributes = (array) $attributes;\n \n- $this->hidden = array_unique(array_merge($this->hidden, (array) $attributes));\n+ $this->visible = array_diff($this->visible, $attributes);\n+\n+ $this->hidden = array_unique(array_merge($this->hidden, $attributes));\n \n return $this;\n }", "filename": "src/Illuminate/Database/Eloquent/Model.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": "On the 4.2 branch, calling `Response::json($x)` where `json_encode($x)` fails (e.g., where $x is an invalid UTF-8 character string) produces the following:\n\n```\nlocal.ERROR: exception 'UnexpectedValueException' with message 'The Response content must be a string or object implementing __toString(), \"boolean\" given.' in /www/gateway/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Response.php:403\nStack trace:\n#0 /www/gateway/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/JsonResponse.php(173): Symfony\\Component\\HttpFoundation\\Response->setContent(false)\n#1 /www/gateway/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php(52): Symfony\\Component\\HttpFoundation\\JsonResponse->update()\n#2 /www/gateway/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/JsonResponse.php(49): Illuminate\\Http\\JsonResponse->setData(Array)\n#3 /www/gateway/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php(28): Symfony\\Component\\HttpFoundation\\JsonResponse->__construct(Array, 200, Array)\n```\n\nBased on this alone, it's not clear that `json_encode()` failing is the cause of the error. The [Symfony JsonResponse class from which this is derived handles this](https://github.com/symfony/http-foundation/blob/6a5b4e01eeb168cea372c6a7eac023b80b31e846/JsonResponse.php#L113), but the `setData` method is overridden in the Laravel implementation. The [5.2 branch also looks for an error on json_encode() and emits a more useful exception](https://github.com/laravel/framework/blob/249c948ce62dd9543e23cb2d7158f5edb651bf67/src/Illuminate/Http/JsonResponse.php#L45), so I'm backporting that logic here. Since `json_last_error_msg()` was added in PHP 5.5.0 and Laravel 4.2 supports PHP 5.4.0, I have to additionally check that this function exists.\n", "number": 14798, "review_comments": [], "title": "Backport JSON encoding exception handling to 4.2" }
{ "commits": [ { "message": "Backport JSON encoding exception handling to 4.2" } ], "files": [ { "diff": "@@ -1,6 +1,7 @@\n <?php namespace Illuminate\\Http;\n \n use Illuminate\\Support\\Contracts\\JsonableInterface;\n+use InvalidArgumentException;\n \n class JsonResponse extends \\Symfony\\Component\\HttpFoundation\\JsonResponse {\n \n@@ -49,6 +50,14 @@ public function setData($data = array())\n \t\t\t\t\t\t\t\t ? $data->toJson($this->jsonOptions)\n \t\t\t\t\t\t\t\t : json_encode($data, $this->jsonOptions);\n \n+ if (JSON_ERROR_NONE !== json_last_error()) {\n+ if (function_exists('json_last_error_msg')) {\n+ throw new InvalidArgumentException(json_last_error_msg());\n+ } else {\n+ throw new InvalidArgumentException('A JSON encoding error occurred', json_last_error());\n+ }\n+ }\n+\n \t\treturn $this->update();\n \t}\n ", "filename": "src/Illuminate/Http/JsonResponse.php", "status": "modified" } ] }
{ "body": "Alias View as ViewContract\n", "comments": [ { "body": "👍 \n", "created_at": "2016-08-07T09:55:24Z" }, { "body": "Is a breaking change to change the type hint.\n", "created_at": "2016-08-07T17:21:45Z" }, { "body": "True dat.\n", "created_at": "2016-08-07T19:01:46Z" } ], "number": 14671, "title": "[5.2] Alias View as ViewContract" }
{ "body": "Alias View as ViewContract\n\n---\n\nReplace #14671 \n", "number": 14673, "review_comments": [], "title": "[5.3] Alias View as ViewContract" }
{ "commits": [ { "message": "Alias View as ViewContract" } ], "files": [ { "diff": "@@ -11,6 +11,7 @@\n use Illuminate\\View\\Engines\\EngineResolver;\n use Illuminate\\Contracts\\Events\\Dispatcher;\n use Illuminate\\Contracts\\Container\\Container;\n+use Illuminate\\Contracts\\View\\View as ViewContract;\n use Illuminate\\Contracts\\View\\Factory as FactoryContract;\n \n class Factory implements FactoryContract\n@@ -513,7 +514,7 @@ protected function parseClassEvent($class, $prefix)\n * @param \\Illuminate\\Contracts\\View\\View $view\n * @return void\n */\n- public function callComposer(View $view)\n+ public function callComposer(ViewContract $view)\n {\n $this->events->fire('composing: '.$view->getName(), [$view]);\n }\n@@ -524,7 +525,7 @@ public function callComposer(View $view)\n * @param \\Illuminate\\Contracts\\View\\View $view\n * @return void\n */\n- public function callCreator(View $view)\n+ public function callCreator(ViewContract $view)\n {\n $this->events->fire('creating: '.$view->getName(), [$view]);\n }", "filename": "src/Illuminate/View/Factory.php", "status": "modified" } ] }
{ "body": "Fixes the issue I have pointed in these [comments](https://github.com/laravel/framework/commit/d48e5312550e7df050f63c5040c3043cde96f369#commitcomment-17917096).\n", "comments": [ { "body": "I have refined the code:\n- Consistent across `select()` and `cursor()`.\n- Makes it clear we are handling the erroneous use of `PDO::FETCH_CLASS` without class name (https://github.com/laravel/laravel/pull/3814).\n- Supports as well modes such as `PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE` (of course the user is expected to provide a class name).\n\nping @jdpanderson as this might interest you.\n", "created_at": "2016-06-19T22:04:01Z" }, { "body": "Slightly adjusted `testAlternateFetchModes` (which btw doesn't test the modes are actually working).\n\nBecause `setFetchMode(PDO::FETCH_CLASS, 'stdClass', [1, 2, 3]);` would actually produce this error:\n\n> PDOStatement::setFetchMode(): SQLSTATE[HY000]: General error: user-supplied class does not have a constructor, use NULL for the ctor_params parameter, or simply omit it\n\nWith `PDO::FETCH_CLASS` and `'stdClass'`, constructor argument (3rd argument) can be: omitted, null, empty array. Edit: HHVM doesn't support empty array to skip the argument, it has to be omitted or null.\n", "created_at": "2016-06-21T03:16:00Z" }, { "body": "Hey @vlakoff, since this has been merged into the v5.2.40 release, I and others (https://laracasts.com/discuss/channels/forge/sqlstatehy000-general-error-user-supplied-class-does-not-have-a-constructor) have been seeing intermittent SQL errors, and this commit seems to be what is causing them.\n\nFor some select queries, I'm getting:\n`SQLSTATE[HY000]: General error: user-supplied class does not have a constructor, use NULL for the ctor_params parameter, or simply omit it`\nThe stack trace leads to line 345 of the Connection file as the culprit:\n`return isset($fetchArgument)\n ? $statement->fetchAll($fetchMode, $fetchArgument, $me->getFetchConstructorArgument())\n : $statement->fetchAll($fetchMode);`\n\nTo be perfectly honest, I'm not exactly sure what is happening here, but I hadn't had any issues before this was merged. Any idea on what could be happening here?\n", "created_at": "2016-07-22T15:09:46Z" }, { "body": "Sigh. What needs to happen to fix this @vlakoff \n", "created_at": "2016-07-22T22:18:31Z" }, { "body": "Fixed by #14429.\n", "created_at": "2016-07-22T22:52:41Z" }, { "body": "Hey guys, I'm still having problem on my DO server deployed by Forge.\n\nOn my local machine there are no problems.\n\nLocally I'm using mysql and on forge I selected Maria and HHVM (though I don't know anything about HHVM I just Googled it when I was deploying the server and it seemed as something that I should investigate and use in the future). \n\n> General error: user-supplied class does not have a constructor, use NULL for the ctor_params parameter, or simply omit it (SQL: select exists(select \\* from `users` where `email` = my.email@gmail.com and `users`.`deleted_at` is null) as `exists`)\n\nI'm sending an email to the App and checking if there is a user with this email in it (using softdeletes).\n", "created_at": "2016-07-31T13:58:18Z" }, { "body": "That's in the above linked PR.\n\nI had fixed `cursor()` but introduced an incompatibility of both `select()` and `cursor()` with HHVM. So basically Laravel 5.2.40 and 5.2.41 are broken on HHVM.\n\nI had submitted a PR less than two hours after the bug report. It has been merged, but we still need a new Laravel 5.2 release to be tagged.\n\nFor now you have to hold on Laravel 5.2.39.\n", "created_at": "2016-07-31T22:14:35Z" }, { "body": "Hey guys, I'm still getting this the same error on 5.2.42\n", "created_at": "2016-08-01T14:11:48Z" }, { "body": "In your composer.json replace\n\n\"laravelcollective/html\": \"5.2.*\",\n\nwith \n\n\"laravelcollective/html\": \"5.2.39\",\n\nThis will force your app to use the .39 version where the bug doesn't exist.\n", "created_at": "2016-08-01T14:14:47Z" }, { "body": "[Laravel 5.2.42](https://github.com/laravel/framework/commit/d1bf46f359d2ede2d4ef847fb79d3758d868f2b7) just released :)\n", "created_at": "2016-08-08T17:08:49Z" } ], "number": 14052, "title": "[5.2] Properly support PDO::FETCH_CLASS in cursor()" }
{ "body": "HHVM doesn't support using an empty array to omit the 3rd parameter \"constructor argument\".\n\nRefs #14052 and #14426.\n", "number": 14429, "review_comments": [], "title": "[5.2] Fix PDO connection on HHVM with the default \"class without name\" case" }
{ "commits": [ { "message": "Fix PDO connection on HHVM with the default \"class without name\" case\n\nHHVM doesn't support using an empty array to omit the 3rd parameter \"constructor argument\"." } ], "files": [ { "diff": "@@ -336,13 +336,15 @@ public function select($query, $bindings = [], $useReadPdo = true)\n \n $fetchMode = $me->getFetchMode();\n $fetchArgument = $me->getFetchArgument();\n+ $fetchConstructorArgument = $me->getFetchConstructorArgument();\n \n if ($fetchMode === PDO::FETCH_CLASS && ! isset($fetchArgument)) {\n $fetchArgument = 'StdClass';\n+ $fetchConstructorArgument = null;\n }\n \n return isset($fetchArgument)\n- ? $statement->fetchAll($fetchMode, $fetchArgument, $me->getFetchConstructorArgument())\n+ ? $statement->fetchAll($fetchMode, $fetchArgument, $fetchConstructorArgument)\n : $statement->fetchAll($fetchMode);\n });\n }\n@@ -366,13 +368,15 @@ public function cursor($query, $bindings = [], $useReadPdo = true)\n \n $fetchMode = $me->getFetchMode();\n $fetchArgument = $me->getFetchArgument();\n+ $fetchConstructorArgument = $me->getFetchConstructorArgument();\n \n if ($fetchMode === PDO::FETCH_CLASS && ! isset($fetchArgument)) {\n $fetchArgument = 'StdClass';\n+ $fetchConstructorArgument = null;\n }\n \n if (isset($fetchArgument)) {\n- $statement->setFetchMode($fetchMode, $fetchArgument, $me->getFetchConstructorArgument());\n+ $statement->setFetchMode($fetchMode, $fetchArgument, $fetchConstructorArgument);\n } else {\n $statement->setFetchMode($fetchMode);\n }", "filename": "src/Illuminate/Database/Connection.php", "status": "modified" } ] }
{ "body": "", "comments": [ { "body": "Ah, thanks I shall test it this afternoon\n", "created_at": "2015-10-15T09:45:14Z" }, { "body": ":)\n", "created_at": "2015-10-15T09:45:38Z" }, { "body": "To answer your question from https://github.com/laravel/framework/issues/10604#issuecomment-148334017 that is the only additional error message I've spotted. I've asked the person who reported it to me and he said the same thing.\n\nI'll keep an eye out and let you know if any others appear, but that has been the only one in a few days of trying to figure out what was happening.\n\nApparently it is also possible to have \"Error while sending QUERY packet\" but presumably Laravel always uses prepared statements? and \"Error while sending STMT_CLOSE packet\" but I'm guessing that can safely be ignored? But as I said, I've never had those happen\n", "created_at": "2015-10-15T10:40:08Z" }, { "body": "So, typically, `Error while sending`.\n", "created_at": "2015-10-15T13:54:13Z" }, { "body": "Seems to be working :) Thanks\n", "created_at": "2015-10-15T14:53:13Z" }, { "body": ":)\n", "created_at": "2015-10-15T16:54:21Z" }, { "body": "I was going to port this fix to 4.2 - but is Taylor still accepting pull requests for 4.2?\n", "created_at": "2016-04-08T08:13:22Z" }, { "body": "No. Only bug fixes to 5.1, and only security fixes to 5.0 and lower.\n", "created_at": "2016-04-08T09:24:18Z" } ], "number": 10609, "title": "[5.1] Added message typical of lost connection on MariaDB" }
{ "body": "Ran into this issue #10609 running 4.2\n", "number": 13744, "review_comments": [], "title": "Backport Pull Request #10609 to 4.2" }
{ "commits": [ { "message": "Backport Pull Request #10609" } ], "files": [ { "diff": "@@ -4,6 +4,7 @@\n use Closure;\n use DateTime;\n use Illuminate\\Events\\Dispatcher;\n+use Illuminate\\Support\\Str;\n use Illuminate\\Database\\Query\\Processors\\Processor;\n use Doctrine\\DBAL\\Connection as DoctrineConnection;\n \n@@ -661,7 +662,15 @@ protected function tryAgainIfCausedByLostConnection(QueryException $e, $query, $\n \t */\n \tprotected function causedByLostConnection(QueryException $e)\n \t{\n-\t\treturn str_contains($e->getPrevious()->getMessage(), 'server has gone away');\n+\t\t$message = $e->getPrevious()->getMessage();\n+\n+\t\treturn Str::contains($message, [\n+\t\t\t'server has gone away',\n+\t\t\t'no connection to the server',\n+\t\t\t'Lost connection',\n+\t\t\t'is dead or not enabled',\n+\t\t\t'Error while sending',\n+\t\t]);\n \t}\n \n \t/**", "filename": "src/Illuminate/Database/Connection.php", "status": "modified" } ] }
{ "body": "I came to an unexpected result when using **makeVisible** method and not making the attributes I passed visible, so I saw that the reason was that the method will only make visible the fields if them are in the 'hidden' property.\n\nModel.php\n\n``` php\n protected $visible = ['remaining', 'restored_at'];\n```\n\n``` php\n // id not returned\n $model->all()->makeVisible(['id'])->toArray();\n```\n\nInstead having Model.php\n\n``` php\n protected $hidden = ['id'];\n```\n\n``` php\n // id returned\n $model->all()->makeVisible(['id'])->toArray();\n```\n\nThe easy workaround would be using hidden property but I'm making a package and I need to get a full properties toArray() no matter which property the user uses.\n\nIs this the expected behaviour?\n", "comments": [ { "body": "Ping @taylorotwell.\n", "created_at": "2016-03-28T12:50:04Z" }, { "body": "I was facing the same problem. I ended using the hidden property.\n\nIn my opinion makeVisible should... make visible the passed attributes, so yes, weird behaviour.\n", "created_at": "2016-03-31T10:15:14Z" }, { "body": "....I've run into this bug too...\ndebug for a total afternoon!\n\nthks @marcmascarell \n", "created_at": "2016-05-23T10:42:04Z" }, { "body": "Fix already merged.\n", "created_at": "2016-05-23T13:01:03Z" }, { "body": "Will be available in the next release.\n", "created_at": "2016-05-23T13:01:28Z" } ], "number": 12894, "title": "Eloquent Collection's makeVisible method only works when using the 'hidden' property" }
{ "body": "Closes Issue #12894 \n\nI have chosen to add the given attributes to the visible property when it is not empty.\n", "number": 13625, "review_comments": [], "title": "[5.2] Laravel Collection's makeVisible method should work when the 'visible' property already has values" }
{ "commits": [ { "message": "Laravel Collection's makeVisible method should work when the 'visible' property already has values" } ], "files": [ { "diff": "@@ -2136,6 +2136,10 @@ public function makeVisible($attributes)\n {\n $this->hidden = array_diff($this->hidden, (array) $attributes);\n \n+ if (! empty($this->visible)) {\n+ $this->addVisible($attributes);\n+ }\n+\n return $this;\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -250,9 +250,19 @@ public function testNonModelRelatedMethods()\n $this->assertEquals(get_class($a->zip(['a', 'b'], ['c', 'd'])), BaseCollection::class);\n $this->assertEquals(get_class($b->flip()), BaseCollection::class);\n }\n+\n+ public function testMakeVisibleRemovesHiddenAndIncludesVisible()\n+ {\n+ $c = new Collection([new TestEloquentCollectionModel]);\n+ $c = $c->makeVisible('hidden');\n+\n+ $this->assertEquals([], $c[0]->getHidden());\n+ $this->assertEquals(['visible', 'hidden'], $c[0]->getVisible());\n+ }\n }\n \n class TestEloquentCollectionModel extends Illuminate\\Database\\Eloquent\\Model\n {\n+ protected $visible = ['visible'];\n protected $hidden = ['hidden'];\n }", "filename": "tests/Database/DatabaseEloquentCollectionTest.php", "status": "modified" } ] }
{ "body": "The code\n\n``` php\nConfig::get('dbconfig::dbconfig.table')\n```\n\nreturn content of config in app but in migration it is 'null'\n", "comments": [ { "body": "This is because a packages config is registered in the `boot()` method of a service provider. The application is never \"booted\" as such when run via Artisan.\n\nPerhaps @taylorotwell can boot registered service providers when running in the console.\n\nFor now @sajjad-ser you can manually register your packages config in the `register()` method of your service provider.\n\n```\n$this->app['config']->package('<vendor>/<package>', __DIR__.'/../../config');\n```\n\nFirst parameter should be your packages `vendor/package` and the second should be the path to the packages `config` directory.\n", "created_at": "2013-01-15T07:19:18Z" }, { "body": "Tank you @jasonlewis \n", "created_at": "2013-01-15T07:29:48Z" }, { "body": "Yeah all packages probably need to be booted in Artisan. Will look into this.\n", "created_at": "2013-01-20T14:30:33Z" }, { "body": "Fixed.\n", "created_at": "2013-01-24T05:43:40Z" } ], "number": 38, "title": "Configuration of package isn not loaded in migration" }
{ "body": "This broke Cachet, among other things.\n\n```\n[2016-04-27 09:09:31] testing.ERROR: BadMethodCallException: Method Mockery_0_Illuminate_Contracts_Events_Dispatcher::listen() does not exist on this mock object in /media/sf_GitHub/Cachet/Cachet/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php(16) : eval()'d code:709\nStack trace:\n#0 /media/sf_GitHub/Cachet/Cachet/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php(16) : eval()'d code(761): Mockery_0_Illuminate_Contracts_Events_Dispatcher->_mockery_handleMethodCall('listen', Array)\n#1 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1286): Mockery_0_Illuminate_Contracts_Events_Dispatcher->listen('eloquent.saving...', 'AltThree\\\\Valida...', 0)\n#2 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(423): Illuminate\\Database\\Eloquent\\Model::registerModelEvent('saving', 'AltThree\\\\Valida...', 0)\n#3 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/validator/src/ValidatingTrait.php(30): Illuminate\\Database\\Eloquent\\Model::observe(Object(AltThree\\Validator\\ValidatingObserver))\n#4 [internal function]: CachetHQ\\Cachet\\Models\\Subscriber::bootValidatingTrait()\n#5 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(323): forward_static_call(Array)\n#6 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(309): Illuminate\\Database\\Eloquent\\Model::bootTraits()\n#7 /media/sf_GitHub/Cachet/Cachet/app/Models/Subscriber.php(63): Illuminate\\Database\\Eloquent\\Model::boot()\n#8 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(296): CachetHQ\\Cachet\\Models\\Subscriber::boot()\n#9 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(277): Illuminate\\Database\\Eloquent\\Model->bootIfNotBooted()\n#10 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(3505): Illuminate\\Database\\Eloquent\\Model->__construct()\n#11 /media/sf_GitHub/Cachet/Cachet/app/Bus/Handlers/Commands/Subscriber/SubscribeSubscriberCommandHandler.php(40): Illuminate\\Database\\Eloquent\\Model::__callStatic('where', Array)\n#12 [internal function]: CachetHQ\\Cachet\\Bus\\Handlers\\Commands\\Subscriber\\SubscribeSubscriberCommandHandler->handle(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#13 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/bus/src/Dispatcher.php(225): call_user_func(Array, Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#14 [internal function]: AltThree\\Bus\\Dispatcher->AltThree\\Bus\\{closure}(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#15 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(150): call_user_func(Object(Closure), Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#16 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#17 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#18 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/bus/src/Dispatcher.php(226): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#19 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/bus/src/Dispatcher.php(201): AltThree\\Bus\\Dispatcher->dispatchNow(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand), NULL)\n#20 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(323): AltThree\\Bus\\Dispatcher->dispatch(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#21 /media/sf_GitHub/Cachet/Cachet/app/Http/Controllers/Api/SubscriberController.php(46): dispatch(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#22 [internal function]: CachetHQ\\Cachet\\Http\\Controllers\\Api\\SubscriberController->postSubscribers()\n#23 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(80): call_user_func_array(Array, Array)\n#24 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(146): Illuminate\\Routing\\Controller->callAction('postSubscribers', Array)\n#25 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(94): Illuminate\\Routing\\ControllerDispatcher->call(Object(CachetHQ\\Cachet\\Http\\Controllers\\Api\\SubscriberController), Object(Illuminate\\Routing\\Route), 'postSubscribers')\n#26 [internal function]: Illuminate\\Routing\\ControllerDispatcher->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#27 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#28 [internal function]: Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#29 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#30 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(96): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#31 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(54): Illuminate\\Routing\\ControllerDispatcher->callWithinStack(Object(CachetHQ\\Cachet\\Http\\Controllers\\Api\\SubscriberController), Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request), 'postSubscribers')\n#32 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Route.php(174): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request), 'CachetHQ\\\\Cachet...', 'postSubscribers')\n#33 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Route.php(140): Illuminate\\Routing\\Route->runController(Object(Illuminate\\Http\\Request))\n#34 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(724): Illuminate\\Routing\\Route->run(Object(Illuminate\\Http\\Request))\n#35 [internal function]: Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#36 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#37 /media/sf_GitHub/Cachet/Cachet/app/Http/Middleware/ApiAuthentication.php(67): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#38 [internal function]: CachetHQ\\Cachet\\Http\\Middleware\\ApiAuthentication->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'true')\n#39 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#40 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#41 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#42 /media/sf_GitHub/Cachet/Cachet/app/Http/Middleware/Timezone.php(53): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#43 [internal function]: CachetHQ\\Cachet\\Http\\Middleware\\Timezone->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#44 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#45 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#46 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#47 /media/sf_GitHub/Cachet/Cachet/app/Http/Middleware/Acceptable.php(35): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#48 [internal function]: CachetHQ\\Cachet\\Http\\Middleware\\Acceptable->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#49 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#50 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#51 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#52 /media/sf_GitHub/Cachet/Cachet/vendor/barryvdh/laravel-cors/src/HandleCors.php(34): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#53 [internal function]: Barryvdh\\Cors\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#54 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#55 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#56 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#57 [internal function]: Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#58 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#59 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(726): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#60 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(699): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))\n#61 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))\n#62 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))\n#63 [internal function]: Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))\n#64 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#65 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#66 [internal function]: Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#67 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#68 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#69 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#70 /media/sf_GitHub/Cachet/Cachet/vendor/fideloper/proxy/src/TrustProxies.php(46): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#71 [internal function]: Fideloper\\Proxy\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#72 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#73 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#74 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#75 [internal function]: Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#76 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#77 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#78 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\n#79 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(506): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\n#80 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(126): Illuminate\\Foundation\\Testing\\TestCase->call('POST', '/api/v1/subscri...', Array, Array, Array, Array)\n#81 /media/sf_GitHub/Cachet/Cachet/tests/Api/SubscriberTest.php(47): Illuminate\\Foundation\\Testing\\TestCase->post('/api/v1/subscri...', Array)\n#82 [internal function]: CachetHQ\\Tests\\Cachet\\Api\\SubscriberTest->testCreateSubscriber()\n#83 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestCase.php(908): ReflectionMethod->invokeArgs(Object(CachetHQ\\Tests\\Cachet\\Api\\SubscriberTest), Array)\n#84 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestCase.php(768): PHPUnit_Framework_TestCase->runTest()\n#85 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestResult.php(612): PHPUnit_Framework_TestCase->runBare()\n#86 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestCase.php(724): PHPUnit_Framework_TestResult->run(Object(CachetHQ\\Tests\\Cachet\\Api\\SubscriberTest))\n#87 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestSuite.php(747): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))\n#88 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestSuite.php(747): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult))\n#89 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/TextUI/TestRunner.php(440): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult))\n#90 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/TextUI/Command.php(149): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)\n#91 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/TextUI/Command.php(100): PHPUnit_TextUI_Command->run(Array, true)\n#92 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/phpunit(47): PHPUnit_TextUI_Command::main()\n#93 {main} {\"identification\":{\"id\":\"ea24b7eb-bf29-48e5-930f-29e8335e4fab\"}} \n```\n", "number": 13331, "review_comments": [], "title": "[5.2] Revert broken changes" }
{ "commits": [ { "message": "Revert broken changes" }, { "message": "Applied fixes from StyleCI" }, { "message": "Merge pull request #13330 from laravel/analysis-q2QKAl\n\nApplied fixes from StyleCI" } ], "files": [ { "diff": "@@ -4,7 +4,6 @@\n \n use Mockery;\n use Exception;\n-use Illuminate\\Database\\Eloquent\\Model;\n \n trait MocksApplicationServices\n {\n@@ -89,16 +88,8 @@ protected function withoutEvents()\n $this->firedEvents[] = $called;\n });\n \n- $mock->shouldReceive('until')->andReturnUsing(function ($called) {\n- $this->firedEvents[] = $called;\n-\n- return true;\n- });\n-\n $this->app->instance('events', $mock);\n \n- Model::setEventDispatcher($mock);\n-\n return $this;\n }\n ", "filename": "src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php", "status": "modified" }, { "diff": "@@ -4,7 +4,6 @@\n \n use Mockery;\n use PHPUnit_Framework_TestCase;\n-use Illuminate\\Database\\Eloquent\\Model;\n \n abstract class TestCase extends PHPUnit_Framework_TestCase\n {\n@@ -84,8 +83,6 @@ protected function refreshApplication()\n putenv('APP_ENV=testing');\n \n $this->app = $this->createApplication();\n-\n- Model::setEventDispatcher($this->app['events']);\n }\n \n /**", "filename": "src/Illuminate/Foundation/Testing/TestCase.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": "This broke Cachet, among other things.\n\n```\n[2016-04-27 09:09:31] testing.ERROR: BadMethodCallException: Method Mockery_0_Illuminate_Contracts_Events_Dispatcher::listen() does not exist on this mock object in /media/sf_GitHub/Cachet/Cachet/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php(16) : eval()'d code:709\nStack trace:\n#0 /media/sf_GitHub/Cachet/Cachet/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php(16) : eval()'d code(761): Mockery_0_Illuminate_Contracts_Events_Dispatcher->_mockery_handleMethodCall('listen', Array)\n#1 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1286): Mockery_0_Illuminate_Contracts_Events_Dispatcher->listen('eloquent.saving...', 'AltThree\\\\Valida...', 0)\n#2 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(423): Illuminate\\Database\\Eloquent\\Model::registerModelEvent('saving', 'AltThree\\\\Valida...', 0)\n#3 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/validator/src/ValidatingTrait.php(30): Illuminate\\Database\\Eloquent\\Model::observe(Object(AltThree\\Validator\\ValidatingObserver))\n#4 [internal function]: CachetHQ\\Cachet\\Models\\Subscriber::bootValidatingTrait()\n#5 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(323): forward_static_call(Array)\n#6 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(309): Illuminate\\Database\\Eloquent\\Model::bootTraits()\n#7 /media/sf_GitHub/Cachet/Cachet/app/Models/Subscriber.php(63): Illuminate\\Database\\Eloquent\\Model::boot()\n#8 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(296): CachetHQ\\Cachet\\Models\\Subscriber::boot()\n#9 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(277): Illuminate\\Database\\Eloquent\\Model->bootIfNotBooted()\n#10 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(3505): Illuminate\\Database\\Eloquent\\Model->__construct()\n#11 /media/sf_GitHub/Cachet/Cachet/app/Bus/Handlers/Commands/Subscriber/SubscribeSubscriberCommandHandler.php(40): Illuminate\\Database\\Eloquent\\Model::__callStatic('where', Array)\n#12 [internal function]: CachetHQ\\Cachet\\Bus\\Handlers\\Commands\\Subscriber\\SubscribeSubscriberCommandHandler->handle(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#13 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/bus/src/Dispatcher.php(225): call_user_func(Array, Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#14 [internal function]: AltThree\\Bus\\Dispatcher->AltThree\\Bus\\{closure}(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#15 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(150): call_user_func(Object(Closure), Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#16 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#17 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#18 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/bus/src/Dispatcher.php(226): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#19 /media/sf_GitHub/Cachet/Cachet/vendor/alt-three/bus/src/Dispatcher.php(201): AltThree\\Bus\\Dispatcher->dispatchNow(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand), NULL)\n#20 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(323): AltThree\\Bus\\Dispatcher->dispatch(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#21 /media/sf_GitHub/Cachet/Cachet/app/Http/Controllers/Api/SubscriberController.php(46): dispatch(Object(CachetHQ\\Cachet\\Bus\\Commands\\Subscriber\\SubscribeSubscriberCommand))\n#22 [internal function]: CachetHQ\\Cachet\\Http\\Controllers\\Api\\SubscriberController->postSubscribers()\n#23 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(80): call_user_func_array(Array, Array)\n#24 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(146): Illuminate\\Routing\\Controller->callAction('postSubscribers', Array)\n#25 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(94): Illuminate\\Routing\\ControllerDispatcher->call(Object(CachetHQ\\Cachet\\Http\\Controllers\\Api\\SubscriberController), Object(Illuminate\\Routing\\Route), 'postSubscribers')\n#26 [internal function]: Illuminate\\Routing\\ControllerDispatcher->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#27 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#28 [internal function]: Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#29 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#30 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(96): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#31 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(54): Illuminate\\Routing\\ControllerDispatcher->callWithinStack(Object(CachetHQ\\Cachet\\Http\\Controllers\\Api\\SubscriberController), Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request), 'postSubscribers')\n#32 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Route.php(174): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request), 'CachetHQ\\\\Cachet...', 'postSubscribers')\n#33 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Route.php(140): Illuminate\\Routing\\Route->runController(Object(Illuminate\\Http\\Request))\n#34 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(724): Illuminate\\Routing\\Route->run(Object(Illuminate\\Http\\Request))\n#35 [internal function]: Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#36 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#37 /media/sf_GitHub/Cachet/Cachet/app/Http/Middleware/ApiAuthentication.php(67): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#38 [internal function]: CachetHQ\\Cachet\\Http\\Middleware\\ApiAuthentication->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'true')\n#39 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#40 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#41 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#42 /media/sf_GitHub/Cachet/Cachet/app/Http/Middleware/Timezone.php(53): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#43 [internal function]: CachetHQ\\Cachet\\Http\\Middleware\\Timezone->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#44 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#45 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#46 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#47 /media/sf_GitHub/Cachet/Cachet/app/Http/Middleware/Acceptable.php(35): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#48 [internal function]: CachetHQ\\Cachet\\Http\\Middleware\\Acceptable->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#49 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#50 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#51 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#52 /media/sf_GitHub/Cachet/Cachet/vendor/barryvdh/laravel-cors/src/HandleCors.php(34): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#53 [internal function]: Barryvdh\\Cors\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#54 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#55 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#56 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#57 [internal function]: Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#58 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#59 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(726): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#60 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(699): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))\n#61 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Router.php(675): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))\n#62 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(246): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))\n#63 [internal function]: Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))\n#64 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(52): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#65 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(44): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#66 [internal function]: Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#67 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#68 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#69 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#70 /media/sf_GitHub/Cachet/Cachet/vendor/fideloper/proxy/src/TrustProxies.php(46): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#71 [internal function]: Fideloper\\Proxy\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#72 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(136): call_user_func_array(Array, Array)\n#73 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#74 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(32): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#75 [internal function]: Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))\n#76 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#77 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(132): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#78 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(99): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\n#79 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(506): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\n#80 /media/sf_GitHub/Cachet/Cachet/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(126): Illuminate\\Foundation\\Testing\\TestCase->call('POST', '/api/v1/subscri...', Array, Array, Array, Array)\n#81 /media/sf_GitHub/Cachet/Cachet/tests/Api/SubscriberTest.php(47): Illuminate\\Foundation\\Testing\\TestCase->post('/api/v1/subscri...', Array)\n#82 [internal function]: CachetHQ\\Tests\\Cachet\\Api\\SubscriberTest->testCreateSubscriber()\n#83 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestCase.php(908): ReflectionMethod->invokeArgs(Object(CachetHQ\\Tests\\Cachet\\Api\\SubscriberTest), Array)\n#84 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestCase.php(768): PHPUnit_Framework_TestCase->runTest()\n#85 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestResult.php(612): PHPUnit_Framework_TestCase->runBare()\n#86 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestCase.php(724): PHPUnit_Framework_TestResult->run(Object(CachetHQ\\Tests\\Cachet\\Api\\SubscriberTest))\n#87 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestSuite.php(747): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))\n#88 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/Framework/TestSuite.php(747): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult))\n#89 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/TextUI/TestRunner.php(440): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult))\n#90 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/TextUI/Command.php(149): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)\n#91 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/src/TextUI/Command.php(100): PHPUnit_TextUI_Command->run(Array, true)\n#92 /media/sf_GitHub/Cachet/Cachet/vendor/phpunit/phpunit/phpunit(47): PHPUnit_TextUI_Command::main()\n#93 {main} {\"identification\":{\"id\":\"ea24b7eb-bf29-48e5-930f-29e8335e4fab\"}} \n```\n", "number": 13331, "review_comments": [], "title": "[5.2] Revert broken changes" }
{ "commits": [ { "message": "Revert broken changes" }, { "message": "Applied fixes from StyleCI" }, { "message": "Merge pull request #13330 from laravel/analysis-q2QKAl\n\nApplied fixes from StyleCI" } ], "files": [ { "diff": "@@ -4,7 +4,6 @@\n \n use Mockery;\n use Exception;\n-use Illuminate\\Database\\Eloquent\\Model;\n \n trait MocksApplicationServices\n {\n@@ -89,16 +88,8 @@ protected function withoutEvents()\n $this->firedEvents[] = $called;\n });\n \n- $mock->shouldReceive('until')->andReturnUsing(function ($called) {\n- $this->firedEvents[] = $called;\n-\n- return true;\n- });\n-\n $this->app->instance('events', $mock);\n \n- Model::setEventDispatcher($mock);\n-\n return $this;\n }\n ", "filename": "src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php", "status": "modified" }, { "diff": "@@ -4,7 +4,6 @@\n \n use Mockery;\n use PHPUnit_Framework_TestCase;\n-use Illuminate\\Database\\Eloquent\\Model;\n \n abstract class TestCase extends PHPUnit_Framework_TestCase\n {\n@@ -84,8 +83,6 @@ protected function refreshApplication()\n putenv('APP_ENV=testing');\n \n $this->app = $this->createApplication();\n-\n- Model::setEventDispatcher($this->app['events']);\n }\n \n /**", "filename": "src/Illuminate/Foundation/Testing/TestCase.php", "status": "modified" } ] }
{ "body": "`@parent` is not escaping when the data comes from the MySQL but it get's compiled and executed. This can be a security issue.\n\nI have created a sample repo to demonstrate the issue https://github.com/abhimanyu003/laravelSample\n- Clone the repo and run `composer install`\n- Run `php artisan migrate` \n- Run `php aritsan db:seed` ( Which will create a user with name `@parent` )\n- Visit home page\n\nYou will see a notice `Master sidebar only display if @\\parent tag is executed.` which means that `@parent` tag is executed and not escaped out when it is getting data from MySQL.\n\nI'm just fetching the first user from MySQL in `routes.php` file https://github.com/abhimanyu003/laravelSample/blob/master/app/Http/routes.php then that data passed to view `child` ( Location: `resouces/views/child.blade.php` )\n\nYou can see at line no 4. `{{ $user->name }}` https://github.com/abhimanyu003/laravelSample/blob/master/resources/views/child.blade.php#L4 this is the place where blade supposed to escape `@parent` tag but it is not rather it is excution it and appending it `master.blade.php`\n\n**Expected Result:**\n\n```\n @parent\n <p>This is appended to the master sidebar.</p>\n```\n\n**Current Result:**\n\n```\nMaster sidebar only display if @\\parent tag is executed.\nThis is appended to the master sidebar.\n```\n\nPS: `@parent` is the also the name of user in database.\n\nThanks\n", "comments": [ { "body": "You should NEVER execute php code from user input. That's what you're doing here. Looking at your code there, I don't see why you have an issue though, because you're just echoing a value in php.\n", "created_at": "2015-08-28T12:48:08Z" }, { "body": "How come `@parent` is php code ? It a blade syntax.\n", "created_at": "2015-08-28T12:49:03Z" }, { "body": "Because it gets compiled by blade into php, then the file is \"required\".\n", "created_at": "2015-08-28T12:49:21Z" }, { "body": "From your code sample there, that's not happening though.\n", "created_at": "2015-08-28T12:49:42Z" }, { "body": "That sort of thing would only happen if you're actually building files from user input.\n", "created_at": "2015-08-28T12:49:58Z" }, { "body": "@GrahamCampbell I'm doing nothing special you can see, but somehow `@parent` is executing. Let's say if there is some textarea on my website and i'm displaying in the same way. It can break the current website.\n\nSo can you please tell how to avoid so that `@parent` will not get executed.\n", "created_at": "2015-08-28T12:53:04Z" }, { "body": "> I'm doing nothing special you can see, but somehow @parent is executing.\n\nThat's impossible from that code sample.\n", "created_at": "2015-08-28T13:05:28Z" }, { "body": "We don't even have a way to execute `@parent`. It has to be compiled first then the result must be required.\n", "created_at": "2015-08-28T13:05:55Z" }, { "body": "So sorry. Just read our code again. It seems that part isn't done at the \"compile\" level, but is done after.\n", "created_at": "2015-08-28T13:08:44Z" }, { "body": "You have indeed uncovered a security issue. I'm going to contact Taylor.\n", "created_at": "2015-08-28T13:09:14Z" }, { "body": "@GrahamCampbell many many thanks for reopening the issue. :)\n", "created_at": "2015-08-28T13:09:40Z" }, { "body": "Not at all, security is very important. Sorry I took a while to realise what was going on here.\n", "created_at": "2015-08-28T13:11:36Z" }, { "body": "In future, could you please contact Taylor directly regarding security issues, because now this is public knowledge to anyone wanting to target Laravel apps.\n", "created_at": "2015-08-28T13:12:26Z" }, { "body": "IMO, the issue here is not so much the escaping, but more, that there's an inherit design floor here that allows this to happen in the first place.\n", "created_at": "2015-08-28T13:13:15Z" }, { "body": "Ok, so sorry for not contacting Taylor directly and I will make sure of this next time. I will wait for some update.\n", "created_at": "2015-08-28T13:16:35Z" }, { "body": "I reported this exact issue months ago - and it got closed to due inactivity: https://github.com/laravel/framework/issues/7888\n", "created_at": "2015-08-31T14:11:17Z" }, { "body": "@TheShiftExchange this so strange, I'm giving try to few things but i'm not sure what causing this. I can't say much but this need to resolved quickly.\n", "created_at": "2015-08-31T17:19:57Z" }, { "body": "Is anyone able to look into this? The previous fix we had was very good, but it had to be reverted due to a bug.\n", "created_at": "2015-12-25T01:48:27Z" }, { "body": "I looked into this and put something together, just need some tests and i will send a PR. @GrahamCampbell should I send a PR to 5.1 or 5.2 branch ? Thanks\n", "created_at": "2015-12-27T13:02:30Z" }, { "body": "Sorry to disturb, but can somebody fix it for 5.3 at least? I only know how to remove the feature, if you like me to submit a PR!? I am sending this just because 5.3 is coming soon and I think it is better not to have this bug there, than be backward compatible.\n", "created_at": "2016-06-22T10:05:20Z" }, { "body": "The PR had to be reverted not because of BC, but because it didn't actually work properly. We'd definitely accept a PR that does work. :)\n", "created_at": "2016-06-22T10:08:14Z" }, { "body": "Yes it should be fixed, not removed.\n", "created_at": "2016-06-22T12:17:03Z" }, { "body": "@taylorotwell can I request re-open for community to help ?\n", "created_at": "2016-06-22T12:27:36Z" }, { "body": "For now, since we don't use the @parent feature of blade, we've overwritten the method and commented the str_replace line.\n", "created_at": "2016-07-12T05:50:07Z" }, { "body": "this was fixed in https://github.com/laravel/framework/pull/16033\n", "created_at": "2016-10-24T18:52:19Z" } ], "number": 10068, "title": "[5.1] [5.3] @parent tag is not escaping" }
{ "body": "Added:\n\nextends, extends with parent, `@parent` mention in #10068 (if it is fixed, the test for that will show error)\n\nFixes: \n\nfix of use statement `@endpush`, refine the factory\n", "number": 13192, "review_comments": [], "title": "[5.2] Add more test on View" }
{ "commits": [ { "message": "Add more test on View" } ], "files": [ { "diff": "@@ -2,127 +2,202 @@\n \n use Mockery as m;\n use Illuminate\\View\\Factory;\n+use Illuminate\\Filesystem\\Filesystem;\n+use Illuminate\\View\\Engines\\CompilerEngine;\n use Illuminate\\View\\Compilers\\BladeCompiler;\n \n class ViewFlowTest extends PHPUnit_Framework_TestCase\n {\n+ public function setUp()\n+ {\n+ parent::setUp();\n+\n+ $files = new Filesystem;\n+ $this->tempDir = __DIR__.'/tmp';\n+\n+ if (!$files->exists($this->tempDir)) {\n+ $files->makeDirectory($this->tempDir);\n+ }\n+ }\n+\n public function tearDown()\n {\n+ $files = new Filesystem;\n+ $files->deleteDirectory($this->tempDir);\n+\n m::close();\n }\n \n public function testPushWithExtend()\n {\n- $files = new Illuminate\\Filesystem\\Filesystem;\n-\n+ $files = new Filesystem;\n $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n \n- $files->put(__DIR__.'/fixtures/child.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/child.php', $compiler->compileString('\n @extends(\"layout\")\n \n @push(\"content\")\n World\n @endpush'));\n- $files->put(__DIR__.'/fixtures/layout.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/layout.php', $compiler->compileString('\n @push(\"content\")\n Hello\n @endpush\n @stack(\"content\")'));\n \n- $engine = new Illuminate\\View\\Engines\\CompilerEngine(m::mock('Illuminate\\View\\Compilers\\CompilerInterface'));\n- $engine->getCompiler()->shouldReceive('getCompiledPath')->andReturnUsing(function ($path) { return $path; });\n- $engine->getCompiler()->shouldReceive('isExpired')->times(2)->andReturn(false);\n-\n- $factory = $this->getFactory();\n- $factory->getEngineResolver()->shouldReceive('resolve')->times(2)->andReturn($engine);\n- $factory->getFinder()->shouldReceive('find')->once()->with('child')->andReturn(__DIR__.'/fixtures/child.php');\n- $factory->getFinder()->shouldReceive('find')->once()->with('layout')->andReturn(__DIR__.'/fixtures/layout.php');\n- $factory->getDispatcher()->shouldReceive('fire')->times(4);\n-\n+ $factory = $this->prepareCommonFactory();\n $this->assertEquals(\"Hello\\nWorld\\n\", $factory->make('child')->render());\n-\n- $files->delete(__DIR__.'/fixtures/layout.php');\n- $files->delete(__DIR__.'/fixtures/child.php');\n }\n \n public function testPushWithMultipleExtends()\n {\n- $files = new Illuminate\\Filesystem\\Filesystem;\n-\n+ $files = new Filesystem;\n $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n \n- $files->put(__DIR__.'/fixtures/a.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/a.php', $compiler->compileString('\n a\n @stack(\"me\")'));\n \n- $files->put(__DIR__.'/fixtures/b.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/b.php', $compiler->compileString('\n @extends(\"a\")\n @push(\"me\")\n b\n-@endpush(\"me\")'));\n+@endpush'));\n \n- $files->put(__DIR__.'/fixtures/c.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/c.php', $compiler->compileString('\n @extends(\"b\")\n @push(\"me\")\n c\n-@endpush(\"me\")'));\n-\n- $engine = new Illuminate\\View\\Engines\\CompilerEngine(m::mock('Illuminate\\View\\Compilers\\CompilerInterface'));\n- $engine->getCompiler()->shouldReceive('getCompiledPath')->andReturnUsing(function ($path) { return $path; });\n- $engine->getCompiler()->shouldReceive('isExpired')->andReturn(false);\n-\n- $factory = $this->getFactory();\n- $factory->getEngineResolver()->shouldReceive('resolve')->andReturn($engine);\n- $factory->getFinder()->shouldReceive('find')->andReturnUsing(function ($path) {\n- return __DIR__.'/fixtures/'.$path.'.php';\n- });\n- $factory->getDispatcher()->shouldReceive('fire');\n+@endpush'));\n \n+ $factory = $this->prepareCommonFactory();\n $this->assertEquals(\"a\\nb\\nc\\n\", $factory->make('c')->render());\n-\n- $files->delete(__DIR__.'/fixtures/a.php');\n- $files->delete(__DIR__.'/fixtures/b.php');\n- $files->delete(__DIR__.'/fixtures/c.php');\n }\n \n public function testPushWithInputAndExtend()\n {\n- $files = new Illuminate\\Filesystem\\Filesystem;\n-\n+ $files = new Filesystem;\n $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n \n- $files->put(__DIR__.'/fixtures/aa.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/aa.php', $compiler->compileString('\n a\n @stack(\"me\")'));\n \n- $files->put(__DIR__.'/fixtures/bb.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/bb.php', $compiler->compileString('\n @push(\"me\")\n b\n-@endpush(\"me\")'));\n+@endpush'));\n \n- $files->put(__DIR__.'/fixtures/cc.php', $compiler->compileString('\n+ $files->put($this->tempDir.'/cc.php', $compiler->compileString('\n @extends(\"aa\")\n @include(\"bb\")\n @push(\"me\")\n c\n-@endpush(\"me\")'));\n+@endpush'));\n+\n+ $factory = $this->prepareCommonFactory();\n+ $this->assertEquals(\"a\\nc\\nb\\n\", $factory->make('cc')->render());\n+ }\n+\n+ public function testExtends()\n+ {\n+ $files = new Filesystem;\n+ $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n+\n+ $files->put($this->tempDir.'/extends-a.php', $compiler->compileString('\n+yield:\n+@yield(\"me\")'));\n+\n+ $files->put($this->tempDir.'/extends-b.php', $compiler->compileString('\n+@extends(\"extends-a\")\n+@section(\"me\")\n+b\n+@endsection'));\n+\n+ $files->put($this->tempDir.'/extends-c.php', $compiler->compileString('\n+@extends(\"extends-b\")\n+@section(\"me\")\n+c\n+@endsection'));\n+\n+ $factory = $this->prepareCommonFactory();\n+ $this->assertEquals(\"yield:\\nb\\n\", $factory->make('extends-b')->render());\n+ $this->assertEquals(\"yield:\\nc\\n\", $factory->make('extends-c')->render());\n+ }\n \n- $engine = new Illuminate\\View\\Engines\\CompilerEngine(m::mock('Illuminate\\View\\Compilers\\CompilerInterface'));\n- $engine->getCompiler()->shouldReceive('getCompiledPath')->andReturnUsing(function ($path) { return $path; });\n+ public function testExtendsWithParent()\n+ {\n+ $files = new Filesystem;\n+ $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n+\n+ $files->put($this->tempDir.'/extends-layout.php', $compiler->compileString('\n+yield:\n+@yield(\"me\")'));\n+\n+ $files->put($this->tempDir.'/extends-dad.php', $compiler->compileString('\n+@extends(\"extends-layout\")\n+@section(\"me\")\n+dad\n+@endsection'));\n+\n+ $files->put($this->tempDir.'/extends-child.php', $compiler->compileString('\n+@extends(\"extends-dad\")\n+@section(\"me\")\n+@parent\n+child\n+@endsection'));\n+\n+ $factory = $this->prepareCommonFactory();\n+ $this->assertEquals(\"yield:\\ndad\\n\\nchild\\n\", $factory->make('extends-child')->render());\n+ }\n+\n+ public function testExtendsWithVariable()\n+ {\n+ $files = new Filesystem;\n+ $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n+\n+ $files->put($this->tempDir.'/extends-variable-layout.php', $compiler->compileString('\n+yield:\n+@yield(\"me\")'));\n+\n+ $files->put($this->tempDir.'/extends-variable-dad.php', $compiler->compileString('\n+@extends(\"extends-variable-layout\")\n+@section(\"me\")\n+dad\n+@endsection'));\n+\n+ $files->put($this->tempDir.'/extends-variable-child-a.php', $compiler->compileString('\n+@extends(\"extends-variable-dad\")\n+@section(\"me\")\n+{{ $title }}\n+@endsection'));\n+\n+ $files->put($this->tempDir.'/extends-variable-child-b.php', $compiler->compileString('\n+@extends(\"extends-variable-dad\")\n+@section(\"me\")\n+{{ $title }}\n+@endsection'));\n+\n+ $factory = $this->prepareCommonFactory();\n+ $this->assertEquals(\"yield:\\ntitle\\n\", $factory->make('extends-variable-child-a', ['title' => 'title'])->render());\n+ $this->assertEquals(\"yield:\\ndad\\n\\n\", $factory->make('extends-variable-child-b', ['title' => '@parent'])->render());\n+ }\n+\n+ protected function prepareCommonFactory()\n+ {\n+ $engine = new CompilerEngine(m::mock('Illuminate\\View\\Compilers\\CompilerInterface'));\n+ $engine->getCompiler()->shouldReceive('getCompiledPath')\n+ ->andReturnUsing(function ($path) { return $path; });\n $engine->getCompiler()->shouldReceive('isExpired')->andReturn(false);\n \n $factory = $this->getFactory();\n $factory->getEngineResolver()->shouldReceive('resolve')->andReturn($engine);\n $factory->getFinder()->shouldReceive('find')->andReturnUsing(function ($path) {\n- return __DIR__.'/fixtures/'.$path.'.php';\n+ return $this->tempDir.'/'.$path.'.php';\n });\n $factory->getDispatcher()->shouldReceive('fire');\n \n- $this->assertEquals(\"a\\nc\\nb\\n\", $factory->make('cc')->render());\n-\n- $files->delete(__DIR__.'/fixtures/aa.php');\n- $files->delete(__DIR__.'/fixtures/bb.php');\n- $files->delete(__DIR__.'/fixtures/cc.php');\n+ return $factory;\n }\n \n protected function getFactory()", "filename": "tests/View/ViewFlowTest.php", "status": "modified" } ] }
{ "body": "Without this, MySQL throws an error e.g. when using reserved names as field names.\n\nAt least in theory, this should also reduce attack surface for SQL injection! _This weakness may apply to other database grammars (Postgres?), not tested._\n\nExample behavior without this fix:\n\n```\n~/Code/backend$ php artisan tinker\n\nPsy Shell v0.7.2 (PHP 7.0.3-13+deb.sury.org~trusty+1 — cli) by Justin Hileman\n\n>>> App\\User::where('values->test', \"1\")->get()\n\nIlluminate\\Database\\QueryException with message 'SQLSTATE[42000]: Syntax\nerror or access violation: 1064 You have an error in your SQL syntax; check the\nmanual that corresponds to your MySQL server version for the right syntax to\nuse near '->\"$.test\" = ?' at line 1 (SQL: select * from `users` where\nvalues->\"$.test\" = 1)'\n```\n", "comments": [ { "body": "Just noticed the failing tests, fixing it...\n", "created_at": "2016-04-01T10:47:49Z" }, { "body": "@themsaid thoughts?\n", "created_at": "2016-04-01T13:38:21Z" }, { "body": "Yes correct, an error will be thrown if the field name is not wrapped for preserved keys.\n\nselect `order`->\"$.en\" from products LIMIt 1 // OK\n`select order->\"$.en\" from products LIMIt 1` // Syntax error\n", "created_at": "2016-04-01T14:17:55Z" }, { "body": "So you're saying this should be merged @themsaid ?\n", "created_at": "2016-04-01T14:24:52Z" }, { "body": "I think this can be simplified:\n\n```\nprotected function wrapJsonSelector($value)\n {\n $path = explode('->', $value);\n\n return '`'.array_shift($path).'`->'.'\"$.'.implode('.', $path).'\"';\n }\n```\n\nNo need to call `wrapValue()` again.\n", "created_at": "2016-04-01T14:33:57Z" }, { "body": "Wrapping the value surely isn't sufficient. We'd need to use prepared statements?\n", "created_at": "2016-04-01T14:35:43Z" }, { "body": "I'm not at my disk now, I may look into that in detail later today.\n", "created_at": "2016-04-01T14:43:15Z" }, { "body": "@themsaid sure, proposed simplification works for now, but each future improvement to wrapValue() - which may be security-related, for example when applying/changing escaping - must then be incorporated here.\n\n@GrahamCampbell As this PR is about wrapping column names: doesn't the mechanism of prepared statements apply to values only? Are prepared statements also applied to column names? \n", "created_at": "2016-04-01T15:08:46Z" }, { "body": "We wouldn't use prepared statements for column names @GrahamCampbell \n", "created_at": "2016-04-01T18:16:33Z" }, { "body": "I don't see how this is related to SQL injection at all in any way shape or form.\n", "created_at": "2016-04-01T18:16:56Z" }, { "body": "It's only to wrap column names to be safe from conflicting with reserved keywords.\n", "created_at": "2016-04-01T18:18:36Z" }, { "body": "@taylorotwell Before this PR, code like\n\n``` php\nApp\\User::where($request->get('searchfield').'->selector', 'value')->delete()\n```\n\nwas vulnerable to SQL injection as it circumvented `wrapValue()`, which wraps everything in backticks and escapes any contained backticks.\n\nI know such code is a dangerous idea but now it's correctly wrapped (escaped). There's still `whereRaw` for anyone intentionally writing dangerous code. :smiling_imp: \n\nExamples:\n\nQuery as intended: `?searchfield=foo`\n\n``` mysql\ndelete from `users` where foo->selector=value\n```\n\nMalicious query: `?searchfield=%3Dfoo+or+foo`\n\nSQL injection without fix:\n\n``` mysql\ndelete from `users` where foo=foo or foo->selector=value\n```\n\nWith fix a regular SQL error should be triggered:\n\n``` mysql\ndelete from `users` where `foo=foo or foo`->selector=value\n```\n\nIn addition, the attacker cannot break out of the backticks because `wrapValue()` escapes any contained backticks.\n\nIf you think I'm correct then similar implementations for other grammars, e.g. PostgreSQL, could be vulnerable aswell and should be checked (I don't know PostgreSQL well enough)\n\nNote: I'm currently working on additionally wrapping/escaping the JSON path for the same reason.\n", "created_at": "2016-04-01T21:36:46Z" } ], "number": 12964, "title": "[5.2] Wrap field name in MySQL JSON path expressions" }
{ "body": "Followup to PR #12964\n\nIncludes two tests (one related to #12964) to verify correct wrapping/escaping.\n", "number": 12992, "review_comments": [], "title": "[5.2] Wrap and escape MySQL JSON path" }
{ "commits": [ { "message": "wrap and escape json path" }, { "message": "add test for wrapping and escaping of field names in json expressions" } ], "files": [ { "diff": "@@ -156,6 +156,12 @@ protected function wrapJsonSelector($value)\n \n $field = $this->wrapValue(array_shift($path));\n \n- return $field.'->'.'\"$.'.implode('.', $path).'\"';\n+ $path = '$.'.implode('.', $path);\n+\n+ $path = str_replace('\\\\', '\\\\\\\\', $path);\n+ $path = str_replace('\"', '\\\\\"', $path);\n+ $path = '\"'.$path.'\"';\n+\n+ return $field.'->'.$path;\n }\n }", "filename": "src/Illuminate/Database/Query/Grammars/MySqlGrammar.php", "status": "modified" }, { "diff": "@@ -1213,6 +1213,14 @@ public function testMySqlWrappingJson()\n $builder = $this->getMySqlBuilder();\n $builder->select('*')->from('users')->where('items->price->in_usd', '=', 1)->where('items->age', '=', 2);\n $this->assertEquals('select * from `users` where `items`->\"$.price.in_usd\" = ? and `items`->\"$.age\" = ?', $builder->toSql());\n+\n+ $builder = $this->getMySqlBuilder();\n+ $builder->select('*')->from('users')->where('field`safe`from`sql`injection->price', '=', 1);\n+ $this->assertEquals('select * from `users` where `field``safe``from``sql``injection`->\"$.price\" = ?', $builder->toSql());\n+\n+ $builder = $this->getMySqlBuilder();\n+ $builder->select('*')->from('users')->where('items->value_safe_from_sql_injection_\\'\"\\\\', '=', 1);\n+ $this->assertEquals('select * from `users` where `items`->\"$.value_safe_from_sql_injection_\\'\\\\\"\\\\\\\\\" = ?', $builder->toSql());\n }\n \n public function testPostgresWrappingJson()", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "Hello.\n\nI have next route:\n\n```\nRoute::get('/calendar/{user}/{department?}/{year?}/{month?}/{team?}',[ 'as' => 'schedule.show', 'uses' => 'ScheduleController@show' ]);\n```\n\nAnd controller method:\n\n```\npublic function show(Request $request, User $user, Department $department = null, $year = null, $month = null, Team $team = null)\n{\n...\n}\n```\n\nWhen I open url localhost/calendar/1/5/2016/02/9 or localhost/calendar/1/5/2016/02 (with team and without) - eversyng is ok, but when I try to open localhost/calendar/1 (without all optional params) - I got empty Team class in variable $year. Example:\n\n```\nlocalhost/calendar/1/5/2016/02/9:\n$user -> Object of User with id 1\n$department -> Object of Department with id 5\n$year -> string 2016\n$month -> string 02\n$team -> Object of Team with id 9\n\n---\n\nlocalhost/calendar/1/5/2016/02:\n$user -> Object of User with id 1\n$department -> Object of Department with id 5\n$year -> string 2016\n$month -> string 02\n$team -> Object of empty (not exists) Team\n\n---\n\nlocalhost/calendar/1:\n$user -> Object of User with id 1\n$department -> Object of empty Department\n$year -> Object of empty Team\n$month -> null\n$team -> null\n```\n\nI have found just one sollution - remove class name \"Team\" from method params:\n\n```\npublic function show(Request $request, User $user, Department $department = null, $year = null, $month = null, $team = null)\n{\n...\n}\n```\n", "comments": [ { "body": "Looks like there is a shift because of the unhinted `$year` and `$month` preceding the hinted `$team`.\n", "created_at": "2016-03-05T00:26:16Z" }, { "body": "Have you tried moving `$team` var around?\n\n```\npublic function show(Request $request, User $user, Department $department = null, Team $team = null, $year = null, $month = null)\n{\n...\n}\n```\n", "created_at": "2016-03-07T11:37:42Z" }, { "body": "> Have you tried moving $team var around?\n\nYes, I have tried. In this case links without team id works fine, but such links as `localhost/calendar/1/5/2016/02/9` throw next error:\n\n```\nType error: Argument 4 passed to App\\Http\\Controllers\\ScheduleController::show() must be an instance of App\\Team, string given\n\n1. in ScheduleController.php line 107\n2. at ScheduleController->show(object(Request), object(User), object(Department), '2016', '3', object(Team))\n3. at call_user_func_array(array(object(ScheduleController), 'show'), array(object(Request), 'user' => object(User), 'department' => object(Department), 'year' => '2016', 'month' => '3', 'team' => object(Team))) in Controller.php line 78\n...\n```\n", "created_at": "2016-03-09T07:45:37Z" }, { "body": "@GrahamCampbell Can you look at this? I think it is explained in #12959 as a bug\n", "created_at": "2016-04-01T15:10:48Z" }, { "body": "Sorry, I don't have time to personally look into every bug report.\n", "created_at": "2016-04-01T15:23:37Z" }, { "body": "@GrahamCampbell No problem, thank you\n", "created_at": "2016-04-01T15:25:48Z" }, { "body": "Closing since we now have a PR.", "created_at": "2017-01-01T15:46:44Z" } ], "number": 12630, "title": "[5.2] Controller method with optional params issue" }
{ "body": "As you may notice, commit 143ba0e and then doesn't pass the test, the one of the results are\n\n```\n$router->get('hello/{foo}/{year?}/{bar?}', function (User $foo, $year = null, Team $bar = null) {\n // $foo is instance of User\n // $year should be null, but instance of Team\n // $bar should be instance of Team, but null\n return 'hello';\n});\n$router->dispatch(Request::create('hello/taylor', 'GET'))->getContent();\n```\n\nIt seems comes to do with `Routing\\RouteDependencyResolverTrait@resolveClassMethodDependencies`, which will mess up the $parameter to call action.\n\nRef: you may see #12887 and #12886 how test works\nRef2: issue #12630\n\n// Updated\n", "number": 12888, "review_comments": [ { "body": "`$parameters` are **associative array**, which will produce unpredictable behavior when apply to `call_user_func_array`. So I use the numerical index here.\n", "created_at": "2016-03-29T04:43:29Z" }, { "body": "The problem here is that if there are multiple same `$class`, the `$value` instance of `$class` in `$parameters` may be short of. (example: requiring three User class, but only provide two instance, so we mush make the third one)\n", "created_at": "2016-03-29T04:53:59Z" } ], "title": "[5.2] Fix implicit model binding bugs" }
{ "commits": [ { "message": "Test with multiple models and parameters" }, { "message": "Add a fail test, weird behavior" }, { "message": "More test" }, { "message": "rewrite resolveMethodDependencies" } ], "files": [ { "diff": "@@ -3,8 +3,6 @@\n namespace Illuminate\\Routing;\n \n use ReflectionMethod;\n-use ReflectionParameter;\n-use Illuminate\\Support\\Arr;\n use ReflectionFunctionAbstract;\n \n trait RouteDependencyResolverTrait\n@@ -52,54 +50,31 @@ protected function resolveClassMethodDependencies(array $parameters, $instance,\n public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector)\n {\n $originalParameters = $parameters;\n+ $parameters = array_values($parameters);\n \n foreach ($reflector->getParameters() as $key => $parameter) {\n- $instance = $this->transformDependency(\n- $parameter, $parameters, $originalParameters\n- );\n-\n- if (! is_null($instance)) {\n- $this->spliceIntoParameters($parameters, $key, $instance);\n+ $class = $parameter->getClass();\n+ if ($class) {\n+ if (array_key_exists($key, $parameters) && $parameters[$key] instanceof $class->name) {\n+ continue;\n+ } else {\n+ $instance = $this->container->make($class->name);\n+ if (array_key_exists($key, $parameters)) {\n+ $this->spliceIntoParameters($parameters, $key, $instance);\n+ } else {\n+ $parameters[$key] = $instance;\n+ }\n+ }\n+ } else {\n+ if (! array_key_exists($key, $parameters)) {\n+ $parameters[$key] = $parameter->getDefaultValue();\n+ }\n }\n }\n \n return $parameters;\n }\n \n- /**\n- * Attempt to transform the given parameter into a class instance.\n- *\n- * @param \\ReflectionParameter $parameter\n- * @param array $parameters\n- * @param array $originalParameters\n- * @return mixed\n- */\n- protected function transformDependency(ReflectionParameter $parameter, $parameters, $originalParameters)\n- {\n- $class = $parameter->getClass();\n-\n- // If the parameter has a type-hinted class, we will check to see if it is already in\n- // the list of parameters. If it is we will just skip it as it is probably a model\n- // binding and we do not want to mess with those; otherwise, we resolve it here.\n- if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {\n- return $this->container->make($class->name);\n- }\n- }\n-\n- /**\n- * Determine if an object of the given class is in a list of parameters.\n- *\n- * @param string $class\n- * @param array $parameters\n- * @return bool\n- */\n- protected function alreadyInParameters($class, array $parameters)\n- {\n- return ! is_null(Arr::first($parameters, function ($key, $value) use ($class) {\n- return $value instanceof $class;\n- }));\n- }\n-\n /**\n * Splice the given value into the parameter list.\n *", "filename": "src/Illuminate/Routing/RouteDependencyResolverTrait.php", "status": "modified" }, { "diff": "@@ -893,6 +893,116 @@ public function testImplicitBindingsWithOptionalParameter()\n $router->dispatch(Request::create('bar', 'GET'))->getContent();\n }\n \n+ public function testImplicitBindingsMultipleModelsAndParameters()\n+ {\n+ $phpunit = $this;\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{bar}', function (RoutingTestUserModel $foo, RoutingTestUserModel $bar) use ($phpunit) {\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $foo);\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);\n+\n+ $phpunit->assertEquals('taylor', $foo->value);\n+ $phpunit->assertEquals('otwell', $bar->value);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/taylor/otwell', 'GET'))->getContent());\n+\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{bar}', function (RoutingTestTeamModel $foo, RoutingTestUserModel $bar) use ($phpunit) {\n+ $phpunit->assertInstanceOf(RoutingTestTeamModel::class, $foo);\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);\n+\n+ $phpunit->assertEquals('laravel', $foo->value);\n+ $phpunit->assertEquals('taylor', $bar->value);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/laravel/taylor', 'GET'))->getContent());\n+\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{year}/{bar}', function (RoutingTestUserModel $foo, $year, RoutingTestUserModel $bar) use ($phpunit) {\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $foo);\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);\n+\n+ $phpunit->assertEquals('taylor', $foo->value);\n+ $phpunit->assertEquals(2015, $year);\n+ $phpunit->assertEquals('otwell', $bar->value);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/taylor/2015/otwell', 'GET'))->getContent());\n+ }\n+\n+ public function testImplicitBindingsMultipleModelsAndParametersWithOptinal()\n+ {\n+ $phpunit = $this;\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{year?}/{bar?}', function (RoutingTestUserModel $foo, $year = null, RoutingTestUserModel $bar = null) use ($phpunit) {\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $foo);\n+ $phpunit->assertEquals('taylor', $foo->value);\n+ $phpunit->assertNull($year);\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);\n+ $phpunit->assertNull($bar->value);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/taylor', 'GET'))->getContent());\n+\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{year?}/{bar?}', function (RoutingTestUserModel $foo, $year = null, RoutingTestTeamModel $bar = null) use ($phpunit) {\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $foo);\n+ $phpunit->assertEquals('taylor', $foo->value);\n+ $phpunit->assertNull($year);\n+ $phpunit->assertInstanceOf(RoutingTestTeamModel::class, $bar);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/taylor', 'GET'))->getContent());\n+\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{year?}/{bar?}', function (RoutingTestUserModel $foo, $year = 2015, RoutingTestTeamModel $bar = null) use ($phpunit) {\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $foo);\n+ $phpunit->assertEquals('taylor', $foo->value);\n+ $phpunit->assertEquals(2015, $year);\n+ $phpunit->assertInstanceOf(RoutingTestTeamModel::class, $bar);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/taylor', 'GET'))->getContent());\n+ }\n+\n+ public function testImplicitBindingsMixAll()\n+ {\n+ $phpunit = $this;\n+ $router = $this->getRouter();\n+ $router->get('hello/{foo}/{year?}/{bar?}', function (Request $request, RoutingTestUserModel $foo, $year = null, RoutingTestUserModel $bar = null) use ($phpunit) {\n+\n+ $phpunit->assertInstanceOf(Request::class, $request);\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $foo);\n+ $phpunit->assertEquals('taylor', $foo->value);\n+ $phpunit->assertNull($year);\n+ $phpunit->assertInstanceOf(RoutingTestUserModel::class, $bar);\n+\n+ return 'hello';\n+ });\n+\n+ // this makes sure the callback is called\n+ $this->assertEquals('hello', $router->dispatch(Request::create('hello/taylor', 'GET'))->getContent());\n+ }\n+\n protected function getRouter()\n {\n return new Router(new Illuminate\\Events\\Dispatcher);\n@@ -1094,3 +1204,28 @@ public function firstOrFail()\n return $this;\n }\n }\n+\n+class RoutingTestTeamModel extends Model\n+{\n+ public function getRouteKeyName()\n+ {\n+ return 'id';\n+ }\n+\n+ public function where($key, $value)\n+ {\n+ $this->value = $value;\n+\n+ return $this;\n+ }\n+\n+ public function first()\n+ {\n+ return $this;\n+ }\n+\n+ public function firstOrFail()\n+ {\n+ return $this;\n+ }\n+}", "filename": "tests/Routing/RoutingRouteTest.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": "Have a problem with Cache/FileStore on a production server. It periodically fails with unserialize error:\n\n```\nexception 'ErrorException' with message 'unserialize(): Error at offset 282612 of 282614 bytes' in /home/user/xxx/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php:80\nStack trace:\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(8, 'unserialize(): ...', '/home/user/xxx...', 80, Array)\n#1 /home/user/xxx/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php(80): unserialize('O:39:\"Illuminat...')\n#2 /home/user/xxx/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php(49): Illuminate\\Cache\\FileStore->getPayload('todayEvents')\n#3 /home/user/xxx/vendor/laravel/framework/src/Illuminate/Cache/Repository.php(129): Illuminate\\Cache\\FileStore->get('todayEvents')\n#4 /home/user/xxx/vendor/laravel/framework/src/Illuminate/Cache/Repository.php(288): Illuminate\\Cache\\Repository->get('todayEvents')\n#5 [internal function]: Illuminate\\Cache\\Repository->remember('todayEvents', 1, Object(Closure))\n#6 /home/user/xxx/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php(296): call_user_func_array(Array, Array)\n#7 /home/user/xxx/bootstrap/cache/compiled.php(6222): Illuminate\\Cache\\CacheManager->__call('remember', Array)\n#8 /home/user/xxx/bootstrap/cache/compiled.php(6222): Illuminate\\Cache\\CacheManager->remember('todayEvents', 1, Object(Closure))\n#9 /home/user/xxx/app/Http/Controllers/Controller.php(101): Illuminate\\Support\\Facades\\Facade::__callStatic('remember', Array)\n#10 /home/user/xxx/app/Http/Controllers/Controller.php(101): Illuminate\\Support\\Facades\\Cache::remember('todayEvents', 1, Object(Closure))\n```\n\nCache/FileStore read file from cache when another instance of php script write same file into cache. I've added some locks to read/write from cache.\n", "number": 12796, "review_comments": [ { "body": "this should be wrapped in a try finally to make sure this gets closed\n", "created_at": "2016-03-19T13:43:14Z" } ], "title": "[5.2] Add shared locks to Filesystem and Cache/FileStore" }
{ "commits": [ { "message": "Add shared locks to Filesystem and Cache/FileStore" }, { "message": "codestyle fix" }, { "message": "add empty lines" }, { "message": "add try/finally block" }, { "message": "skip HHVM test due to bug" }, { "message": "codestyle fix" } ], "files": [ { "diff": "@@ -63,7 +63,7 @@ protected function getPayload($key)\n // just return null. Otherwise, we'll get the contents of the file and get\n // the expiration UNIX timestamps from the start of the file's contents.\n try {\n- $expire = substr($contents = $this->files->get($path), 0, 10);\n+ $expire = substr($contents = $this->files->get($path, true), 0, 10);\n } catch (Exception $e) {\n return ['data' => null, 'time' => null];\n }\n@@ -101,7 +101,7 @@ public function put($key, $value, $minutes)\n \n $this->createCacheDirectory($path = $this->path($key));\n \n- $this->files->put($path, $value);\n+ $this->files->put($path, $value, true);\n }\n \n /**", "filename": "src/Illuminate/Cache/FileStore.php", "status": "modified" }, { "diff": "@@ -27,19 +27,49 @@ public function exists($path)\n * Get the contents of a file.\n *\n * @param string $path\n+ * @param bool $lock\n * @return string\n *\n * @throws \\Illuminate\\Contracts\\Filesystem\\FileNotFoundException\n */\n- public function get($path)\n+ public function get($path, $lock = false)\n {\n if ($this->isFile($path)) {\n+ if ($lock) {\n+ return $this->sharedGet($path, $lock);\n+ }\n+\n return file_get_contents($path);\n }\n \n throw new FileNotFoundException(\"File does not exist at path {$path}\");\n }\n \n+ /**\n+ * Get contents of a file with shared access.\n+ *\n+ * @param string $path\n+ * @return string\n+ */\n+ public function sharedGet($path)\n+ {\n+ $contents = '';\n+ $handle = fopen($path, 'r');\n+ if ($handle) {\n+ try {\n+ if (flock($handle, LOCK_SH)) {\n+ while (! feof($handle)) {\n+ $contents .= fread($handle, 1048576);\n+ }\n+ }\n+ } finally {\n+ fclose($handle);\n+ }\n+ }\n+\n+ return $contents;\n+ }\n+\n /**\n * Get the returned value of a file.\n *", "filename": "src/Illuminate/Filesystem/Filesystem.php", "status": "modified" }, { "diff": "@@ -289,4 +289,39 @@ public function testMakeDirectory()\n $this->assertFileExists(__DIR__.'/foo');\n @rmdir(__DIR__.'/foo');\n }\n+\n+ public function testSharedGet()\n+ {\n+ if (defined('HHVM_VERSION')) {\n+ $this->markTestSkipped('Skip HHVM test due to bug: https://github.com/facebook/hhvm/issues/5657');\n+\n+ return;\n+ }\n+\n+ $content = '';\n+ for ($i = 0; $i < 1000000; ++$i) {\n+ $content .= $i;\n+ }\n+ $result = 1;\n+\n+ for ($i = 1; $i <= 20; ++$i) {\n+ $pid = pcntl_fork();\n+\n+ if (! $pid) {\n+ $files = new Filesystem;\n+ $files->put(__DIR__.'/file.txt', $content, true);\n+ $read = $files->get(__DIR__.'/file.txt', true);\n+\n+ exit(($read === $content) ? 1 : 0);\n+ }\n+ }\n+\n+ while (pcntl_waitpid(0, $status) != -1) {\n+ $status = pcntl_wexitstatus($status);\n+ $result *= $status;\n+ }\n+\n+ $this->assertTrue($result === 1);\n+ @unlink(__DIR__.'/file.txt');\n+ }\n }", "filename": "tests/Filesystem/FilesystemTest.php", "status": "modified" } ] }
{ "body": "Previously, this would only check the bindings, but not the instances and aliases. This way, we centralize the logic in the `bound()` method.\n\nFixes #11167\n", "comments": [ { "body": "Should this go to 5.1?\n", "created_at": "2016-03-16T11:35:19Z" }, { "body": "Correct, I just wasn't sure if that's okay, because the contribution guide\nsays to use the latest stable as the target, and, well, 5.2 is the latest\nstable as far as I understand.\n\nFeel free to merge wherever you think it's appropriate, thanks!\nOn Mar 16, 2016 15:35, \"Graham Campbell\" notifications@github.com wrote:\n\n> Should this go to 5.1?\n> \n> —\n> You are receiving this because you authored the thread.\n> Reply to this email directly or view it on GitHub\n> https://github.com/laravel/framework/pull/12745#issuecomment-197276443\n", "created_at": "2016-03-16T11:40:43Z" }, { "body": "Bug fixes need to go to 5.1 LTS.\n", "created_at": "2016-03-16T11:42:30Z" } ], "number": 12745, "title": "[5.2] Fix isset($container[$key]) behavior for instances and aliases" }
{ "body": "Previously, this would only check the bindings, but not the instances and aliases. This way, we centralize the logic in the `bound()` method.\n\nFixes #11167\nSupersedes #12745\n", "number": 12746, "review_comments": [], "title": "[5.1] Fix isset($container[$key]) behavior for instances and aliases" }
{ "commits": [ { "message": "Fix isset($container[$key]) behavior for instances and aliases\n\nPreviously, this would only check the bindings, but not the instances\nand aliases. This way, we centralize the logic in the bound() method.\n\nFixes #11167" } ], "files": [ { "diff": "@@ -1149,7 +1149,7 @@ public static function setInstance(ContainerContract $container)\n */\n public function offsetExists($key)\n {\n- return isset($this->bindings[$key]);\n+ return $this->bound($key);\n }\n \n /**", "filename": "src/Illuminate/Container/Container.php", "status": "modified" }, { "diff": "@@ -268,6 +268,16 @@ public function testUnsetRemoveBoundInstances()\n $this->assertFalse($container->bound('object'));\n }\n \n+ public function testBoundInstanceAndAliasCheckViaArrayAccess()\n+ {\n+ $container = new Container;\n+ $container->instance('object', new StdClass);\n+ $container->alias('object', 'alias');\n+\n+ $this->assertTrue(isset($container['object']));\n+ $this->assertTrue(isset($container['alias']));\n+ }\n+\n public function testReboundListeners()\n {\n unset($_SERVER['__test.rebind']);", "filename": "tests/Container/ContainerTest.php", "status": "modified" } ] }
{ "body": "When adding constraints names are not automatically escaped:\n\n``` php\n<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\n\nclass CreateUserTable extends Migration {\n\n public function up()\n {\n Schema::create('user', function(Blueprint $table)\n {\n $table->increments('id');\n $table->string('name', 64);\n }\n }\n}\n\nclass CreateUserHasSsoTable extends Migration {\n\n public function up()\n {\n Schema::table('user_has_sso', function(Blueprint $table)\n {\n $table->increments('id');\n $table->integer('user_id')->index('sso-to-user');\n\n $table\n ->foreign('user_id', 'sso-to-user')\n ->references('id')\n ->on('user')\n ->onUpdate('NO ACTION')\n ->onDelete('CASCADE');\n });\n }\n}\n```\n\nGives me the following error:\n\n```\n [Illuminate\\Database\\QueryException] \n SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-to-user foreign key (`user_id` \n ) references `user` (`id`) on delete CASCADE on u' at line 1 (SQL: alter table `user_has_sso` add constraint sso-to-user foreign key (`user_id`) references `user` (`id`) on delete CASCADE on update NO ACTION) \n```\n\n``` sql\nalter table `user_has_sso` \nadd constraint sso-to-user -- sso is a reserved keyword\nforeign key (`user_id`) references `user` (`id`) on delete CASCADE on update NO ACTION)\n```\n\nBut when using `$table->foreign('user_id', '`sso-to-user`')` the query will run correctly due to the fact that `sso_to_user` will be escaped.\n", "comments": [ { "body": "`sso` isn't a reserved word. It is more than likely the hypens in it because its not backticked.\nIn regards to your last sentence, can you add the generated query that makes, to show how that one works correctly.\n", "created_at": "2016-02-26T16:31:46Z" }, { "body": "A quick verification indeed confirms that sso isn't reserved, my bad. \n\n``` sql\n-- $table->foreign('user_id', 'sso-to-user')-> ...\nalter table `user_has_sso` add constraint sso-to-user foreign key (`user_id`) references `user` (`id`) on delete CASCADE on update NO ACTION;\n-- $table->foreign('user_id', '`sso-to-user`')-> ...\nalter table `user_has_sso` add constraint `sso-to-user` foreign key (`user_id`) references `user` (`id`) on delete CASCADE on update NO ACTION;\n```\n\nFull log\n\n```\n /p/t/migration-test> php artisan migrate --pretend | grep -i sso-to\nCreateUserHasSsoTable: alter table `user_has_sso` add index `sso-to-user`(`user_id`)\nAddForeignKeysToUserHasSsoTable: alter table `user_has_sso` add constraint sso-to-user foreign key (`user_id`) references `user` (`id`) on delete CASCADE on update NO ACTION\n /p/t/migration-test> nano database/migrations/2016_02_26_151614_add_foreign_keys_to_user_has_sso_table.php # Add backticks\n /p/t/migration-test> php artisan migrate --pretend | grep -i sso-to\nCreateUserHasSsoTable: alter table `user_has_sso` add index `sso-to-user`(`user_id`)\nAddForeignKeysToUserHasSsoTable: alter table `user_has_sso` add constraint `sso-to-user` foreign key (`user_id`) references `user` (`id`) on delete CASCADE on update NO ACTION\n```\n", "created_at": "2016-02-26T16:45:32Z" }, { "body": "Can this be closed then?\n", "created_at": "2016-02-26T16:46:26Z" }, { "body": "@GrahamCampbell is the grammar for mysql supposed to backtick that 2nd argument for foreign in the sql?\n", "created_at": "2016-02-26T16:50:45Z" }, { "body": "I guess it is, yes. Ping @taylorotwell.\n", "created_at": "2016-02-26T16:51:43Z" }, { "body": "Illuminate/Database/Schema/Grammars/Grammar.php\n\nLine 94\n\n``` php\n$sql = \"alter table {$table} add constraint {$command->index} \";\n```\n\nCould be changed to this to wrap the index:\n\n``` php\n$index = $this->wrap($command->index);\n\n$sql = \"alter table {$table} add constraint {$index} \";\n```\n\nHappy to send a pull request if needed.\n", "created_at": "2016-02-27T14:15:20Z" }, { "body": "@GrahamCampbell Can you close this Issue?\n", "created_at": "2016-04-19T23:47:27Z" } ], "number": 12503, "title": "[5.2.5] Constraint names are not automatically escaped" }
{ "body": "This pull request updates the database grammars to wrap all constraints and indexes by default. \n\nSee issue #12503\n", "number": 12599, "review_comments": [], "title": "[5.2] Wrap all database indexes and constraints" }
{ "commits": [ { "message": "Wrap all indexes and constraints. Modify tests to match." } ], "files": [ { "diff": "@@ -82,6 +82,8 @@ public function compileForeign(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n+ $index = $this->wrap($command->index);\n+\n $on = $this->wrapTable($command->on);\n \n // We need to prepare several of the elements of the foreign key definition\n@@ -91,7 +93,7 @@ public function compileForeign(Blueprint $blueprint, Fluent $command)\n \n $onColumns = $this->columnize((array) $command->references);\n \n- $sql = \"alter table {$table} add constraint {$command->index} \";\n+ $sql = \"alter table {$table} add constraint {$index} \";\n \n $sql .= \"foreign key ({$columns}) references {$on} ({$onColumns})\";\n ", "filename": "src/Illuminate/Database/Schema/Grammars/Grammar.php", "status": "modified" }, { "diff": "@@ -165,7 +165,9 @@ protected function compileKey(Blueprint $blueprint, Fluent $command, $type)\n \n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} add {$type} `{$command->index}`($columns)\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} add {$type} {$index}($columns)\";\n }\n \n /**\n@@ -231,7 +233,9 @@ public function compileDropUnique(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop index `{$command->index}`\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop index {$index}\";\n }\n \n /**\n@@ -245,7 +249,9 @@ public function compileDropIndex(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop index `{$command->index}`\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop index {$index}\";\n }\n \n /**\n@@ -259,7 +265,9 @@ public function compileDropForeign(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop foreign key `{$command->index}`\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop foreign key {$index}\";\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php", "status": "modified" }, { "diff": "@@ -101,9 +101,11 @@ public function compileUnique(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n+ $index = $this->wrap($command->index);\n+\n $columns = $this->columnize($command->columns);\n \n- return \"alter table $table add constraint {$command->index} unique ($columns)\";\n+ return \"alter table $table add constraint {$index} unique ($columns)\";\n }\n \n /**\n@@ -117,7 +119,9 @@ public function compileIndex(Blueprint $blueprint, Fluent $command)\n {\n $columns = $this->columnize($command->columns);\n \n- return \"create index {$command->index} on \".$this->wrapTable($blueprint).\" ({$columns})\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"create index {$index} on \".$this->wrapTable($blueprint).\" ({$columns})\";\n }\n \n /**\n@@ -171,7 +175,9 @@ public function compileDropPrimary(Blueprint $blueprint, Fluent $command)\n {\n $table = $blueprint->getTable();\n \n- return 'alter table '.$this->wrapTable($blueprint).\" drop constraint {$table}_pkey\";\n+ $index = $this->wrap(\"{$table}_pkey\");\n+\n+ return 'alter table '.$this->wrapTable($blueprint).\" drop constraint {$index}\";\n }\n \n /**\n@@ -185,7 +191,9 @@ public function compileDropUnique(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop constraint {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop constraint {$index}\";\n }\n \n /**\n@@ -197,7 +205,9 @@ public function compileDropUnique(Blueprint $blueprint, Fluent $command)\n */\n public function compileDropIndex(Blueprint $blueprint, Fluent $command)\n {\n- return \"drop index {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"drop index {$index}\";\n }\n \n /**\n@@ -211,7 +221,9 @@ public function compileDropForeign(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop constraint {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop constraint {$index}\";\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php", "status": "modified" }, { "diff": "@@ -170,7 +170,9 @@ public function compileUnique(Blueprint $blueprint, Fluent $command)\n \n $table = $this->wrapTable($blueprint);\n \n- return \"create unique index {$command->index} on {$table} ({$columns})\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"create unique index {$index} on {$table} ({$columns})\";\n }\n \n /**\n@@ -186,7 +188,9 @@ public function compileIndex(Blueprint $blueprint, Fluent $command)\n \n $table = $this->wrapTable($blueprint);\n \n- return \"create index {$command->index} on {$table} ({$columns})\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"create index {$index} on {$table} ({$columns})\";\n }\n \n /**\n@@ -257,7 +261,9 @@ public function compileDropColumn(Blueprint $blueprint, Fluent $command, Connect\n */\n public function compileDropUnique(Blueprint $blueprint, Fluent $command)\n {\n- return \"drop index {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"drop index {$index}\";\n }\n \n /**\n@@ -269,7 +275,9 @@ public function compileDropUnique(Blueprint $blueprint, Fluent $command)\n */\n public function compileDropIndex(Blueprint $blueprint, Fluent $command)\n {\n- return \"drop index {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"drop index {$index}\";\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php", "status": "modified" }, { "diff": "@@ -87,7 +87,9 @@ public function compilePrimary(Blueprint $blueprint, Fluent $command)\n \n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} add constraint {$command->index} primary key ({$columns})\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} add constraint {$index} primary key ({$columns})\";\n }\n \n /**\n@@ -103,7 +105,9 @@ public function compileUnique(Blueprint $blueprint, Fluent $command)\n \n $table = $this->wrapTable($blueprint);\n \n- return \"create unique index {$command->index} on {$table} ({$columns})\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"create unique index {$index} on {$table} ({$columns})\";\n }\n \n /**\n@@ -119,7 +123,9 @@ public function compileIndex(Blueprint $blueprint, Fluent $command)\n \n $table = $this->wrapTable($blueprint);\n \n- return \"create index {$command->index} on {$table} ({$columns})\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"create index {$index} on {$table} ({$columns})\";\n }\n \n /**\n@@ -173,7 +179,9 @@ public function compileDropPrimary(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop constraint {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop constraint {$index}\";\n }\n \n /**\n@@ -187,7 +195,9 @@ public function compileDropUnique(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"drop index {$command->index} on {$table}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"drop index {$index} on {$table}\";\n }\n \n /**\n@@ -201,7 +211,9 @@ public function compileDropIndex(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"drop index {$command->index} on {$table}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"drop index {$index} on {$table}\";\n }\n \n /**\n@@ -215,7 +227,9 @@ public function compileDropForeign(Blueprint $blueprint, Fluent $command)\n {\n $table = $this->wrapTable($blueprint);\n \n- return \"alter table {$table} drop constraint {$command->index}\";\n+ $index = $this->wrap($command->index);\n+\n+ return \"alter table {$table} drop constraint {$index}\";\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -275,7 +275,7 @@ public function testAddingForeignKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table `users` add constraint users_foo_id_foreign foreign key (`foo_id`) references `orders` (`id`)', $statements[0]);\n+ $this->assertEquals('alter table `users` add constraint `users_foo_id_foreign` foreign key (`foo_id`) references `orders` (`id`)', $statements[0]);\n }\n \n public function testAddingIncrementingID()", "filename": "tests/Database/DatabaseMySqlSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -81,7 +81,7 @@ public function testDropPrimary()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" drop constraint users_pkey', $statements[0]);\n+ $this->assertEquals('alter table \"users\" drop constraint \"users_pkey\"', $statements[0]);\n }\n \n public function testDropUnique()\n@@ -91,7 +91,7 @@ public function testDropUnique()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" drop constraint foo', $statements[0]);\n+ $this->assertEquals('alter table \"users\" drop constraint \"foo\"', $statements[0]);\n }\n \n public function testDropIndex()\n@@ -101,7 +101,7 @@ public function testDropIndex()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('drop index foo', $statements[0]);\n+ $this->assertEquals('drop index \"foo\"', $statements[0]);\n }\n \n public function testDropForeign()\n@@ -111,7 +111,7 @@ public function testDropForeign()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" drop constraint foo', $statements[0]);\n+ $this->assertEquals('alter table \"users\" drop constraint \"foo\"', $statements[0]);\n }\n \n public function testDropTimestamps()\n@@ -161,7 +161,7 @@ public function testAddingUniqueKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" add constraint bar unique (\"foo\")', $statements[0]);\n+ $this->assertEquals('alter table \"users\" add constraint \"bar\" unique (\"foo\")', $statements[0]);\n }\n \n public function testAddingIndex()\n@@ -171,7 +171,7 @@ public function testAddingIndex()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('create index baz on \"users\" (\"foo\", \"bar\")', $statements[0]);\n+ $this->assertEquals('create index \"baz\" on \"users\" (\"foo\", \"bar\")', $statements[0]);\n }\n \n public function testAddingIncrementingID()", "filename": "tests/Database/DatabasePostgresSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -61,7 +61,7 @@ public function testDropUnique()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('drop index foo', $statements[0]);\n+ $this->assertEquals('drop index \"foo\"', $statements[0]);\n }\n \n public function testDropIndex()\n@@ -71,7 +71,7 @@ public function testDropIndex()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('drop index foo', $statements[0]);\n+ $this->assertEquals('drop index \"foo\"', $statements[0]);\n }\n \n public function testRenameTable()\n@@ -115,7 +115,7 @@ public function testAddingUniqueKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('create unique index bar on \"users\" (\"foo\")', $statements[0]);\n+ $this->assertEquals('create unique index \"bar\" on \"users\" (\"foo\")', $statements[0]);\n }\n \n public function testAddingIndex()\n@@ -125,7 +125,7 @@ public function testAddingIndex()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('create index baz on \"users\" (\"foo\", \"bar\")', $statements[0]);\n+ $this->assertEquals('create index \"baz\" on \"users\" (\"foo\", \"bar\")', $statements[0]);\n }\n \n public function testAddingIncrementingID()", "filename": "tests/Database/DatabaseSQLiteSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -71,7 +71,7 @@ public function testDropPrimary()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" drop constraint foo', $statements[0]);\n+ $this->assertEquals('alter table \"users\" drop constraint \"foo\"', $statements[0]);\n }\n \n public function testDropUnique()\n@@ -81,7 +81,7 @@ public function testDropUnique()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('drop index foo on \"users\"', $statements[0]);\n+ $this->assertEquals('drop index \"foo\" on \"users\"', $statements[0]);\n }\n \n public function testDropIndex()\n@@ -91,7 +91,7 @@ public function testDropIndex()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('drop index foo on \"users\"', $statements[0]);\n+ $this->assertEquals('drop index \"foo\" on \"users\"', $statements[0]);\n }\n \n public function testDropForeign()\n@@ -101,7 +101,7 @@ public function testDropForeign()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" drop constraint foo', $statements[0]);\n+ $this->assertEquals('alter table \"users\" drop constraint \"foo\"', $statements[0]);\n }\n \n public function testDropTimestamps()\n@@ -141,7 +141,7 @@ public function testAddingPrimaryKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('alter table \"users\" add constraint bar primary key (\"foo\")', $statements[0]);\n+ $this->assertEquals('alter table \"users\" add constraint \"bar\" primary key (\"foo\")', $statements[0]);\n }\n \n public function testAddingUniqueKey()\n@@ -151,7 +151,7 @@ public function testAddingUniqueKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('create unique index bar on \"users\" (\"foo\")', $statements[0]);\n+ $this->assertEquals('create unique index \"bar\" on \"users\" (\"foo\")', $statements[0]);\n }\n \n public function testAddingIndex()\n@@ -161,7 +161,7 @@ public function testAddingIndex()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertEquals(1, count($statements));\n- $this->assertEquals('create index baz on \"users\" (\"foo\", \"bar\")', $statements[0]);\n+ $this->assertEquals('create index \"baz\" on \"users\" (\"foo\", \"bar\")', $statements[0]);\n }\n \n public function testAddingIncrementingID()", "filename": "tests/Database/DatabaseSqlServerSchemaGrammarTest.php", "status": "modified" } ] }
{ "body": "I have an eloquent Model with a 16 bit [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) attribute. When represented as a UTF-8 string, it contains malformed characters, which is expected. I use the attribute getter/setters to transform the UUID into the 36 character readable string, but when passed into the closure of a Mail::queue it causes `json_encode` to fail inside of `\\Illuminate\\Queue\\Queue::createPayload`. This results in a `ReflectionException`.\n\nRelevant json_encode error message:\n`json_last_error_msg => \"Malformed UTF-8 characters, possibly incorrectly encoded\"`\n\nHiding the attribute in the Model doesn't having any affect on the serialized data string, since the entire object is serialized including the `$original` array.\n\nI can get around this by passing just the subset of the Model data that is needed for the mail, but perhaps there's a better way of handling this in the framework?\n", "comments": [ { "body": "Ping @taylorotwell.\n", "created_at": "2016-02-07T09:40:57Z" }, { "body": "@JamesGuthrie \nHave you tried to output your model as JSON using `\\Illuminate\\Database\\Eloquent\\Model::toJson` ?\nThis should return an error too.\nDo you have the same error with `\\Illuminate\\Database\\Eloquent\\Model::toJson(JSON_UNESCAPED_UNICODE)` ?\n", "created_at": "2016-02-15T22:42:34Z" }, { "body": "The result of `\\Illuminate\\Database\\Eloquent\\Model::toJson`, with or without the `JSON_UNESCAPED_UNICODE` option, is the same and has no error:\n\n`{\"id\":2,\"uuid\":{}}`\n\nThe class which handles the UUID doesn't have any public fields, which is why it's empty here. The attribute methods, within the `Model`, for the UUID are:\n\n```\nuse Rhumsaa\\Uuid\\Uuid;\n...\npublic function getUuidAttribute($value)\n{\n return Uuid::fromBytes($value);\n}\n\npublic function setUuidAttribute($value)\n{\n $this->attributes['uuid'] = $uuid->getBytes();\n}\n```\n\nAnd this is the library referenced: [Rhumsaa\\Uuid](https://github.com/ramsey/uuid)\n", "created_at": "2016-02-16T01:00:18Z" }, { "body": "I don't understand why the `UUID` is not just stored as a string\n\n``` php\n// Generate a version 1 (time-based) UUID object\n$uuid1 = Uuid::uuid1();\necho $uuid1->toString() . \"\\n\"; // i.e. e4eaaaf2-d142-11e1-b3e4-080027620cdd\n\n// Generate a version 3 (name-based and hashed with MD5) UUID object\n$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');\necho $uuid3->toString() . \"\\n\"; // i.e. 11a38b9a-b3da-360f-9353-a5a725514269\n\n// Generate a version 4 (random) UUID object\n$uuid4 = Uuid::uuid4();\necho $uuid4->toString() . \"\\n\"; // i.e. 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a\n\n// Generate a version 5 (name-based and hashed with SHA1) UUID object\n$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net');\necho $uuid5->toString() . \"\\n\"; // i.e. c4a760a8-dbcf-5254-a0d9-6a4474bd1b62\n```\n", "created_at": "2016-02-16T01:07:18Z" }, { "body": "Ping @jamesmirvine ?\n", "created_at": "2016-02-17T10:24:22Z" }, { "body": "For certain scenarios, storing the `UUID` as a string could be a viable workaround. But in general, the issue remains that stored byte-strings inside of Eloquent Models will cause an exception when passed to the queue.\n", "created_at": "2016-02-18T00:12:39Z" }, { "body": "What is a solution @jamesmirvine ?", "created_at": "2017-05-14T18:51:58Z" }, { "body": "The simplest way is to create a new object with only those fields which are required.\r\nIf you need a byte-string field, then you'll have to convert the field from byte-string to string manually before queuing. Basically, create a JSON friendly object to pass into the queue.", "created_at": "2017-05-15T00:11:30Z" }, { "body": "Thank's for answer me. I'm doing the same. :D", "created_at": "2017-05-15T00:15:54Z" } ], "number": 12194, "title": "Queue Fails to Create Payload with Invalid Characters in Data" }
{ "body": "WIP\n\n---\n\nFix #12194\n", "number": 12308, "review_comments": [], "title": "[5.2] [WIP] Queue : do not escape unicode character" }
{ "commits": [ { "message": "Do not escape unicode character" } ], "files": [ { "diff": "@@ -72,15 +72,17 @@ public function bulk($jobs, $data = '', $queue = null)\n protected function createPayload($job, $data = '', $queue = null)\n {\n if ($job instanceof Closure) {\n- return json_encode($this->createClosurePayload($job, $data));\n+ $payload = $this->createClosurePayload($job, $data);\n } elseif (is_object($job)) {\n return json_encode([\n 'job' => 'Illuminate\\Queue\\CallQueuedHandler@call',\n 'data' => ['command' => serialize(clone $job)],\n ]);\n+ } else {\n+ $payload = $this->createPlainPayload($job, $data);\n }\n \n- return json_encode($this->createPlainPayload($job, $data));\n+ return json_encode($payload, JSON_UNESCAPED_UNICODE);\n }\n \n /**", "filename": "src/Illuminate/Queue/Queue.php", "status": "modified" } ] }
{ "body": "I have a model with this relationship:\n\n``` php\npublic function customer()\n {\n return $this->belongsToMany(Customer::class, 'document_document', 'document_id', 'related_document_id')\n ->wherePivot('type', 'reminder_customer');\n }\n```\n\nWhen I try to query the model like this, it throws a QueryException saying the document_document.type column is not found:\n\n``` php\nReminder::has('customer')->get();\n```\n\nHere's the SQL Eloquent is trying to write. You can see the issue here. The table has been aliased with a hash, but the wherePivot constraint isn't using the hash:\n\n``` sql\nselect * from `documents` where `documents`.`deleted_at` is null and (select count(*) from `document_document` as `self_2f1ddd7f1306826b8c54f745c0141237` where `self_2f1ddd7f1306826b8c54f745c0141237`.`document_id` = `documents`.`id` and `documents`.`deleted_at` is null and `document_document`.`type` = reminder_customer) >= 1\n```\n\nAm I using this improperly or is there a bug here? Thanks!\n", "comments": [ { "body": "I don't think what you are describing is an issue, from what I can gather from your description you don't need to call the \"has('customer')\" to obtain all customers that are related to the \"Reminder\" class via the relationship belongsToMany. \n\nYou can simply do something like this to get all the customers:\n\n```\n$reminder = Reminder::find($id); \n$reminder->customer; \n```\n\nThe `$id` is the corresponding id of the reminder you are interested in.\nNow if you do: `dd($reminder->customer);` you should see a collection of all customers related to the Reminder.\n\nIf you want to loop through each one and get their pivot information you can do something like this:\n\n```\nforeach ($reminder->customer as $customer)\n{\n // $customer->pivot->type\n}\n```\n\nHopefully this is what you were trying to do and that it is helpful! \n", "created_at": "2015-12-04T02:41:35Z" }, { "body": "Thanks for the suggestion @willstumpf, but that doesn't solve the problem. This is actually being used as a filter during the query, as suggested by the documentation (see Eloquent Querying Relationship Existence). I don't want the Customer records actually -- just to return the Reminders that have Customers attached. From what I can tell the more I dig into it, this is a bug. I'll dig in further to see if I can find a fix. As a temporary workaround, I can do a manual join to the pivot table.\n", "created_at": "2015-12-04T03:01:56Z" }, { "body": "Ah, my mistake. Could you share your DB structure? I think I might understand the issue. I'm confused on what your document_document table is because from your code that you show it seems like you only need customers, reminders, and a reminder_customer table but perhaps you named it otherwise or have some other motive that i am misunderstanding. \n\nWhere do you have your pivot column 'type'? I set up something similar to what I think you have and it works for me:\n\nthe DB structure which works for me is similar to:\n\n```\ncustomers\n -id\n\nreminders\n -id\n\nreminder_customer\n -id\n -reminder_id\n -customer_id\n -type\n```\n\n```\npublic function customers()\n {\n return $this->belongsToMany(Customer::class)->wherePivot('type', 'some_type_you_want_to_select_on');\n }\n```\n\nFrom my testing this returns all reminders that has a customer that has a type \"some_type_you_want_to_select_on\" of the pivot field if i use `Reminder::has('customers')->get();`\n\nPerhaps i am misunderstanding the problem again but i think you were using the wherePivot to select the the pivot table. but this should be defined in the belongsToMany function. so it would be something along the lines of:\n\n```\nbelongsToMany(Customer::class, 'reminder_customer', 'customer_id', reminder_id')->wherePivot('type', 'test');\n```\n", "created_at": "2015-12-04T15:06:25Z" }, { "body": "It's exactly that DB structure just with custom table and column names. Your last line matches my original code examples with different table/column names. The type column value is actually \"reminder_customer\" -- that wasn't a mistake. That's actually the type. The table name is actually \"document_document\" -- that wasn't a mistake either.\n\nMy guess is this might the custom table name causing the bug if you're test without custom table name worked. I'll do some more testing on a clean project so I can test with both custom and non-custom table names.\n", "created_at": "2015-12-04T15:12:14Z" }, { "body": "Did some quick testing and found the bug. It only happens when the table name of both models is the same. In my case both the Reminder model and the Customer model have the same table name since both records are in the same table (that's not a mistake). When this happens, Laravel uses the getRelationCountHash() method to generate a table alias for the join but fails to also use the generated alias for the wherePivot constraint fields.\n\nThis won't be an easy fix because the getRelationCountHash() method returns a new timestamped hash each time it's called. Calling it again would generate a different hash. The hash would need to be passed on to wherePivots down the chain, but keeping track of which hash goes with which constraint could require some reworking of the query builder perhaps. Unless I have time to dig into the guts of Eloquent to better understand how this is all working together and submit a PR, I think we'll have to defer this to Taylor if he sees value in fixing -- it's definitely a fringe problem that may only apply to a few of us.\n", "created_at": "2015-12-04T15:41:41Z" }, { "body": "Thanks for investigating this. Are you able to send a PR?\n", "created_at": "2015-12-19T23:14:27Z" }, { "body": "I am not able to right now due to a heavy workload. I worked around this by writing a scope with joins in it to get the project done, so didn't get into finding an actual solution. 99% of projects I work with don't have this issue, but if I get a free moment I'll see if I can find a fix and submit a PR for others who may have models with identical table names. Thanks for following up.\n", "created_at": "2015-12-21T03:30:18Z" }, { "body": "Has this been fixed by #12146?", "created_at": "2016-11-28T01:37:57Z" } ], "number": 11182, "title": "[5.1] [5.2] Cannot use belongsToMany -> withPivot and ->has() methods together" }
{ "body": "This pull requests fixes a couple related issues dealing with self-related relationships.\n- Issue #11182 (open) deals with the `has()` method not working on `belongsToMany` self-relationships that have a `wherePivot` constraint.\n- Issue #9726 (closed, but still an issue) deals with the `whereHas()` method not working on `belongsToMany` self-relationships.\n- Issue #8563 (closed, but still an issue) is basically the same as #9726, it is just framed as the `has()` method being passed a closure, which is basically just the `whereHas()` method. This does not work on `belongsToMany` self-relationships.\n- PR #4954 (merged in PR #6726) contains a [comment](https://github.com/laravel/framework/pull/4954#issuecomment-55391194) detailing that `has()`/`whereHas()` with nested self-relationships don't work.\n\nAll fixes occur in the `getRelationQueryForSelfRelation` method of the `HasOneOrMany` and `BelongsTo` relationships, and the `getRelationQueryForSelfJoin` method of the `BelongsToMany` relationship.\n\nThe basic issue is that when the relationship is a self-relationship, the subquery generated to check `has` existence updates the `from` portion of the subquery to use an alias. However, any conditions added to this subquery will not know about the alias, so they will still reference the base table name.\n\nWith this PR, when the alias is added to the `from` portion of the subquery, the table name on the Model for the subquery will be set to the new alias. By doing this, qualified field names requested from this subquery will now be qualified with the alias, instead of the original table name. This fixes the `has()`/`whereHas()` issue with nested self-relationships.\n\nIn addition to this, for the `BelongsToMany` relationship, the subquery for the self-relationship now includes the base table (which is aliased) joined to the pivot table, not just the pivot table. This, in addition to updating the table name on the related Model (to the alias), fixes the `whereHas()` and `has()`/`wherePivot()` issues on `BelongsToMany` self-relationships.\n\nLet me know if there are any questions or issues, or if I need to retarget this at another branch.\n\nThanks.\n", "number": 12146, "review_comments": [], "title": "[5.2] Fix issues with self-related relationships (has, whereHas, wherePivot)" }
{ "commits": [ { "message": "Add tests for self relationships." }, { "message": "Update query model table with alias for self relationships." }, { "message": "Removed unused use statement." } ], "files": [ { "diff": "@@ -111,6 +111,8 @@ public function getRelationQueryForSelfRelation(Builder $query, Builder $parent,\n \n $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());\n \n+ $query->getModel()->setTable($hash);\n+\n $key = $this->wrap($this->getQualifiedForeignKey());\n \n return $query->where($hash.'.'.$query->getModel()->getKeyName(), '=', new Expression($key));", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsTo.php", "status": "modified" }, { "diff": "@@ -6,7 +6,6 @@\n use Illuminate\\Support\\Str;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Builder;\n-use Illuminate\\Database\\Query\\Expression;\n use Illuminate\\Database\\Eloquent\\Collection;\n use Illuminate\\Database\\Eloquent\\ModelNotFoundException;\n \n@@ -333,11 +332,13 @@ public function getRelationQueryForSelfJoin(Builder $query, Builder $parent, $co\n {\n $query->select($columns);\n \n- $query->from($this->table.' as '.$hash = $this->getRelationCountHash());\n+ $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash());\n \n- $key = $this->wrap($this->getQualifiedParentKeyName());\n+ $this->related->setTable($hash);\n \n- return $query->where($hash.'.'.$this->foreignKey, '=', new Expression($key));\n+ $this->setJoin($query);\n+\n+ return parent::getRelationQuery($query, $parent, $columns);\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php", "status": "modified" }, { "diff": "@@ -85,6 +85,8 @@ public function getRelationQueryForSelfRelation(Builder $query, Builder $parent,\n \n $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());\n \n+ $query->getModel()->setTable($hash);\n+\n $key = $this->wrap($this->getQualifiedParentKeyName());\n \n return $query->where($hash.'.'.$this->getPlainForeignKey(), '=', new Expression($key));", "filename": "src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php", "status": "modified" }, { "diff": "@@ -517,6 +517,41 @@ public function testOrHasNested()\n $this->assertEquals($builder->toSql(), $result);\n }\n \n+ public function testSelfHasNested()\n+ {\n+ $model = new EloquentBuilderTestModelSelfRelatedStub;\n+\n+ $nestedSql = $model->whereHas('parentFoo', function ($q) {\n+ $q->has('childFoo');\n+ })->toSql();\n+\n+ $dotSql = $model->has('parentFoo.childFoo')->toSql();\n+\n+ // alias has a dynamic hash, so replace with a static string for comparison\n+ $alias = 'self_alias_hash';\n+ $aliasRegex = '/\\b(self_[a-f0-9]{32})(\\b|$)/i';\n+\n+ $nestedSql = preg_replace($aliasRegex, $alias, $nestedSql);\n+ $dotSql = preg_replace($aliasRegex, $alias, $dotSql);\n+\n+ $this->assertEquals($nestedSql, $dotSql);\n+ }\n+\n+ public function testSelfHasNestedUsesAlias()\n+ {\n+ $model = new EloquentBuilderTestModelSelfRelatedStub;\n+\n+ $sql = $model->has('parentFoo.childFoo')->toSql();\n+\n+ // alias has a dynamic hash, so replace with a static string for comparison\n+ $alias = 'self_alias_hash';\n+ $aliasRegex = '/\\b(self_[a-f0-9]{32})(\\b|$)/i';\n+\n+ $sql = preg_replace($aliasRegex, $alias, $sql);\n+\n+ $this->assertContains('\"self_related_stubs\".\"parent_id\" = \"self_alias_hash\".\"id\"', $sql);\n+ }\n+\n protected function mockConnectionForModel($model, $database)\n {\n $grammarClass = 'Illuminate\\Database\\Query\\Grammars\\\\'.$database.'Grammar';\n@@ -611,3 +646,38 @@ public function baz()\n class EloquentBuilderTestModelFarRelatedStub extends Illuminate\\Database\\Eloquent\\Model\n {\n }\n+\n+class EloquentBuilderTestModelSelfRelatedStub extends Illuminate\\Database\\Eloquent\\Model\n+{\n+ protected $table = 'self_related_stubs';\n+\n+ public function parentFoo()\n+ {\n+ return $this->belongsTo('EloquentBuilderTestModelSelfRelatedStub', 'parent_id', 'id', 'parent');\n+ }\n+\n+ public function childFoo()\n+ {\n+ return $this->hasOne('EloquentBuilderTestModelSelfRelatedStub', 'parent_id', 'id', 'child');\n+ }\n+\n+ public function childFoos()\n+ {\n+ return $this->hasMany('EloquentBuilderTestModelSelfRelatedStub', 'parent_id', 'id', 'children');\n+ }\n+\n+ public function parentBars()\n+ {\n+ return $this->belongsToMany('EloquentBuilderTestModelSelfRelatedStub', 'self_pivot', 'child_id', 'parent_id', 'parent_bars');\n+ }\n+\n+ public function childBars()\n+ {\n+ return $this->belongsToMany('EloquentBuilderTestModelSelfRelatedStub', 'self_pivot', 'parent_id', 'child_id', 'child_bars');\n+ }\n+\n+ public function bazes()\n+ {\n+ return $this->hasMany('EloquentBuilderTestModelFarRelatedStub', 'foreign_key', 'id', 'bar');\n+ }\n+}", "filename": "tests/Database/DatabaseEloquentBuilderTest.php", "status": "modified" }, { "diff": "@@ -286,6 +286,68 @@ public function testHasOnSelfReferencingBelongsToManyRelationship()\n $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n }\n \n+ public function testWhereHasOnSelfReferencingBelongsToManyRelationship()\n+ {\n+ $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);\n+\n+ $results = EloquentTestUser::whereHas('friends', function ($query) {\n+ $query->where('email', 'abigailotwell@gmail.com');\n+ })->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n+ }\n+\n+ public function testHasOnNestedSelfReferencingBelongsToManyRelationship()\n+ {\n+ $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);\n+ $nestedFriend = $friend->friends()->create(['email' => 'foo@gmail.com']);\n+\n+ $results = EloquentTestUser::has('friends.friends')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n+ }\n+\n+ public function testWhereHasOnNestedSelfReferencingBelongsToManyRelationship()\n+ {\n+ $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);\n+ $nestedFriend = $friend->friends()->create(['email' => 'foo@gmail.com']);\n+\n+ $results = EloquentTestUser::whereHas('friends.friends', function ($query) {\n+ $query->where('email', 'foo@gmail.com');\n+ })->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n+ }\n+\n+ public function testHasOnSelfReferencingBelongsToManyRelationshipWithWherePivot()\n+ {\n+ $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);\n+\n+ $results = EloquentTestUser::has('friendsOne')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n+ }\n+\n+ public function testHasOnNestedSelfReferencingBelongsToManyRelationshipWithWherePivot()\n+ {\n+ $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);\n+ $nestedFriend = $friend->friends()->create(['email' => 'foo@gmail.com']);\n+\n+ $results = EloquentTestUser::has('friendsOne.friendsTwo')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n+ }\n+\n public function testHasOnSelfReferencingBelongsToRelationship()\n {\n $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n@@ -297,6 +359,45 @@ public function testHasOnSelfReferencingBelongsToRelationship()\n $this->assertEquals('Child Post', $results->first()->name);\n }\n \n+ public function testWhereHasOnSelfReferencingBelongsToRelationship()\n+ {\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);\n+\n+ $results = EloquentTestPost::whereHas('parentPost', function ($query) {\n+ $query->where('name', 'Parent Post');\n+ })->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Child Post', $results->first()->name);\n+ }\n+\n+ public function testHasOnNestedSelfReferencingBelongsToRelationship()\n+ {\n+ $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);\n+\n+ $results = EloquentTestPost::has('parentPost.parentPost')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Child Post', $results->first()->name);\n+ }\n+\n+ public function testWhereHasOnNestedSelfReferencingBelongsToRelationship()\n+ {\n+ $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);\n+\n+ $results = EloquentTestPost::whereHas('parentPost.parentPost', function ($query) {\n+ $query->where('name', 'Grandparent Post');\n+ })->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Child Post', $results->first()->name);\n+ }\n+\n public function testHasOnSelfReferencingHasManyRelationship()\n {\n $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n@@ -308,6 +409,45 @@ public function testHasOnSelfReferencingHasManyRelationship()\n $this->assertEquals('Parent Post', $results->first()->name);\n }\n \n+ public function testWhereHasOnSelfReferencingHasManyRelationship()\n+ {\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);\n+\n+ $results = EloquentTestPost::whereHas('childPosts', function ($query) {\n+ $query->where('name', 'Child Post');\n+ })->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Parent Post', $results->first()->name);\n+ }\n+\n+ public function testHasOnNestedSelfReferencingHasManyRelationship()\n+ {\n+ $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);\n+\n+ $results = EloquentTestPost::has('childPosts.childPosts')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Grandparent Post', $results->first()->name);\n+ }\n+\n+ public function testWhereHasOnNestedSelfReferencingHasManyRelationship()\n+ {\n+ $grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);\n+\n+ $results = EloquentTestPost::whereHas('childPosts.childPosts', function ($query) {\n+ $query->where('name', 'Child Post');\n+ })->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Grandparent Post', $results->first()->name);\n+ }\n+\n public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()\n {\n $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n@@ -333,6 +473,26 @@ public function testBasicHasManyEagerLoading()\n $this->assertEquals('taylorotwell@gmail.com', $post->first()->user->email);\n }\n \n+ public function testBasicNestedSelfReferencingHasManyEagerLoading()\n+ {\n+ $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ $post = $user->posts()->create(['name' => 'First Post']);\n+ $post->childPosts()->create(['name' => 'Child Post', 'user_id' => $user->id]);\n+\n+ $user = EloquentTestUser::with('posts.childPosts')->where('email', 'taylorotwell@gmail.com')->first();\n+\n+ $this->assertNotNull($user->posts->first());\n+ $this->assertEquals('First Post', $user->posts->first()->name);\n+\n+ $this->assertNotNull($user->posts->first()->childPosts->first());\n+ $this->assertEquals('Child Post', $user->posts->first()->childPosts->first()->name);\n+\n+ $post = EloquentTestPost::with('parentPost.user')->where('name', 'Child Post')->get();\n+ $this->assertNotNull($post->first()->parentPost);\n+ $this->assertNotNull($post->first()->parentPost->user);\n+ $this->assertEquals('taylorotwell@gmail.com', $post->first()->parentPost->user->email);\n+ }\n+\n public function testBasicMorphManyRelationship()\n {\n $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n@@ -646,6 +806,16 @@ public function friends()\n return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id');\n }\n \n+ public function friendsOne()\n+ {\n+ return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id')->wherePivot('user_id', 1);\n+ }\n+\n+ public function friendsTwo()\n+ {\n+ return $this->belongsToMany('EloquentTestUser', 'friends', 'user_id', 'friend_id')->wherePivot('user_id', 2);\n+ }\n+\n public function posts()\n {\n return $this->hasMany('EloquentTestPost', 'user_id');", "filename": "tests/Database/DatabaseEloquentIntegrationTest.php", "status": "modified" } ] }
{ "body": "When using the fill method, any $casts are ignored. Ex.\n\n'valid' => 'boolean'\n\nWorks:\n$object->valid = 'something'; // Will convert to a 1 for database storage\n\nDoesn't work:\n$arr = ['valid' => 'something'];\n$object->fill($arr); // will stay as 'something'\n\nTemporary Fix is just to make a setValidAttribute($valid) mutator but I would think that in order to have consistent behavior across the board, $casts should be respected anyway that attributes can be set.\n", "comments": [ { "body": "Looks like a bug to me.\n", "created_at": "2015-06-03T14:20:06Z" }, { "body": "I'm pretty sure that `$object->valid = 'somthing';` will not cast the value unless you try to access it.\n\nTry to `dd()` or `dump()` the object after you do that to see the actual value.\n\nSo this is expected behaviour.\n", "created_at": "2015-06-03T18:03:12Z" }, { "body": "Both `Model::fill()` and `Model::__set()` use `Model::setAttribute()` to set the attribute value.\n", "created_at": "2015-06-03T18:04:30Z" }, { "body": "Hmm... I somehow am not able to replicate this again, maybe I was doing something funky.\nEither way to add on/change this bug a bit.\nThe documentation says the following:\n\"Otherwise, you will have to define a mutator for each of the attributes, which can be time consuming.\"\nwhich is what led me to believe that the cast would occur in setting and getting.\n\nOn top of that there is some implicit casting going on if you have a json castable item. as seen in Model::isJsonCastable() which is called from Model::setAttribute(). I would say there should either be cast checking for any column set as castable or none as this was actually a bit confusing.\n", "created_at": "2015-06-04T14:48:36Z" }, { "body": "`Model::setAttribute()` doesn't make any casts in 5.1 source. Only `Model::getAttribute()` does. Is this intended?\n", "created_at": "2015-06-04T20:44:33Z" }, { "body": "...It actually does....\nhttps://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L2766\nhttps://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L2770\nboth of those reference implicit casting for specific cases which is where this ticket came from.\n", "created_at": "2015-06-05T15:29:19Z" }, { "body": "@ragingdave But that relates only for dates and json casts. Not $casts attrubute related fields\n", "created_at": "2015-06-05T16:30:26Z" }, { "body": "Again actually it does....\nhttps://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L2685\nleads to\nhttps://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L2676\nSo it in fact does deal with $casts. It doesn't care specifically about casting it using castAttribute, but it does cast an array/json/object/collection to a string using json_encode.\n", "created_at": "2015-06-05T18:36:17Z" }, { "body": "I guess it was done for a reason - according to `castAttribute` method phpDoc casting is made _to a native PHP type_. So it is made to avoid incorrect handling of values from different database types (e. g. MySQL uses integer to implement booleans while PostgreSQL has native boolean type).\n\nYou should control types written to database from you code while Eloquent prevents your code from getting unexpected types.\n\nThis differs from JSON - which must always be encoded to string before passing to PDO.\n", "created_at": "2015-06-09T16:15:31Z" }, { "body": "Wouldn't that specific of casting happen in the specific connection?\nI assume eloquent shouldn't care about the underlying PDO that is being used, so in that train of thought any casting to handle that type of requirement at a storage engine level should not be a Model but instead be in the Connection layer perhaps when the statements get prepared and whatnot to convert specific types to database friendly ones?\n", "created_at": "2015-06-09T18:08:18Z" }, { "body": "@ragingdave Ideally - it is.\nBut actually this is possible only by analyzing schema configuration (because `TINYINT(1)` in MySQL is not always boolean).\nBut migrations are not present in all projects - e. g. I don't duplicate migrations on projects using the same DB. And also this would be very slow - as it is needed to execute all migrations one by one to get final schema configuration.\n\nSo implementing this in a Model is much more handy - you always know which fields you will get from DB and which casting type you should use. And the same vice versa - you always know what kind of data you should store in a Model field.\n\nI think if casting will be enabled on attribute setting, then peoples will tend to avoid proper validation (mistakely believing the Model will properly cast values), thus causing unexpected data written to database.\n", "created_at": "2015-06-10T01:44:27Z" }, { "body": "I had a similiar problem today regarding the casting implementation.\nI was using the 5.0.31 version with a custom Pivot class. On this class I had:\n\n``` php\nprotected $casts = [\n 'details' => 'array'\n]\n```\n\nI tried to update to v5.0.33 and I noticed that when I asked for the value of details using my pivot I was receiving a string instead of an array. I did a diff between v5.0.31 and v5.0.33 and found 2 method calls on Pivot.php class.\n\n``` php\n$this->forceFill($attributes);\n$this->syncOriginal();\n```\n\nThe forceFill method seems to be the problem in my case, it calls the setAttribute method that checks the attribute using isJsonCastable and encode the value twice. So for a object stored as { c1: \"on\" } as string becomes serialised version of the string \"{ c1: \\\"on\\\" }\" which cannot be decoded using json_decode.\n\nFor me, as a workaround I had to implement the method getDetailsAttribute on the Pivot and remove the property from $casts array to avoid the double encoding problem.\n\nI'm still figuring out a more smart solution.\n", "created_at": "2015-06-24T17:26:37Z" }, { "body": "Why is this issue 'closed'? Is it fixed? You've referenced my originally issue 'Laravel Eloquent Model 'getDirty()' behaviour #10735' to this one and now it's closed?!\n", "created_at": "2016-02-17T15:13:43Z" }, { "body": "I was hit with a strange issue in our codebase today, more related to https://github.com/laravel/framework/issues/10792 actually:\n- assume an attribute `some_flag` using the following migration for a MySQL database: `$table->boolean('some_flag')->default(0);`\n- have a `$casts` on the model: `'some_flag' => 'boolean',`\n- fetch model from DB, `$model->some_flag` is returned as `false` (properly cast, everything good!)\n- I now perform: `$model->some_flag = false;`\n- The output of `$model->getDirty()` is (using artisan tinker):\n\n```\n>>> $model->getDirty()\n=> [\n \"some_flag\" => false,\n ]\n```\n\nWhy this? Because the `$original` value is `0` and not false:\n\n```\n>>> $model->getOriginal('some_flag')\n=> 0\n```\n\nand `getDirty()` does this comparison (reformatted from original code for smaller line lenght):\n\n```\nif (\n $value !== $this->original[$key] &&\n ! $this->originalIsNumericallyEquivalent($key)\n ) {\n```\n\nIn the end, it's doing the check `false !== 0`.\n\nCasts are not considered here, which may impact your expectations:\n- if you use `getDirty()` to rely on changes to a model (e.g. for recording)\n- `$model->save()` will cause unnecessary saves to the database\n", "created_at": "2016-03-01T10:39:06Z" }, { "body": "Can confirm that the issue still exists. It does also apply to MySQL decimals btw.\n\nIm using [this workaround](https://gist.github.com/paslandau/b2e17820f7458943967c) for now.\n", "created_at": "2016-03-17T18:20:27Z" }, { "body": "I'm having the exact same problem as @mfn here.\n", "created_at": "2016-04-18T12:03:50Z" }, { "body": "I related the same issue on #13742 with MySQL decimal fields.\n\nThe problem looks like be on this method:\n\n```\n protected function originalIsNumericallyEquivalent($key)\n {\n $current = $this->attributes[$key];\n $original = $this->original[$key];\n return is_numeric($current) && is_numeric($original) && strcmp((string) $current, (string) $original) === 0;\n }\n```\n\nThe comparation `is_numeric($original) && strcmp((string) $current, (string) $original) === 0` does not compare properly, since the decimal field from mysql cames as `\"14.00\"` and the float value `14.00` is casted to string as `\"14\"`.\n\nShouldn't this values be casted to float and compared?\n\n```\n protected function originalIsNumericallyEquivalent($key)\n {\n $current = $this->attributes[$key];\n $original = $this->original[$key];\n return is_numeric($current) && is_numeric($original) && (float) $original == (float) $current;\n }\n```\n", "created_at": "2016-05-27T14:51:00Z" }, { "body": "This issue still persists for laravel 5.1.*\n\nI have a Location model, with a polymorphic relation to a couple of other models. On this models, I have a casts defined as:\n\n``` php\nprotected $casts = [\n 'address_components' => 'json',\n 'types' => 'json',\n 'components' => 'json',\n ];\n```\n\nFrom the related models, when saving I'm doing:\n\n``` php\n$this->location()->create($location);\n```\n\nthen update like so:\n\n``` php\n$this->location()->update($location);\n```\n\nThe save method causes a double cast on the defined fields, causing the end result to be a string. However, update works as expected.\n", "created_at": "2016-09-19T18:20:47Z" }, { "body": "This is still an issue on laravel 5.2.45. If I call getAttributes() on a model and then create another object with those attributes, on save the attribute casted as array is double encoded.\n\nMy fix was to override the method getAttributes() in a BaseModel class in my app like so:\n\n```\n public function getAttributes()\n {\n $attributes = parent::getAttributes();\n\n foreach ($attributes as $name => $attribute) {\n if ($this->isJsonCastable($name)) {\n $attributes[$name] = $this->fromJson($attribute);\n }\n }\n\n return $attributes;\n }\n```\n", "created_at": "2016-10-17T22:26:17Z" }, { "body": "Expanding on my https://github.com/laravel/framework/issues/8972#issuecomment-190656490 : \nWe're switching from MySQL to Postgres and notice these problems are gone. In our test suite we do a (few) less `SQL UPDATE` statements, because the `getDirty()` comparison less often triggers a dirty object.\n\nThe reasoning behind this is that we use the `->boolean()` type in our migration which, in postgres due native boolean support, is the actual postgres type boolean which ends up back in Laravel natively as `boolean` too, returned from the PDO driver.\n\nAs such, for my case, it's basically solved.\n\nIt seems this either needs a in-between-layer between taking the PDO result and hydrating the data into Laravel, specifically for MySQL, or MySQL gets (or has aleady?) a native boolean type too.\n", "created_at": "2016-10-30T06:50:16Z" }, { "body": "@mfn shouldn't you technically be able to cast the result of any int column to a bool with Eloquent's casts property, even if MySQL did have native booleans that you could migrate to? If so it would suggest the resolution should be above the PDO layer rather than in it - it would be a valid use case even on Postgres.\n", "created_at": "2016-11-07T18:26:09Z" }, { "body": "> @mfn shouldn't you technically be able to cast the result of any int column to a bool with Eloquent's casts property, even if MySQL did have native booleans that you could migrate to?\n\nMind you that this \"casting\" only happens when you invoke the attribute getter from a model.\n\nBut when you retrieve a model, fresh from the DB, the hydrated values internally in the model, stored in `$original` are **not** cast. But these values are referenced when determining whether the model is dirty or not.\n\nTo given an example with a boolean:\n- since MySQL doesn't have a native boolean type, the `$original` will contain the value `1` for a truthy value (people usually just use `TINYINT(1)` for this; even https://github.com/barryvdh/laravel-ide-helper thinks so and will update the models PHPDOC in such cases with `boolean`)\n- When you invoke the getter, with a cast, you get an actual `true`\n- Now assume you **set** the value to `true`. Right, makes no sense, the value is already true.\n- Wrong, however: the value in `$original` is still the `1`. You set a `true` so the `getDirty()` comparison will, in fact, determine that the model is dirty, because `1 !== true`\n- This will lead to needless updates in the database\n\nAs long as you're using the native boolean type in PgSQL, this won't happen there because `$original` will already be filled with an actual `true` value and as such `getDirty()` will in such a case not determine that the model is dirty.\n\nWhat's with the contrived example, setting the value to the same value again?\n\nWell, just think about a `PATCH` API endpoint. The request issues some updates to boolean fields, setting some values to `true`. Now even if that value in MySQL would be `1` already, but because of the above mentioned comparison failing, we still would trigger updating the model. And suddenly things are not so contrived anymore.\n\nGranted, it's a _small_ thing but if you're concerned what's going on under the hood, these things may trip you over and left wonder.\n\nAll examples I have with `1` and `true` equally apply to `0` and `false` too.\n\nAlso see https://github.com/laravel/framework/issues/10792 (which was closed a kind-a dupe of this one). Also 2: I gave already thorough example I just realized, see https://github.com/laravel/framework/issues/8972#issuecomment-190656490 \n", "created_at": "2016-11-07T21:32:24Z" }, { "body": "I have ended up with this workaround in my base model if anyone is interested.\n\n```\n\n /**\n * Get the attributes that have been changed since last sync.\n *\n * @return array\n */\n public function getDirty()\n {\n $dirty = [];\n\n // cast any original attributes to the types they are expected to be\n foreach ($this->original as $key => $value) {\n if (isset($this->casts[$key])) {\n $this->original[$key] = $this->castAttribute($key, $value);\n }\n }\n\n foreach ($this->attributes as $key => $value) {\n // cast any of the current attributes to the types they are expected to be\n if (isset($this->casts[$key])) {\n $value = $this->castAttribute($key, $value);\n }\n\n if (! array_key_exists($key, $this->original)) {\n $dirty[$key] = $value;\n } elseif ($value !== $this->original[$key] &&\n ! $this->originalIsNumericallyEquivalent($key)) {\n $dirty[$key] = $value;\n }\n }\n\n return $dirty;\n }\n```\n\nSection of a now passing unit test for a model using casts:\n\n```\n /** @var Asset $asset */\n $asset = Asset::findOrFail(1);\n $asset->is_active = true;\n $asset->save();\n\n $asset = Asset::findOrFail(1);\n $isActive = $asset->is_active;\n // probably unnecessary to wrap the extra equality check\n // however, considering the behaviour in question concerns casting I went with an explicit strict check here\n $this->assertTrue($isActive === true);\n\n $asset->is_active = true;\n // property hasn't changed so it should be clean\n $this->assertFalse($asset->isDirty());\n```\n\nRelevant part of the model itself:\n\n```\n protected $casts = [\n 'is_available' => 'boolean',\n 'is_active' => 'boolean',\n ];\n```\n", "created_at": "2016-11-09T15:08:00Z" }, { "body": "Hey @GrahamCampbell still up to the same old bullshit I see. This bug still exists but you closed it without saying why. There are actually various bugs I keep running into with `original` attributes since they don't use casts or mutators. But why would I try open a new issue about it when it will just get closed for no reason?\r\n\r\nI use `$casts` with boolean for an attribute. I have controller update this (sets the same value, `true` to it). It is now dirty because in the database it is `1` and the attribute is seen as `true` due to casts (same would happen with mutators).\r\n\r\nOriginal values need to be using the casts and mutator systems or there needs to be a second set of `$this->original` for this instead of doing things like the hacky `originalIsNumericallyEquivalent`.\r\n\r\nReopen the damn issue.", "created_at": "2017-02-15T03:28:22Z" }, { "body": "I have created a trait to fix this for my needs. It doesn't account for some things I don't need but will now work for all casts except `object` and mutators that return a scalar or array.\r\n\r\nThis is done on Laravel 5.3.x. But from what I looked at for 5.4 the only changes made were moving code to traits, not changing it.\r\n\r\nThe trait:\r\n```php\r\n<?php\r\n\r\nnamespace App;\r\n\r\n// TODO: remove when bug is fixed, https://github.com/laravel/framework/issues/8972\r\ntrait FixEloquentDirty\r\n{\r\n // NOTE: this still doesn't handle appends or extra casts. I could have copy pasted\r\n // a bunch of stuff from `attributesToArray` but I don't need it anyway for this.\r\n // The proper fix for this should be using refactored methods from `attributesToArray`\r\n // NOTE 2: the methods I was talking about that should be refactored in `attributesToArray`\r\n // have been refactored in Laravel 5.4 (except where it handles appends)\r\n public function syncOriginal()\r\n {\r\n foreach ($this->attributes as $key => $value) {\r\n $this->originalCasted[$key] = $this->getAttributeValue($key);\r\n }\r\n\r\n foreach ($this->getDates() as $key) {\r\n if (! isset($this->originalCasted[$key])) {\r\n continue;\r\n }\r\n\r\n // needs to be the same as the database, skipping the models `$this->dateFormat`\r\n $this->originalCasted[$key] = $this->asDateTime($this->originalCasted[$key])\r\n ->format($this->getConnection()->getQueryGrammar()->getDateFormat());\r\n }\r\n\r\n return parent::syncOriginal();\r\n }\r\n\r\n // this probably doesn't need that hacky `originalIsNumericallyEquivalent` anymore either so removed it\r\n public function getDirty()\r\n {\r\n $dirty = [];\r\n foreach ($this->attributes as $key => $value) {\r\n // this clearly needs a refactor\r\n if (! array_key_exists($key, $this->originalCasted)) {\r\n $dirty[$key] = $value;\r\n } elseif (is_scalar($value) && $value !== $this->originalCasted[$key]) {\r\n $dirty[$key] = $value;\r\n } elseif (is_array($value) && $value != $this->originalCasted[$key]) {\r\n $dirty[$key] = $value;\r\n }\r\n // TODO: checking Arrayable here would make it work with collections\r\n // then StdClass could be made compatable from `$casts` `object` if\r\n // you compare a json_encode or convert to array and compare\r\n }\r\n\r\n return $dirty;\r\n }\r\n}\r\n```\r\n\r\nAnd using it in my base model, note that you need to set `protected $originalCasted = [];` in the model or it won't work.\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App;\r\n\r\n... \r\n\r\nuse Illuminate\\Database\\Eloquent\\Model as BaseModel;\r\n\r\nclass Model extends BaseModel\r\n{\r\n // TODO: remove when bug is fixed, https://github.com/laravel/framework/issues/8972#issuecomment-279907478\r\n use FixEloquentDirty;\r\n protected $originalCasted = [];\r\n\r\n ...\r\n}\r\n\r\n```\r\n\r\nThat is the way I envision it being fixed since I have had various issues with `original` and actually needing them run through casts and mutators. However it could be slow and give eloquent a performance hit in general so maybe instead, just doing some basic checks like running through `$casts` and if something is set to `bool` also check for `false` vs `0` and `true` vs `1`.\r\n", "created_at": "2017-02-15T04:39:49Z" }, { "body": "Honestly it needs to be either checking what the model has like what I am doing above (bad for performance but good for me until fixed properly), store what is dirty as it is set (this is a common way to do it and doesn't impact performance), or compare what you got from the database to what you will set in the database... anything else, like what is happening now, is a hack and will have bugs of some form.", "created_at": "2017-02-15T05:15:39Z" }, { "body": "looks like `$casts` is just a getter. so use a mutator to enforce persisting the right data type.\r\n\r\nit would be cool if there was a `$mutates` option just for casting types on mutation, rather than create individual mutators just for that\r\n\r\n...it would actual be nice if the docs were more explicit on what something doesn't do.", "created_at": "2017-03-15T16:01:10Z" }, { "body": "still happening with Laravel 5.4\r\n\r\nIs there an easy way to make $model->fill() apply the $casts ? I don't understand about mutators, never used them. Can someone provide an example please?\r\n\r\nAnd why doesn't this get patched? Leads to very inconsistent behavior", "created_at": "2017-05-08T06:39:57Z" }, { "body": "Yeah still happening with laravel 5.4", "created_at": "2017-06-11T09:36:50Z" }, { "body": "@vesper8 I will be happy if someone fix it. I tried to fix it but the patch was rejected and I don't know why! Was it because the patch was wrong or @taylorotwell have a better solution in mind, or he just doesn't think it should be fixed at that time?\r\n\r\nhttps://github.com/laravel/framework/pull/17474#issuecomment-274508335", "created_at": "2017-06-11T09:59:40Z" } ], "number": 8972, "title": "Inconsistant Cast Behavior for Eloquent" }
{ "body": "# Situation\n\nWe need to store some json data in pivot table. And for that we decide to use Eloquent attribute casting functionality, for more easily setting and getting data.\n\nFor that we must create custom pivot model and set `protected $casting` property.\n\n---\n#### expected:\n\nattribute setted in `$casting` property as `json` or `array` will be automaticaly casted in array by accesing that property on our custom pivot model and any setted `array` or `JsonSerializable` object will be json encoded for storing in database.\n#### actually:\n\nwhen pivot model loading, values in castable properties will be double encoded and therefore can not be correctly decoded as we expect.\n#10533 and partially #8972\n\n---\n##### how to reproduce:\n- You can clone prepared by me app for demonstrating this issue. https://github.com/evsign/laravelpivotissue.git/\n- Or follow instructions:\n\ncreate new laravel project\n\n```\nphp artisan make:migration create_students_table --create=students \nphp artisan make:migration create_subjects_table --create=subjects\nphp artisan make:migration create_student_subject_table --create=student_subject\nphp artisan make:model Student\nphp artisan make:model Subject\nphp artisan make:model StudentSubjectPivot\n```\n\nMigrations\n\n``` php\nstudents:\n $table->increments('id');\n $table->string('name');\n $table->string('email');\n $table->timestamps();\nsubjects:\n $table->increments('id');\n $table->string('name');\n $table->string('description');\n $table->timestamps();\nstudent_subject:\n $table->unsignedInteger('student_id');\n $table->unsignedInteger('subject_id');\n $table->text('marks'); //or $table->json('marks');\n $table->timestamps();\n```\n\nStudent.php model\n\n``` php\n<?php\n\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Student extends Model\n{\n protected $fillable = [\n 'name',\n 'email'\n ];\n\n public function subjects()\n {\n return $this->belongsToMany('App\\Subject')->withPivot('marks');\n }\n\n public function newPivot(Model $parent, array $attributes, $table, $exists)\n {\n if ($parent instanceof Subject) {\n return new StudentSubjectPivot($parent, $attributes, $table, $exists);\n }\n\n return parent::newPivot($parent, $attributes, $table, $exists);\n }\n}\n```\n\nSubject.php model\n\n``` php\n<?php\n\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Subject extends Model\n{\n protected $fillable = [\n 'name',\n 'description'\n ];\n\n public function students()\n {\n return $this->belongsToMany('App\\Student')->withPivot('marks');\n }\n\n public function newPivot(Model $parent, array $attributes, $table, $exists)\n {\n if ($parent instanceof Student) {\n return new StudentSubjectPivot($parent, $attributes, $table, $exists);\n }\n\n return parent::newPivot($parent, $attributes, $table, $exists);\n }\n}\n```\n\nStudentSubjectPivot.php model\n\n``` php\n<?php\n\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Relations\\Pivot;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass StudentSubjectPivot extends Pivot\n{\n protected $casts = [\n 'marks' => 'array'\n ];\n\n}\n```\n\nThen fill database with test data including pivot marks column with json\n\n``` php\n$student = App\\Student::create(['name' => 'evsign', 'email' => 'evsign@live.ru']);\n$subject = App\\Subject::create(['name' => 'mathematics', 'description' => 'language of the universe']);\n$student->subjects()->attach([$subject->id => [ 'marks' => '[{\"date\":\"2009-12-29 03:01:18\",\"mark\":\"D\"},{\"date\":\"2009-12-29 03:00:40\",\"mark\":\"F\"},{\"date\":\"2009-12-29 03:01:00\",\"mark\":\"B\"},{\"date\":\"2009-12-29 03:00:33\",\"mark\":\"C\"},{\"date\":\"2009-12-29 03:01:09\",\"mark\":\"A\"},{\"date\":\"2009-12-29 03:00:27\",\"mark\":\"A\"},{\"date\":\"2009-12-29 03:00:37\",\"mark\":\"A\"},{\"date\":\"2009-12-29 03:00:25\",\"mark\":\"F\"}]']]);\ndd(App\\Student::find($student->id)->subjects()->first()->pivot->marks); // will be string instead of array\n```\n\n---\n### For fix this issue\n\nUse accessors and mutators with checking values\n\nor\n\nI suggest to send and check values for `array` or `object` in isJsonCastable function in `Illuminate\\Database\\Eloquen\\Model.php`. :relaxed:\n", "number": 12013, "review_comments": [], "title": "[5.2] Checking value in isJsonCastable function" }
{ "commits": [ { "message": "Checking value in isJsonCastable function" }, { "message": "Adding check for object in isJsonCastable" } ], "files": [ { "diff": "@@ -2840,11 +2840,13 @@ protected function isDateCastable($key)\n * Determine whether a value is JSON castable for inbound manipulation.\n *\n * @param string $key\n+ * @param mixed $value\n * @return bool\n */\n- protected function isJsonCastable($key)\n+ protected function isJsonCastable($key, $value)\n {\n- return $this->hasCast($key, ['array', 'json', 'object', 'collection']);\n+ return $this->hasCast($key, ['array', 'json', 'object', 'collection']) &&\n+ (is_array($value) || is_object($value));\n }\n \n /**\n@@ -2926,7 +2928,7 @@ public function setAttribute($key, $value)\n $value = $this->fromDateTime($value);\n }\n \n- if ($this->isJsonCastable($key) && ! is_null($value)) {\n+ if ($this->isJsonCastable($key, $value) && ! is_null($value)) {\n $value = $this->asJson($value);\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" } ] }
{ "body": "When creating a model that extends Eloquent and has a connection using the sqlsrv driver, if you set the table property to be a MSSQL table-value function it can't run any queries because it wraps the function in square brackets and crahes with \"SQLSTATE[HY000]: General error: 208 General SQL Server error: Check messages from the SQL Server\"\n\nMeaning if set the table property to \n\nmyTableValueFunction()\n\nthe query that runs later uses\n\n...from [myTableValueFunction()]\n\nIf the query was instead \n\n...from [myTableValueFunction]()\n\nthen it would work. Even\n\n...from myTableValueFunction()\n\nwould work.\n", "comments": [ { "body": "We're open to PRs.\n", "created_at": "2015-12-23T23:38:54Z" }, { "body": "@Murtnowski do you expect to pass bindings to the table valued function in the from clause?\n\nfor example :\n\n``` php\n\\DB::table('myTableValueFunction(?,?)', [1,2])->get();\n```\n\nThat would require a lot of changes, but for the case without bindings I have it working, I am just waiting for another PR to be merged/closed to commit it \n\n(I don't know how to commit to a different PR, tried to find in the docs but here [ https://help.github.com/articles/using-pull-requests/ ] it says: **_\"After you send a pull request, any commit that's pushed to your branch will be automatically added to your pull request...\"**_)\n", "created_at": "2015-12-28T12:52:30Z" }, { "body": "Nevermind, I commited to another branch and merged it as a different PR\n", "created_at": "2015-12-28T13:11:59Z" }, { "body": "@rodrigopedra Right now I'm just trying to use it in a Eloquent model\n\nSee this to understand what the model looks like http://pastebin.com/nxY37Zz5\n\nSo i'm not directly using the DB functions nor do I need to pass anything into the table-value function.\n", "created_at": "2015-12-28T15:52:32Z" } ], "number": 11493, "title": "[5.1] Eloquent with sqlsrv connection can't use Table-valued Functions as Table" }
{ "body": "Closes #11493 \n", "number": 11575, "review_comments": [ { "body": "We normally put scalars after objects in phpdoc.\n", "created_at": "2015-12-28T17:31:55Z" }, { "body": "`\\Illuminate\\Database\\Query\\Expression|string`\n", "created_at": "2015-12-28T17:32:08Z" }, { "body": "I copied it from https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Grammar.php#L27-L33\n\nWant me to fix it there too?\n", "created_at": "2015-12-28T17:34:49Z" } ], "title": "[5.1] SQL Server: Accept Table-Valued Function as table name" }
{ "commits": [ { "message": "[5.1] SQL Server: Accept Table-Valued Function as table name" } ], "files": [ { "diff": "@@ -315,4 +315,22 @@ public function compileUpdate(Builder $query, $values)\n \n return trim(\"update {$table}{$joins} set $columns $where\");\n }\n+\n+ /**\n+ * Wrap a table in keyword identifiers.\n+ *\n+ * @param \\Illuminate\\Database\\Query\\Expression|string $table\n+ * @return string\n+ */\n+ public function wrapTable($table)\n+ {\n+ $table = parent::wrapTable($table);\n+\n+ // check if the table is defined as a table-valued function\n+ if (preg_match('/^(.+?)(\\(.*?\\))]$/', $table, $matches) === 1) {\n+ $table = $matches[1].']'.$matches[2];\n+ }\n+\n+ return $table;\n+ }\n }", "filename": "src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -1343,6 +1343,17 @@ public function testCaseInsensitiveLeadingBooleansAreRemoved()\n $this->assertEquals('select * from \"users\" where \"name\" = ?', $builder->toSql());\n }\n \n+ public function testTableValuedFunctionAsTableInSqlServer()\n+ {\n+ $builder = $this->getSqlServerBuilder();\n+ $builder->select('*')->from('users()');\n+ $this->assertEquals('select * from [users]()', $builder->toSql());\n+\n+ $builder = $this->getSqlServerBuilder();\n+ $builder->select('*')->from('users(1,2)');\n+ $this->assertEquals('select * from [users](1,2)', $builder->toSql());\n+ }\n+\n protected function getBuilder()\n {\n $grammar = new Illuminate\\Database\\Query\\Grammars\\Grammar;", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "When creating a model that extends Eloquent and has a connection using the sqlsrv driver, if you set the table property to be a MSSQL table-value function it can't run any queries because it wraps the function in square brackets and crahes with \"SQLSTATE[HY000]: General error: 208 General SQL Server error: Check messages from the SQL Server\"\n\nMeaning if set the table property to \n\nmyTableValueFunction()\n\nthe query that runs later uses\n\n...from [myTableValueFunction()]\n\nIf the query was instead \n\n...from [myTableValueFunction]()\n\nthen it would work. Even\n\n...from myTableValueFunction()\n\nwould work.\n", "comments": [ { "body": "We're open to PRs.\n", "created_at": "2015-12-23T23:38:54Z" }, { "body": "@Murtnowski do you expect to pass bindings to the table valued function in the from clause?\n\nfor example :\n\n``` php\n\\DB::table('myTableValueFunction(?,?)', [1,2])->get();\n```\n\nThat would require a lot of changes, but for the case without bindings I have it working, I am just waiting for another PR to be merged/closed to commit it \n\n(I don't know how to commit to a different PR, tried to find in the docs but here [ https://help.github.com/articles/using-pull-requests/ ] it says: **_\"After you send a pull request, any commit that's pushed to your branch will be automatically added to your pull request...\"**_)\n", "created_at": "2015-12-28T12:52:30Z" }, { "body": "Nevermind, I commited to another branch and merged it as a different PR\n", "created_at": "2015-12-28T13:11:59Z" }, { "body": "@rodrigopedra Right now I'm just trying to use it in a Eloquent model\n\nSee this to understand what the model looks like http://pastebin.com/nxY37Zz5\n\nSo i'm not directly using the DB functions nor do I need to pass anything into the table-value function.\n", "created_at": "2015-12-28T15:52:32Z" } ], "number": 11493, "title": "[5.1] Eloquent with sqlsrv connection can't use Table-valued Functions as Table" }
{ "body": "Closes #11493 \n", "number": 11573, "review_comments": [], "title": "[5.1] SQL Server: Accept Table-Valued Function as table name" }
{ "commits": [ { "message": "Merge pull request #11146 from AdenFraser/patch-1\n\n[5.2] Add a validator helper as a shorthand for Validate::make()" }, { "message": "unify behavior of toArray when dates are in casts and date arrays.\"" }, { "message": "Merge remote-tracking branch 'origin/5.2' into 5.2" }, { "message": "first and last item should be null if there are no results." }, { "message": "current page should never be adjusted to somethign its not because it gives weird json results." }, { "message": "Have pagination resolve sane defaults from input page." }, { "message": "Merge branch '5.1' into 5.2" }, { "message": "Merge branch 'cleanup' of https://github.com/acasar/framework into acasar-cleanup" }, { "message": "mild formatting" }, { "message": "Merge branch '5.2' of https://github.com/timfeid/framework-1 into timfeid-5.2" }, { "message": "code formatting" }, { "message": "fix conflicts" }, { "message": "Merge branch '5.1' into 5.2" }, { "message": "Provides a generic rate limiting middleware for the core." }, { "message": "Rename to ThrottleRequest." }, { "message": "Move method to trait." }, { "message": "Merge branch '5.1' into 5.2" }, { "message": "use sha1" }, { "message": "change wording" }, { "message": "fix tests" }, { "message": "Applied fixes from StyleCI" }, { "message": "Merge pull request #11252 from laravel/analysis-qvvOxq\n\nApplied fixes from StyleCI" }, { "message": "Merge branch '5.1' into 5.2" }, { "message": "Merge branch '5.2' of https://github.com/laravel/framework into 5.2" }, { "message": "Use random_int rather than mt_rand" }, { "message": "Use sha1 rather than md5" }, { "message": "Merge branch '5.1' into 5.2" }, { "message": "Merge pull request #11256 from GrahamForks/sha1\n\n[5.2] Use sha1 rather than md5" }, { "message": "Merge pull request #11251 from GrahamForks/rand\n\n[5.2] Use random_int rather than mt_rand" }, { "message": "Speed up service manifest loading." } ], "files": [ { "diff": "", "filename": ".gitattributes", "status": "modified" }, { "diff": "", "filename": ".gitignore", "status": "modified" }, { "diff": "", "filename": ".travis.yml", "status": "modified" }, { "diff": "", "filename": "CONTRIBUTING.md", "status": "modified" }, { "diff": "@@ -29,31 +29,30 @@ split()\n popd\n }\n \n-split auth src/Illuminate/Auth:git@github.com:illuminate/auth.git \"master 5.0 4.2\"\n-split broadcasting src/Illuminate/Broadcasting:git@github.com:illuminate/broadcasting.git \"master\"\n-split bus src/Illuminate/Bus:git@github.com:illuminate/bus.git \"master 5.0\"\n-split cache src/Illuminate/Cache:git@github.com:illuminate/cache.git \"master 5.0 4.2\"\n-split config src/Illuminate/Config:git@github.com:illuminate/config.git \"master 5.0 4.2\"\n-split console src/Illuminate/Console:git@github.com:illuminate/console.git \"master 5.0 4.2\"\n-split container src/Illuminate/Container:git@github.com:illuminate/container.git \"master 5.0 4.2\"\n-split contracts src/Illuminate/Contracts:git@github.com:illuminate/contracts.git \"master 5.0\"\n-split cookie src/Illuminate/Cookie:git@github.com:illuminate/cookie.git \"master 5.0 4.2\"\n-split database src/Illuminate/Database:git@github.com:illuminate/database.git \"master 5.0 4.2\"\n-split encryption src/Illuminate/Encryption:git@github.com:illuminate/encryption.git \"master 5.0 4.2\"\n-split events src/Illuminate/Events:git@github.com:illuminate/events.git \"master 5.0 4.2\"\n-split exception src/Illuminate/Exception:git@github.com:illuminate/exception.git \"4.2\"\n-split filesystem src/Illuminate/Filesystem:git@github.com:illuminate/filesystem.git \"master 5.0 4.2\"\n-split hashing src/Illuminate/Hashing:git@github.com:illuminate/hashing.git \"master 5.0 4.2\"\n-split http src/Illuminate/Http:git@github.com:illuminate/http.git \"master 5.0 4.2\"\n-split log src/Illuminate/Log:git@github.com:illuminate/log.git \"master 5.0 4.2\"\n-split mail src/Illuminate/Mail:git@github.com:illuminate/mail.git \"master 5.0 4.2\"\n-split pagination src/Illuminate/Pagination:git@github.com:illuminate/pagination.git \"master 5.0 4.2\"\n-split pipeline src/Illuminate/Pipeline:git@github.com:illuminate/pipeline.git \"master 5.0\"\n-split queue src/Illuminate/Queue:git@github.com:illuminate/queue.git \"master 5.0 4.2\"\n-split redis src/Illuminate/Redis:git@github.com:illuminate/redis.git \"master 5.0 4.2\"\n-split routing src/Illuminate/Routing:git@github.com:illuminate/routing.git \"master 5.0 4.2\"\n-split session src/Illuminate/Session:git@github.com:illuminate/session.git \"master 5.0 4.2\"\n-split support src/Illuminate/Support:git@github.com:illuminate/support.git \"master 5.0 4.2\"\n-split translation src/Illuminate/Translation:git@github.com:illuminate/translation.git \"master 5.0 4.2\"\n-split validation src/Illuminate/Validation:git@github.com:illuminate/validation.git \"master 5.0 4.2\"\n-split view src/Illuminate/View:git@github.com:illuminate/view.git \"master 5.0 4.2\"\n+split auth src/Illuminate/Auth:git@github.com:illuminate/auth.git \"master 5.1 5.0\"\n+split broadcasting src/Illuminate/Broadcasting:git@github.com:illuminate/broadcasting.git \"master 5.1\"\n+split bus src/Illuminate/Bus:git@github.com:illuminate/bus.git \"master 5.1 5.0\"\n+split cache src/Illuminate/Cache:git@github.com:illuminate/cache.git \"master 5.1 5.0\"\n+split config src/Illuminate/Config:git@github.com:illuminate/config.git \"master 5.1 5.0\"\n+split console src/Illuminate/Console:git@github.com:illuminate/console.git \"master 5.1 5.0\"\n+split container src/Illuminate/Container:git@github.com:illuminate/container.git \"master 5.1 5.0\"\n+split contracts src/Illuminate/Contracts:git@github.com:illuminate/contracts.git \"master 5.1 5.0\"\n+split cookie src/Illuminate/Cookie:git@github.com:illuminate/cookie.git \"master 5.1 5.0\"\n+split database src/Illuminate/Database:git@github.com:illuminate/database.git \"master 5.1 5.0\"\n+split encryption src/Illuminate/Encryption:git@github.com:illuminate/encryption.git \"master 5.1 5.0\"\n+split events src/Illuminate/Events:git@github.com:illuminate/events.git \"master 5.1 5.0\"\n+split filesystem src/Illuminate/Filesystem:git@github.com:illuminate/filesystem.git \"master 5.1 5.0\"\n+split hashing src/Illuminate/Hashing:git@github.com:illuminate/hashing.git \"master 5.1 5.0\"\n+split http src/Illuminate/Http:git@github.com:illuminate/http.git \"master 5.1 5.0\"\n+split log src/Illuminate/Log:git@github.com:illuminate/log.git \"master 5.1 5.0\"\n+split mail src/Illuminate/Mail:git@github.com:illuminate/mail.git \"master 5.1 5.0\"\n+split pagination src/Illuminate/Pagination:git@github.com:illuminate/pagination.git \"master 5.1 5.0\"\n+split pipeline src/Illuminate/Pipeline:git@github.com:illuminate/pipeline.git \"master 5.1 5.0\"\n+split queue src/Illuminate/Queue:git@github.com:illuminate/queue.git \"master 5.1 5.0\"\n+split redis src/Illuminate/Redis:git@github.com:illuminate/redis.git \"master 5.1 5.0\"\n+split routing src/Illuminate/Routing:git@github.com:illuminate/routing.git \"master 5.1 5.0\"\n+split session src/Illuminate/Session:git@github.com:illuminate/session.git \"master 5.1 5.0\"\n+split support src/Illuminate/Support:git@github.com:illuminate/support.git \"master 5.1 5.0\"\n+split translation src/Illuminate/Translation:git@github.com:illuminate/translation.git \"master 5.1 5.0\"\n+split validation src/Illuminate/Validation:git@github.com:illuminate/validation.git \"master 5.1 5.0\"\n+split view src/Illuminate/View:git@github.com:illuminate/view.git \"master 5.1 5.0\"", "filename": "build/illuminate-split-faster.sh", "status": "modified" }, { "diff": "@@ -1,29 +1,29 @@\n git subsplit init git@github.com:laravel/framework.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Auth:git@github.com:illuminate/auth.git\n-git subsplit publish --heads=\"master 5.0\" src/Illuminate/Bus:git@github.com:illuminate/bus.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Cache:git@github.com:illuminate/cache.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Config:git@github.com:illuminate/config.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Console:git@github.com:illuminate/console.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Container:git@github.com:illuminate/container.git\n-git subsplit publish --heads=\"master 5.0\" src/Illuminate/Contracts:git@github.com:illuminate/contracts.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Cookie:git@github.com:illuminate/cookie.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Database:git@github.com:illuminate/database.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Encryption:git@github.com:illuminate/encryption.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Events:git@github.com:illuminate/events.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Exception:git@github.com:illuminate/exception.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Filesystem:git@github.com:illuminate/filesystem.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Hashing:git@github.com:illuminate/hashing.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Http:git@github.com:illuminate/http.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Log:git@github.com:illuminate/log.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Mail:git@github.com:illuminate/mail.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Pagination:git@github.com:illuminate/pagination.git\n-git subsplit publish --heads=\"master 5.0\" src/Illuminate/Pipeline:git@github.com:illuminate/pipeline.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Queue:git@github.com:illuminate/queue.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Redis:git@github.com:illuminate/redis.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Routing:git@github.com:illuminate/routing.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Session:git@github.com:illuminate/session.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Support:git@github.com:illuminate/support.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Translation:git@github.com:illuminate/translation.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/Validation:git@github.com:illuminate/validation.git\n-git subsplit publish --heads=\"master 5.0 4.2\" src/Illuminate/View:git@github.com:illuminate/view.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Auth:git@github.com:illuminate/auth.git\n+git subsplit publish --heads=\"master 5.1\" src/Illuminate/Bus:git@github.com:illuminate/broadcasting.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Bus:git@github.com:illuminate/bus.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Cache:git@github.com:illuminate/cache.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Config:git@github.com:illuminate/config.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Console:git@github.com:illuminate/console.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Container:git@github.com:illuminate/container.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Contracts:git@github.com:illuminate/contracts.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Cookie:git@github.com:illuminate/cookie.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Database:git@github.com:illuminate/database.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Encryption:git@github.com:illuminate/encryption.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Events:git@github.com:illuminate/events.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Filesystem:git@github.com:illuminate/filesystem.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Hashing:git@github.com:illuminate/hashing.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Http:git@github.com:illuminate/http.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Log:git@github.com:illuminate/log.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Mail:git@github.com:illuminate/mail.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Pagination:git@github.com:illuminate/pagination.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Pipeline:git@github.com:illuminate/pipeline.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Queue:git@github.com:illuminate/queue.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Redis:git@github.com:illuminate/redis.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Routing:git@github.com:illuminate/routing.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Session:git@github.com:illuminate/session.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Support:git@github.com:illuminate/support.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Translation:git@github.com:illuminate/translation.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/Validation:git@github.com:illuminate/validation.git\n+git subsplit publish --heads=\"master 5.1 5.0\" src/Illuminate/View:git@github.com:illuminate/view.git\n rm -rf .subsplit/", "filename": "build/illuminate-split-full.sh", "status": "modified" }, { "diff": "@@ -1,29 +1,29 @@\n git subsplit init git@github.com:laravel/framework.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Auth:git@github.com:illuminate/auth.git\n-git subsplit publish --heads=\"master 5.0\" --no-tags src/Illuminate/Bus:git@github.com:illuminate/bus.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Cache:git@github.com:illuminate/cache.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Config:git@github.com:illuminate/config.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Console:git@github.com:illuminate/console.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Container:git@github.com:illuminate/container.git\n-git subsplit publish --heads=\"master 5.0\" --no-tags src/Illuminate/Contracts:git@github.com:illuminate/contracts.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Cookie:git@github.com:illuminate/cookie.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Database:git@github.com:illuminate/database.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Encryption:git@github.com:illuminate/encryption.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Events:git@github.com:illuminate/events.git\n-git subsplit publish --heads=\"4.2\" --no-tags src/Illuminate/Exception:git@github.com:illuminate/exception.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Filesystem:git@github.com:illuminate/filesystem.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Hashing:git@github.com:illuminate/hashing.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Http:git@github.com:illuminate/http.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Log:git@github.com:illuminate/log.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Mail:git@github.com:illuminate/mail.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Pagination:git@github.com:illuminate/pagination.git\n-git subsplit publish --heads=\"master 5.0\" --no-tags src/Illuminate/Pipeline:git@github.com:illuminate/pipeline.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Queue:git@github.com:illuminate/queue.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Redis:git@github.com:illuminate/redis.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Routing:git@github.com:illuminate/routing.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Session:git@github.com:illuminate/session.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Support:git@github.com:illuminate/support.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Translation:git@github.com:illuminate/translation.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/Validation:git@github.com:illuminate/validation.git\n-git subsplit publish --heads=\"master 5.0 4.2\" --no-tags src/Illuminate/View:git@github.com:illuminate/view.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Auth:git@github.com:illuminate/auth.git\n+git subsplit publish --heads=\"master 5.1\" --no-tags src/Illuminate/Bus:git@github.com:illuminate/broadcasting.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Bus:git@github.com:illuminate/bus.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Cache:git@github.com:illuminate/cache.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Config:git@github.com:illuminate/config.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Console:git@github.com:illuminate/console.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Container:git@github.com:illuminate/container.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Contracts:git@github.com:illuminate/contracts.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Cookie:git@github.com:illuminate/cookie.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Database:git@github.com:illuminate/database.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Encryption:git@github.com:illuminate/encryption.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Events:git@github.com:illuminate/events.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Filesystem:git@github.com:illuminate/filesystem.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Hashing:git@github.com:illuminate/hashing.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Http:git@github.com:illuminate/http.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Log:git@github.com:illuminate/log.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Mail:git@github.com:illuminate/mail.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Pagination:git@github.com:illuminate/pagination.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Pipeline:git@github.com:illuminate/pipeline.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Queue:git@github.com:illuminate/queue.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Redis:git@github.com:illuminate/redis.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Routing:git@github.com:illuminate/routing.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Session:git@github.com:illuminate/session.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Support:git@github.com:illuminate/support.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Translation:git@github.com:illuminate/translation.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/Validation:git@github.com:illuminate/validation.git\n+git subsplit publish --heads=\"master 5.1 5.0\" --no-tags src/Illuminate/View:git@github.com:illuminate/view.git\n rm -rf .subsplit/", "filename": "build/illuminate-split.sh", "status": "modified" }, { "diff": "@@ -18,29 +18,27 @@\n \"php\": \">=5.5.9\",\n \"ext-mbstring\": \"*\",\n \"ext-openssl\": \"*\",\n- \"classpreloader/classpreloader\": \"~2.0|~3.0\",\n- \"danielstjules/stringy\": \"~1.8\",\n+ \"classpreloader/classpreloader\": \"~3.0\",\n \"doctrine/inflector\": \"~1.0\",\n- \"jeremeamia/superclosure\": \"~2.0\",\n+ \"jeremeamia/superclosure\": \"~2.2\",\n \"league/flysystem\": \"~1.0\",\n \"monolog/monolog\": \"~1.11\",\n \"mtdowling/cron-expression\": \"~1.0\",\n- \"nesbot/carbon\": \"~1.19\",\n+ \"nesbot/carbon\": \"~1.20\",\n \"paragonie/random_compat\": \"~1.1\",\n \"psy/psysh\": \"0.6.*\",\n \"swiftmailer/swiftmailer\": \"~5.1\",\n- \"symfony/console\": \"2.7.*\",\n- \"symfony/css-selector\": \"2.7.*\",\n- \"symfony/debug\": \"2.7.*\",\n- \"symfony/dom-crawler\": \"2.7.*\",\n- \"symfony/finder\": \"2.7.*\",\n- \"symfony/http-foundation\": \"2.7.*\",\n- \"symfony/http-kernel\": \"2.7.*\",\n- \"symfony/process\": \"2.7.*\",\n- \"symfony/routing\": \"2.7.*\",\n- \"symfony/translation\": \"2.7.*\",\n- \"symfony/var-dumper\": \"2.7.*\",\n- \"vlucas/phpdotenv\": \"~1.0\"\n+ \"symfony/console\": \"2.8.*|3.0.*\",\n+ \"symfony/debug\": \"2.8.*|3.0.*\",\n+ \"symfony/finder\": \"2.8.*|3.0.*\",\n+ \"symfony/http-foundation\": \"2.8.*|3.0.*\",\n+ \"symfony/http-kernel\": \"2.8.*|3.0.*\",\n+ \"symfony/polyfill-php56\": \"~1.0\",\n+ \"symfony/process\": \"2.8.*|3.0.*\",\n+ \"symfony/routing\": \"2.8.*|3.0.*\",\n+ \"symfony/translation\": \"2.8.*|3.0.*\",\n+ \"symfony/var-dumper\": \"2.8.*|3.0.*\",\n+ \"vlucas/phpdotenv\": \"~2.0\"\n },\n \"replace\": {\n \"illuminate/auth\": \"self.version\",\n@@ -74,11 +72,12 @@\n },\n \"require-dev\": {\n \"aws/aws-sdk-php\": \"~3.0\",\n- \"iron-io/iron_mq\": \"~2.0\",\n \"mockery/mockery\": \"~0.9.2\",\n \"pda/pheanstalk\": \"~3.0\",\n- \"phpunit/phpunit\": \"~4.0\",\n- \"predis/predis\": \"~1.0\"\n+ \"phpunit/phpunit\": \"~4.1\",\n+ \"predis/predis\": \"~1.0\",\n+ \"symfony/css-selector\": \"2.8.*|3.0.*\",\n+ \"symfony/dom-crawler\": \"2.8.*|3.0.*\"\n },\n \"autoload\": {\n \"classmap\": [\n@@ -94,20 +93,21 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"5.1-dev\"\n+ \"dev-master\": \"5.2-dev\"\n }\n },\n \"suggest\": {\n \"aws/aws-sdk-php\": \"Required to use the SQS queue driver and SES mail driver (~3.0).\",\n \"doctrine/dbal\": \"Required to rename columns and drop SQLite columns (~2.4).\",\n \"fzaninotto/faker\": \"Required to use the eloquent factory builder (~1.4).\",\n \"guzzlehttp/guzzle\": \"Required to use the Mailgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).\",\n- \"iron-io/iron_mq\": \"Required to use the iron queue driver (~2.0).\",\n \"league/flysystem-aws-s3-v3\": \"Required to use the Flysystem S3 driver (~1.0).\",\n \"league/flysystem-rackspace\": \"Required to use the Flysystem Rackspace driver (~1.0).\",\n \"pda/pheanstalk\": \"Required to use the beanstalk queue driver (~3.0).\",\n \"predis/predis\": \"Required to use the redis cache and queue drivers (~1.0).\",\n- \"pusher/pusher-php-server\": \"Required to use the Pusher broadcast driver (~2.0).\"\n+ \"pusher/pusher-php-server\": \"Required to use the Pusher broadcast driver (~2.0).\",\n+ \"symfony/css-selector\": \"Required to use some of the crawler integration testing tools (2.8.*|3.0.*).\",\n+ \"symfony/dom-crawler\": \"Required to use most of the crawler integration testing tools (2.8.*|3.0.*).\"\n },\n \"minimum-stability\": \"dev\"\n }", "filename": "composer.json", "status": "modified" }, { "diff": "", "filename": "phpunit.php", "status": "modified" }, { "diff": "", "filename": "phpunit.xml", "status": "modified" }, { "diff": "", "filename": "readme.md", "status": "modified" }, { "diff": "@@ -197,7 +197,7 @@ public function check($ability, $arguments = [])\n {\n try {\n $result = $this->raw($ability, $arguments);\n- } catch (UnauthorizedException $e) {\n+ } catch (AuthorizationException $e) {\n return false;\n }\n \n@@ -211,7 +211,7 @@ public function check($ability, $arguments = [])\n * @param array|mixed $arguments\n * @return \\Illuminate\\Auth\\Access\\Response\n *\n- * @throws \\Illuminate\\Auth\\Access\\UnauthorizedException\n+ * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n */\n public function authorize($ability, $arguments = [])\n {", "filename": "src/Illuminate/Auth/Access/Gate.php", "status": "modified" }, { "diff": "@@ -21,10 +21,10 @@ protected function allow($message = null)\n * @param string $message\n * @return void\n *\n- * @throws \\Illuminate\\Auth\\Access\\UnauthorizedException\n+ * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n */\n protected function deny($message = 'This action is unauthorized.')\n {\n- throw new UnauthorizedException($message);\n+ throw new AuthorizationException($message);\n }\n }", "filename": "src/Illuminate/Auth/Access/HandlesAuthorization.php", "status": "modified" }, { "diff": "@@ -2,20 +2,106 @@\n \n namespace Illuminate\\Auth;\n \n-use Illuminate\\Support\\Manager;\n-use Illuminate\\Contracts\\Auth\\Guard as GuardContract;\n+use Closure;\n+use InvalidArgumentException;\n+use Illuminate\\Contracts\\Auth\\Factory as FactoryContract;\n \n-class AuthManager extends Manager\n+class AuthManager implements FactoryContract\n {\n+ use CreatesUserProviders;\n+\n /**\n- * Create a new driver instance.\n+ * The application instance.\n *\n- * @param string $driver\n+ * @var \\Illuminate\\Foundation\\Application\n+ */\n+ protected $app;\n+\n+ /**\n+ * The registered custom driver creators.\n+ *\n+ * @var array\n+ */\n+ protected $customCreators = [];\n+\n+ /**\n+ * The array of created \"drivers\".\n+ *\n+ * @var array\n+ */\n+ protected $guards = [];\n+\n+ /**\n+ * Create a new Auth manager instance.\n+ *\n+ * @param \\Illuminate\\Foundation\\Application $app\n+ * @return void\n+ */\n+ public function __construct($app)\n+ {\n+ $this->app = $app;\n+ }\n+\n+ /**\n+ * Attempt to get the guard from the local cache.\n+ *\n+ * @param string $name\n+ * @return \\Illuminate\\Contracts\\Auth\\Guard|\\Illuminate\\Contracts\\Auth\\StatefulGuard\n+ */\n+ public function guard($name = null)\n+ {\n+ $name = $name ?: $this->getDefaultDriver();\n+\n+ return isset($this->guards[$name])\n+ ? $this->guards[$name]\n+ : $this->guards[$name] = $this->resolve($name);\n+ }\n+\n+ /**\n+ * Resolve the given guard.\n+ *\n+ * @param string $name\n+ * @return \\Illuminate\\Contracts\\Auth\\Guard|\\Illuminate\\Contracts\\Auth\\StatefulGuard\n+ */\n+ protected function resolve($name)\n+ {\n+ $config = $this->getConfig($name);\n+\n+ if (is_null($config)) {\n+ throw new InvalidArgumentException(\"Auth guard [{$name}] is not defined.\");\n+ }\n+\n+ if (isset($this->customCreators[$config['driver']])) {\n+ return $this->callCustomCreator($name, $config);\n+ } else {\n+ return $this->{'create'.ucfirst($config['driver']).'Driver'}($name, $config);\n+ }\n+ }\n+\n+ /**\n+ * Call a custom driver creator.\n+ *\n+ * @param string $name\n+ * @param array $config\n * @return mixed\n */\n- protected function createDriver($driver)\n+ protected function callCustomCreator($name, array $config)\n {\n- $guard = parent::createDriver($driver);\n+ return $this->customCreators[$config['driver']]($this->app, $name, $config);\n+ }\n+\n+ /**\n+ * Create a session based authentication guard.\n+ *\n+ * @param string $name\n+ * @param array $config\n+ * @return \\Illuminate\\Auth\\SessionGuard\n+ */\n+ public function createSessionDriver($name, $config)\n+ {\n+ $provider = $this->createUserProvider($config['provider']);\n+\n+ $guard = new SessionGuard($name, $provider, $this->app['session.store']);\n \n // When using the remember me functionality of the authentication services we\n // will need to be set the encryption instance of the guard, which allows\n@@ -36,93 +122,125 @@ protected function createDriver($driver)\n }\n \n /**\n- * Call a custom driver creator.\n+ * Create a token based authentication guard.\n *\n- * @param string $driver\n- * @return \\Illuminate\\Contracts\\Auth\\Guard\n+ * @param string $name\n+ * @param array $config\n+ * @return \\Illuminate\\Auth\\TokenGuard\n */\n- protected function callCustomCreator($driver)\n+ public function createTokenDriver($name, $config)\n {\n- $custom = parent::callCustomCreator($driver);\n+ // The token guard implemetns a basic API token based guard implementation\n+ // that takes an API token field from the request and matches it to the\n+ // user in the database or another persistence layer where users are.\n+ $guard = new TokenGuard(\n+ $this->createUserProvider($config['provider']),\n+ $this->app['request']\n+ );\n \n- if ($custom instanceof GuardContract) {\n- return $custom;\n- }\n+ $this->app->refresh('request', $guard, 'setRequest');\n \n- return new Guard($custom, $this->app['session.store']);\n+ return $guard;\n }\n \n /**\n- * Create an instance of the database driver.\n+ * Get the guard configuration.\n *\n- * @return \\Illuminate\\Auth\\Guard\n+ * @param string $name\n+ * @return array\n */\n- public function createDatabaseDriver()\n+ protected function getConfig($name)\n {\n- $provider = $this->createDatabaseProvider();\n-\n- return new Guard($provider, $this->app['session.store']);\n+ return $this->app['config'][\"auth.guards.{$name}\"];\n }\n \n /**\n- * Create an instance of the database user provider.\n+ * Get the default authentication driver name.\n *\n- * @return \\Illuminate\\Auth\\DatabaseUserProvider\n+ * @return string\n */\n- protected function createDatabaseProvider()\n+ public function getDefaultDriver()\n {\n- $connection = $this->app['db']->connection();\n+ return $this->app['config']['auth.defaults.guard'];\n+ }\n \n- // When using the basic database user provider, we need to inject the table we\n- // want to use, since this is not an Eloquent model we will have no way to\n- // know without telling the provider, so we'll inject the config value.\n- $table = $this->app['config']['auth.table'];\n+ /**\n+ * Set the default guard driver the factory should serve.\n+ *\n+ * @param string $name\n+ * @return void\n+ */\n+ public function shouldUse($name)\n+ {\n+ return $this->setDefaultDriver($name);\n+ }\n \n- return new DatabaseUserProvider($connection, $this->app['hash'], $table);\n+ /**\n+ * Set the default authentication driver name.\n+ *\n+ * @param string $name\n+ * @return void\n+ */\n+ public function setDefaultDriver($name)\n+ {\n+ $this->app['config']['auth.defaults.guard'] = $name;\n }\n \n /**\n- * Create an instance of the Eloquent driver.\n+ * Register a new callback based request guard.\n *\n- * @return \\Illuminate\\Auth\\Guard\n+ * @param string $driver\n+ * @param callable $callback\n+ * @return $this\n */\n- public function createEloquentDriver()\n+ public function viaRequest($driver, callable $callback)\n {\n- $provider = $this->createEloquentProvider();\n+ return $this->extend($driver, function () use ($callback) {\n+ $guard = new RequestGuard($callback, $this->app['request']);\n+\n+ $this->app->refresh('request', $guard, 'setRequest');\n \n- return new Guard($provider, $this->app['session.store']);\n+ return $guard;\n+ });\n }\n \n /**\n- * Create an instance of the Eloquent user provider.\n+ * Register a custom driver creator Closure.\n *\n- * @return \\Illuminate\\Auth\\EloquentUserProvider\n+ * @param string $driver\n+ * @param \\Closure $callback\n+ * @return $this\n */\n- protected function createEloquentProvider()\n+ public function extend($driver, Closure $callback)\n {\n- $model = $this->app['config']['auth.model'];\n+ $this->customCreators[$driver] = $callback;\n \n- return new EloquentUserProvider($this->app['hash'], $model);\n+ return $this;\n }\n \n /**\n- * Get the default authentication driver name.\n+ * Register a custom provider creator Closure.\n *\n- * @return string\n+ * @param string $name\n+ * @param \\Closure $callback\n+ * @return $this\n */\n- public function getDefaultDriver()\n+ public function provider($name, Closure $callback)\n {\n- return $this->app['config']['auth.driver'];\n+ $this->customProviderCreators[$name] = $callback;\n+\n+ return $this;\n }\n \n /**\n- * Set the default authentication driver name.\n+ * Dynamically call the default driver instance.\n *\n- * @param string $name\n- * @return void\n+ * @param string $method\n+ * @param array $parameters\n+ * @return mixed\n */\n- public function setDefaultDriver($name)\n+ public function __call($method, $parameters)\n {\n- $this->app['config']['auth.driver'] = $name;\n+ return call_user_func_array([$this->guard(), $method], $parameters);\n }\n }", "filename": "src/Illuminate/Auth/AuthManager.php", "status": "modified" }, { "diff": "@@ -42,7 +42,7 @@ protected function registerAuthenticator()\n });\n \n $this->app->singleton('auth.driver', function ($app) {\n- return $app['auth']->driver();\n+ return $app['auth']->guard();\n });\n }\n ", "filename": "src/Illuminate/Auth/AuthServiceProvider.php", "status": "modified" }, { "diff": "@@ -4,6 +4,16 @@\n \n trait Authenticatable\n {\n+ /**\n+ * Get the name of the unique identifier for the user.\n+ *\n+ * @return string\n+ */\n+ public function getAuthIdentifierName()\n+ {\n+ return $this->getKeyName();\n+ }\n+\n /**\n * Get the unique identifier for the user.\n *", "filename": "src/Illuminate/Auth/Authenticatable.php", "status": "modified" }, { "diff": "@@ -0,0 +1,105 @@\n+<?php\n+\n+namespace Illuminate\\Auth\\Console;\n+\n+use Illuminate\\Console\\Command;\n+\n+class MakeAuthCommand extends Command\n+{\n+ /**\n+ * The name and signature of the console command.\n+ *\n+ * @var string\n+ */\n+ protected $signature = 'make:auth {--views : Only scaffold the authentication views}';\n+\n+ /**\n+ * The console command description.\n+ *\n+ * @var string\n+ */\n+ protected $description = 'Scaffold basic login and registration views and routes';\n+\n+ /**\n+ * THe views that need to be exported.\n+ *\n+ * @var array\n+ */\n+ protected $views = [\n+ 'auth/login.stub' => 'auth/login.blade.php',\n+ 'auth/register.stub' => 'auth/register.blade.php',\n+ 'auth/passwords/email.stub' => 'auth/passwords/email.blade.php',\n+ 'auth/passwords/reset.stub' => 'auth/passwords/reset.blade.php',\n+ 'auth/emails/password.stub' => 'auth/emails/password.blade.php',\n+ 'layouts/app.stub' => 'layouts/app.blade.php',\n+ 'home.stub' => 'home.blade.php',\n+ 'welcome.stub' => 'welcome.blade.php',\n+ ];\n+\n+ /**\n+ * Execute the console command.\n+ *\n+ * @return void\n+ */\n+ public function fire()\n+ {\n+ $this->createDirectories();\n+\n+ $this->exportViews();\n+\n+ if (! $this->option('views')) {\n+ $this->info('Installed HomeController.');\n+\n+ copy(\n+ __DIR__.'/stubs/make/controllers/HomeController.stub',\n+ app_path('Http/Controllers/HomeController.php')\n+ );\n+\n+ $this->info('Updated Routes File.');\n+\n+ file_put_contents(\n+ app_path('Http/routes.php'),\n+ file_get_contents(__DIR__.'/stubs/make/routes.stub'),\n+ FILE_APPEND\n+ );\n+ }\n+\n+ $this->comment('Authentication scaffolding generated successfully!');\n+ }\n+\n+ /**\n+ * Create the directories for the files.\n+ *\n+ * @return void\n+ */\n+ protected function createDirectories()\n+ {\n+ if (! is_dir(base_path('resources/views/layouts'))) {\n+ mkdir(base_path('resources/views/layouts'), 0755, true);\n+ }\n+\n+ if (! is_dir(base_path('resources/views/auth/passwords'))) {\n+ mkdir(base_path('resources/views/auth/passwords'), 0755, true);\n+ }\n+\n+ if (! is_dir(base_path('resources/views/auth/emails'))) {\n+ mkdir(base_path('resources/views/auth/emails'), 0755, true);\n+ }\n+ }\n+\n+ /**\n+ * Export the authentication views.\n+ *\n+ * @return void\n+ */\n+ protected function exportViews()\n+ {\n+ foreach ($this->views as $key => $value) {\n+ $path = base_path('resources/views/'.$value);\n+\n+ $this->line('<info>Created View:</info> '.$path);\n+\n+ copy(__DIR__.'/stubs/make/views/'.$key, $path);\n+ }\n+ }\n+}", "filename": "src/Illuminate/Auth/Console/MakeAuthCommand.php", "status": "added" }, { "diff": "@@ -0,0 +1,29 @@\n+<?php\n+\n+namespace App\\Http\\Controllers;\n+\n+use App\\Http\\Requests;\n+use Illuminate\\Http\\Request;\n+\n+class HomeController extends Controller\n+{\n+ /**\n+ * Create a new controller instance.\n+ *\n+ * @return void\n+ */\n+ public function __construct()\n+ {\n+ $this->middleware('auth');\n+ }\n+\n+ /**\n+ * Show the application dashboard.\n+ *\n+ * @return Response\n+ */\n+ public function index()\n+ {\n+ return view('home');\n+ }\n+}", "filename": "src/Illuminate/Auth/Console/stubs/make/controllers/HomeController.stub", "status": "added" }, { "diff": "@@ -0,0 +1,6 @@\n+\n+Route::group(['middleware' => 'web'], function () {\n+ Route::auth();\n+\n+ Route::get('/home', 'HomeController@index');\n+});", "filename": "src/Illuminate/Auth/Console/stubs/make/routes.stub", "status": "added" }, { "diff": "@@ -0,0 +1 @@\n+Click here to reset your password: {{ url('password/reset/'.$token) }}", "filename": "src/Illuminate/Auth/Console/stubs/make/views/auth/emails/password.stub", "status": "added" }, { "diff": "@@ -0,0 +1,66 @@\n+@extends('layouts.app')\n+\n+@section('content')\n+<div class=\"container\">\n+ <div class=\"row\">\n+ <div class=\"col-md-8 col-md-offset-2\">\n+ <div class=\"panel panel-default\">\n+ <div class=\"panel-heading\">Login</div>\n+ <div class=\"panel-body\">\n+ <form class=\"form-horizontal\" role=\"form\" method=\"POST\" action=\"{{ url('/login') }}\">\n+ {!! csrf_field() !!}\n+\n+ <div class=\"form-group{{ $errors->has('email') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">E-Mail Address</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"email\" class=\"form-control\" name=\"email\" value=\"{{ old('email') }}\">\n+\n+ @if ($errors->has('email'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('email') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group{{ $errors->has('password') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">Password</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"password\" class=\"form-control\" name=\"password\">\n+\n+ @if ($errors->has('password'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('password') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group\">\n+ <div class=\"col-md-6 col-md-offset-4\">\n+ <div class=\"checkbox\">\n+ <label>\n+ <input type=\"checkbox\" name=\"remember\"> Remember Me\n+ </label>\n+ </div>\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group\">\n+ <div class=\"col-md-6 col-md-offset-4\">\n+ <button type=\"submit\" class=\"btn btn-primary\">\n+ <i class=\"fa fa-btn fa-sign-in\"></i>Login\n+ </button>\n+\n+ <a class=\"btn btn-link\" href=\"{{ url('/password/reset') }}\">Forgot Your Password?</a>\n+ </div>\n+ </div>\n+ </form>\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</div>\n+@endsection", "filename": "src/Illuminate/Auth/Console/stubs/make/views/auth/login.stub", "status": "added" }, { "diff": "@@ -0,0 +1,47 @@\n+@extends('layouts.app')\n+\n+<!-- Main Content -->\n+@section('content')\n+<div class=\"container\">\n+ <div class=\"row\">\n+ <div class=\"col-md-8 col-md-offset-2\">\n+ <div class=\"panel panel-default\">\n+ <div class=\"panel-heading\">Reset Password</div>\n+ <div class=\"panel-body\">\n+ @if (session('status'))\n+ <div class=\"alert alert-success\">\n+ {{ session('status') }}\n+ </div>\n+ @endif\n+\n+ <form class=\"form-horizontal\" role=\"form\" method=\"POST\" action=\"{{ url('/password/email') }}\">\n+ {!! csrf_field() !!}\n+\n+ <div class=\"form-group{{ $errors->has('email') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">E-Mail Address</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"email\" class=\"form-control\" name=\"email\" value=\"{{ old('email') }}\">\n+\n+ @if ($errors->has('email'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('email') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group\">\n+ <div class=\"col-md-6 col-md-offset-4\">\n+ <button type=\"submit\" class=\"btn btn-primary\">\n+ <i class=\"fa fa-btn fa-envelope\"></i>Send Password Reset Link\n+ </button>\n+ </div>\n+ </div>\n+ </form>\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</div>\n+@endsection", "filename": "src/Illuminate/Auth/Console/stubs/make/views/auth/passwords/email.stub", "status": "added" }, { "diff": "@@ -0,0 +1,70 @@\n+@extends('layouts.app')\n+\n+@section('content')\n+<div class=\"container\">\n+ <div class=\"row\">\n+ <div class=\"col-md-8 col-md-offset-2\">\n+ <div class=\"panel panel-default\">\n+ <div class=\"panel-heading\">Reset Password</div>\n+\n+ <div class=\"panel-body\">\n+ <form class=\"form-horizontal\" role=\"form\" method=\"POST\" action=\"{{ url('/password/reset') }}\">\n+ {!! csrf_field() !!}\n+\n+ <input type=\"hidden\" name=\"token\" value=\"{{ $token }}\">\n+\n+ <div class=\"form-group{{ $errors->has('email') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">E-Mail Address</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"email\" class=\"form-control\" name=\"email\" value=\"{{ old('email') }}\">\n+\n+ @if ($errors->has('email'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('email') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group{{ $errors->has('password') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">Password</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"password\" class=\"form-control\" name=\"password\">\n+\n+ @if ($errors->has('password'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('password') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">Confirm Password</label>\n+ <div class=\"col-md-6\">\n+ <input type=\"password\" class=\"form-control\" name=\"password_confirmation\">\n+\n+ @if ($errors->has('password_confirmation'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('password_confirmation') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group\">\n+ <div class=\"col-md-6 col-md-offset-4\">\n+ <button type=\"submit\" class=\"btn btn-primary\">\n+ <i class=\"fa fa-btn fa-refresh\"></i>Reset Password\n+ </button>\n+ </div>\n+ </div>\n+ </form>\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</div>\n+@endsection", "filename": "src/Illuminate/Auth/Console/stubs/make/views/auth/passwords/reset.stub", "status": "added" }, { "diff": "@@ -0,0 +1,82 @@\n+@extends('layouts.app')\n+\n+@section('content')\n+<div class=\"container\">\n+ <div class=\"row\">\n+ <div class=\"col-md-8 col-md-offset-2\">\n+ <div class=\"panel panel-default\">\n+ <div class=\"panel-heading\">Register</div>\n+ <div class=\"panel-body\">\n+ <form class=\"form-horizontal\" role=\"form\" method=\"POST\" action=\"{{ url('/register') }}\">\n+ {!! csrf_field() !!}\n+\n+ <div class=\"form-group{{ $errors->has('name') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">Name</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"text\" class=\"form-control\" name=\"name\" value=\"{{ old('name') }}\">\n+\n+ @if ($errors->has('name'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('name') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group{{ $errors->has('email') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">E-Mail Address</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"email\" class=\"form-control\" name=\"email\" value=\"{{ old('email') }}\">\n+\n+ @if ($errors->has('email'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('email') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group{{ $errors->has('password') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">Password</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"password\" class=\"form-control\" name=\"password\">\n+\n+ @if ($errors->has('password'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('password') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}\">\n+ <label class=\"col-md-4 control-label\">Confirm Password</label>\n+\n+ <div class=\"col-md-6\">\n+ <input type=\"password\" class=\"form-control\" name=\"password_confirmation\">\n+\n+ @if ($errors->has('password_confirmation'))\n+ <span class=\"help-block\">\n+ <strong>{{ $errors->first('password_confirmation') }}</strong>\n+ </span>\n+ @endif\n+ </div>\n+ </div>\n+\n+ <div class=\"form-group\">\n+ <div class=\"col-md-6 col-md-offset-4\">\n+ <button type=\"submit\" class=\"btn btn-primary\">\n+ <i class=\"fa fa-btn fa-user\"></i>Register\n+ </button>\n+ </div>\n+ </div>\n+ </form>\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</div>\n+@endsection", "filename": "src/Illuminate/Auth/Console/stubs/make/views/auth/register.stub", "status": "added" }, { "diff": "@@ -0,0 +1,17 @@\n+@extends('layouts.app')\n+\n+@section('content')\n+<div class=\"container spark-screen\">\n+ <div class=\"row\">\n+ <div class=\"col-md-10 col-md-offset-1\">\n+ <div class=\"panel panel-default\">\n+ <div class=\"panel-heading\">Dashboard</div>\n+\n+ <div class=\"panel-body\">\n+ You are logged in!\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</div>\n+@endsection", "filename": "src/Illuminate/Auth/Console/stubs/make/views/home.stub", "status": "added" }, { "diff": "@@ -0,0 +1,82 @@\n+<!DOCTYPE html>\n+<html lang=\"en\">\n+<head>\n+ <meta charset=\"utf-8\">\n+ <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n+ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n+\n+ <title>Laravel</title>\n+\n+ <!-- Fonts -->\n+ <link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css\" rel='stylesheet' type='text/css'>\n+ <link href=\"https://fonts.googleapis.com/css?family=Lato:100,300,400,700\" rel='stylesheet' type='text/css'>\n+\n+ <!-- Styles -->\n+ {{-- <link href=\"{{ elixir('css/app.css') }}\" rel=\"stylesheet\"> --}}\n+ <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n+\n+ <style>\n+ body {\n+ font-family: 'Lato';\n+ }\n+\n+ .fa-btn {\n+ margin-right: 6px;\n+ }\n+ </style>\n+</head>\n+<body id=\"app-layout\">\n+ <nav class=\"navbar navbar-default\">\n+ <div class=\"container\">\n+ <div class=\"navbar-header\">\n+\n+ <!-- Collapsed Hamburger -->\n+ <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#spark-navbar-collapse\">\n+ <span class=\"sr-only\">Toggle Navigation</span>\n+ <span class=\"icon-bar\"></span>\n+ <span class=\"icon-bar\"></span>\n+ <span class=\"icon-bar\"></span>\n+ </button>\n+\n+ <!-- Branding Image -->\n+ <a class=\"navbar-brand\" href=\"{{ url('/') }}\">\n+ Laravel\n+ </a>\n+ </div>\n+\n+ <div class=\"collapse navbar-collapse\" id=\"spark-navbar-collapse\">\n+ <!-- Left Side Of Navbar -->\n+ <ul class=\"nav navbar-nav\">\n+ <li><a href=\"{{ url('/') }}\">Home</a></li>\n+ </ul>\n+\n+ <!-- Right Side Of Navbar -->\n+ <ul class=\"nav navbar-nav navbar-right\">\n+ <!-- Authentication Links -->\n+ @if (Auth::guest())\n+ <li><a href=\"{{ url('/login') }}\">Login</a></li>\n+ <li><a href=\"{{ url('/register') }}\">Register</a></li>\n+ @else\n+ <li class=\"dropdown\">\n+ <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-expanded=\"false\">\n+ {{ Auth::user()->name }} <span class=\"caret\"></span>\n+ </a>\n+\n+ <ul class=\"dropdown-menu\" role=\"menu\">\n+ <li><a href=\"{{ url('/logout') }}\"><i class=\"fa fa-btn fa-sign-out\"></i>Logout</a></li>\n+ </ul>\n+ </li>\n+ @endif\n+ </ul>\n+ </div>\n+ </div>\n+ </nav>\n+\n+ @yield('content')\n+\n+ <!-- JavaScripts -->\n+ {{-- <script src=\"{{ elixir('js/app.js') }}\"></script> --}}\n+ <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js\"></script>\n+ <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n+</body>\n+</html>", "filename": "src/Illuminate/Auth/Console/stubs/make/views/layouts/app.stub", "status": "added" }, { "diff": "@@ -0,0 +1,17 @@\n+@extends('layouts.app')\n+\n+@section('content')\n+<div class=\"container spark-screen\">\n+ <div class=\"row\">\n+ <div class=\"col-md-10 col-md-offset-1\">\n+ <div class=\"panel panel-default\">\n+ <div class=\"panel-heading\">Welcome</div>\n+\n+ <div class=\"panel-body\">\n+ Your Application's Landing Page.\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</div>\n+@endsection", "filename": "src/Illuminate/Auth/Console/stubs/make/views/welcome.stub", "status": "added" }, { "diff": "@@ -0,0 +1,67 @@\n+<?php\n+\n+namespace Illuminate\\Auth;\n+\n+use InvalidArgumentException;\n+\n+trait CreatesUserProviders\n+{\n+ /**\n+ * The registered custom provider creators.\n+ *\n+ * @var array\n+ */\n+ protected $customProviderCreators = [];\n+\n+ /**\n+ * Create the user provider implementation for the driver.\n+ *\n+ * @param string $provider\n+ * @return \\Illuminate\\Contracts\\Auth\\UserProvider\n+ *\n+ * @throws \\InvalidArgumentException\n+ */\n+ public function createUserProvider($provider)\n+ {\n+ $config = $this->app['config']['auth.providers.'.$provider];\n+\n+ if (isset($this->customProviderCreators[$config['driver']])) {\n+ return call_user_func(\n+ $this->customProviderCreators[$config['driver']], $this->app, $config\n+ );\n+ }\n+\n+ switch ($config['driver']) {\n+ case 'database':\n+ return $this->createDatabaseProvider($config);\n+ case 'eloquent':\n+ return $this->createEloquentProvider($config);\n+ default:\n+ throw new InvalidArgumentException(\"Authentication user provider [{$config['driver']}] is not defined.\");\n+ }\n+ }\n+\n+ /**\n+ * Create an instance of the database user provider.\n+ *\n+ * @param array $config\n+ * @return \\Illuminate\\Auth\\DatabaseUserProvider\n+ */\n+ protected function createDatabaseProvider($config)\n+ {\n+ $connection = $this->app['db']->connection();\n+\n+ return new DatabaseUserProvider($connection, $this->app['hash'], $config['table']);\n+ }\n+\n+ /**\n+ * Create an instance of the Eloquent user provider.\n+ *\n+ * @param array $config\n+ * @return \\Illuminate\\Auth\\EloquentUserProvider\n+ */\n+ protected function createEloquentProvider($config)\n+ {\n+ return new EloquentUserProvider($this->app['hash'], $config['model']);\n+ }\n+}", "filename": "src/Illuminate/Auth/CreatesUserProviders.php", "status": "added" }, { "diff": "@@ -59,7 +59,7 @@ public function retrieveByToken($identifier, $token)\n $model = $this->createModel();\n \n return $model->newQuery()\n- ->where($model->getKeyName(), $identifier)\n+ ->where($model->getAuthIdentifierName(), $identifier)\n ->where($model->getRememberTokenName(), $token)\n ->first();\n }", "filename": "src/Illuminate/Auth/EloquentUserProvider.php", "status": "modified" } ] }
{ "body": "Ever since i've updated to 5.2 from 5.1 I get an error when my task runs saying that emailOutputTo can't find the file I'm writing to with sendOutputTo.\n\n```\nlive.ERROR: exception 'ErrorException' with message 'file_get_contents('/home/mysite/site/storage/logs/cron_deletetempfiles_2015_12_25.txt'): failed to open stream: No such file or directory' in /home/mysite/site/vendor/laravel/framework/src/Illuminate/Console/Scheduling/Event.php:710\n```\n\nCode I'm using in app/Console/Kernel.php is\n\n``` php\n$schedule->command('deletetempfiles')\n ->daily()\n ->sendOutputTo(storage_path().'/logs/cron_deletetempfiles_'.date('Y_m_d').'.txt')\n ->emailOutputTo('myemail');\n```\n\nI checked and the file exists and has the proper info in it.\n", "comments": [ { "body": "That's probably a side effect of `sendOutputTo` change\nI'll look into this tomorrow\n", "created_at": "2015-12-24T23:51:04Z" }, { "body": "Thank you very much for the report @neamtua. @arrilot Thanks. :snowman: \n", "created_at": "2015-12-25T01:35:13Z" }, { "body": "> Ever since i've updated to 5.2 from 5.1\n\nActually, this bug is present on 5.1 too. You must have just been using an older version of 5.1.\n", "created_at": "2015-12-25T19:38:21Z" } ], "number": 11517, "title": "[5.1] [5.2] Bug with task scheduling when using emailOutputTo()" }
{ "body": "Closes #11517\n\nI've managed to replicate the issue and test it locally\n\nWe added output path escaping in late 5.1.\\* version.\n\nBut it should not be escaped in setter because some other stuff want to use it as it is.\nFor example `file_get_contents()` in `emailOutputTo()` doesn't play nice with escaped path.\n\nEscaping right before building a crontab command is much safer.\n\nWe really lack test coverage here, but all those `file_get_contents` are not easy to test. \n\nSigh.\n", "number": 11526, "review_comments": [], "title": "[5.1] Escape path directly in build command" }
{ "commits": [ { "message": "Escape path directly in build command" } ], "files": [ { "diff": "@@ -212,12 +212,13 @@ protected function callAfterCallbacks(Container $container)\n */\n public function buildCommand()\n {\n+ $output = ProcessUtils::escapeArgument($this->output);\n $redirect = $this->shouldAppendOutput ? ' >> ' : ' > ';\n \n if ($this->withoutOverlapping) {\n- $command = '(touch '.$this->mutexPath().'; '.$this->command.'; rm '.$this->mutexPath().')'.$redirect.$this->output.' 2>&1 &';\n+ $command = '(touch '.$this->mutexPath().'; '.$this->command.'; rm '.$this->mutexPath().')'.$redirect.$output.' 2>&1 &';\n } else {\n- $command = $this->command.$redirect.$this->output.' 2>&1 &';\n+ $command = $this->command.$redirect.$output.' 2>&1 &';\n }\n \n return $this->user ? 'sudo -u '.$this->user.' '.$command : $command;\n@@ -653,7 +654,7 @@ public function skip(Closure $callback)\n */\n public function sendOutputTo($location, $append = false)\n {\n- $this->output = ProcessUtils::escapeArgument($location);\n+ $this->output = $location;\n \n $this->shouldAppendOutput = $append;\n ", "filename": "src/Illuminate/Console/Scheduling/Event.php", "status": "modified" }, { "diff": "@@ -9,7 +9,7 @@ public function testBuildCommand()\n $event = new Event('php -i');\n \n $defaultOutput = (DIRECTORY_SEPARATOR == '\\\\') ? 'NUL' : '/dev/null';\n- $this->assertSame(\"php -i > {$defaultOutput} 2>&1 &\", $event->buildCommand());\n+ $this->assertSame(\"php -i > '{$defaultOutput}' 2>&1 &\", $event->buildCommand());\n }\n \n public function testBuildCommandSendOutputTo()\n@@ -32,4 +32,15 @@ public function testBuildCommandAppendOutput()\n $event->appendOutputTo('/dev/null');\n $this->assertSame(\"php -i >> '/dev/null' 2>&1 &\", $event->buildCommand());\n }\n+\n+ /**\n+ * @expectedException LogicException\n+ */\n+ public function testEmailOutputToThrowsExceptionIfOutputFileWasNotSpecified()\n+ {\n+ $event = new Event('php -i');\n+ $event->emailOutputTo('foo@example.com');\n+\n+ $event->buildCommand();\n+ }\n }", "filename": "tests/Console/Scheduling/EventTest.php", "status": "modified" } ] }
{ "body": "I've come across a bug when trying to update a database in a migration using `chunk` where some records aren't being saved. In our case we're adding a nullable column, setting the values for that column and then making it nullable within a single migration. Using `chunk` though attempting to remove the `nullable` option from the column would throw an error because some records didn't have the values set.\n\nI've created a minimal example to show this off - https://github.com/EspadaV8/laravel-chunking-non-persistance/tree/develop - cloning this and running `php artisan migrate:refresh --seed` should produce something like the following output\n\n```\nEmpty example table\n+----+------+----------+\n| id | name | new-name |\n+----+------+----------+\n\nPopulated example table with `name`\n+----+------------+----------+\n| id | name | new-name |\n+----+------------+----------+\n| 1 | mM4YJMR3i2 | |\n| 2 | ZYNNY6DBqi | |\n| 3 | okKt4kIARY | |\n| 4 | VHJ6ni85c8 | |\n+----+------------+----------+\n\nPopulated example table with `name-new` using `chuck`\n+----+------------+----------------+\n| id | name | new-name |\n+----+------------+----------------+\n| 1 | mM4YJMR3i2 | mM4YJMR3i2-new |\n| 2 | ZYNNY6DBqi | ZYNNY6DBqi-new |\n| 3 | okKt4kIARY | okKt4kIARY-new |\n| 4 | VHJ6ni85c8 | |\n+----+------------+----------------+\n```\n\nThe one row without a `new-name` set should've been set in the second `chunk` batch.\n", "comments": [ { "body": "Are you able to send a PR please?\n", "created_at": "2015-12-19T22:49:05Z" }, { "body": "I did try having a go at fixing this but I wasn't able to work out where the issue is. If I get a chance to have another look at it I'll see if I can submit something (if you have any pointers as to where to start looking that'd be great).\r\n", "created_at": "2015-12-20T12:48:45Z" }, { "body": "Made a slight change to the seeder so that it appends to the `name-new` column instead of just setting it to a known value and it now produces the following output\n\n```\nespadav8@dolores:~/Workspace/chunking-non-persistance (*)\n> php artisan migrate:refresh --seed develop [7fd9127] modified\nRolled back: 2015_12_10_235952_create_tables\nMigrated: 2015_12_10_235952_create_tables\n\nEmpty example table\n+----+------+----------+\n| id | name | name-new |\n+----+------+----------+\n\nPopulated example table with `name`\n+----+------------+------------+\n| id | name | name-new |\n+----+------------+------------+\n| 1 | kVmjtZUXTH | ZoerIsEvoZ |\n| 2 | 0VkvI2TSIF | DZ1R4Joz26 |\n| 3 | TKaJTOiVzH | W3eOttRChc |\n| 4 | bS6TeDg3xB | DJgjzlQBX5 |\n+----+------------+------------+\n\nPopulated example table with `name-new` using `chuck`\n+----+------------+--------------------+\n| id | name | name-new |\n+----+------------+--------------------+\n| 1 | kVmjtZUXTH | ZoerIsEvoZ-new |\n| 2 | 0VkvI2TSIF | DZ1R4Joz26-new |\n| 3 | TKaJTOiVzH | W3eOttRChc-new-new |\n| 4 | bS6TeDg3xB | DJgjzlQBX5 |\n+----+------------+--------------------+\n```\n\nFor some reason the second `chunk` call returns just 1 record, but it's a record that's already been returned (in this case record 3).\n\nIt looks like the queries that are being created are correct (`$this->forPage($page, $count)->toSql()`)\n\n``` sql\nselect * from \"example\" limit 3 offset 0;\nselect * from \"example\" limit 3 offset 3;\nselect * from \"example\" limit 3 offset 6;\n```\n", "created_at": "2015-12-20T22:40:21Z" }, { "body": "Looks like this might actually be an issue with the postgresql PDO driver. I've submitted it to PHP - https://bugs.php.net/bug.php?id=71176. There's a new script I've added that only uses PDO and shows the same kind of output\n\nhttps://github.com/EspadaV8/laravel-chunking-non-persistance/blob/develop/public/pg-pdo-test.php\n", "created_at": "2015-12-20T23:30:34Z" }, { "body": "So, that bug was closed as `Not a bug`. It looks like it's expected behaviour, at least with postgresql - http://www.postgresql.org/docs/current/static/queries-limit.html\n\nBecause the `chunk` doesn't have any kind of `ORDER BY` the results can be returned in any order. The simple fix would be to `ORDER BY` the primary key (unless something else has been set). Does that sound like an okay fix for you @GrahamCampbell ?\n", "created_at": "2015-12-21T02:14:15Z" }, { "body": "Feel free to send a PR, and we'll review it.\n", "created_at": "2015-12-21T10:53:45Z" }, { "body": "I managed to lose a comment here somehow :confused:\n\nTo have `chunk` use an `ORDER BY` it would need to know what the primary key for a table is, however, there's no way of knowing that within the `Builder` class. It could check to see if an `ORDER BY` has been set and try to use `id` but that could fail, or it could throw an exception if no `ORDER BY` has been set.\n\nNeither of those sound too nice to me. Is there another way that I might be missing that you can think of?\n", "created_at": "2015-12-22T10:08:01Z" }, { "body": "@EspadaV8 You can call `$this->model->getKeyName()` in the Builder to get the primary key column. Does that help?\n", "created_at": "2015-12-22T17:15:27Z" }, { "body": "As far as I know, the Builder doesn't have a reference to an particular model since it can be used by itself. Something like... \n\n```\nDB::table('users')->chunk(...);\n```\n\nDoesn't know what columns are in that table or what the tables primary key is. Currently it will work but in an unsupported way since is should require an `orderBy`. \n", "created_at": "2015-12-23T07:40:42Z" }, { "body": "Well, eloquent Builder does, query builder doesn't. Both have chunk method.\n", "created_at": "2015-12-23T07:50:53Z" }, { "body": "Ah, okay. I was talking about the query builder in this case. The issue could exist within the eloquent builder too though.\n", "created_at": "2015-12-23T11:01:16Z" }, { "body": "What actually needs fixing then?\n", "created_at": "2015-12-30T13:32:50Z" }, { "body": "I still think that the `chunk` method should require an `order by` clause as recommended by both the postgresql and MySQL docs. I wanted to do a quick test of what @taylorotwell mentioned in his comment https://github.com/laravel/framework/pull/11510#issuecomment-167334145 because I don't think you can do any kind of `chunk` when the where includes a field that you are updating because the second call would then skip a whole chunk that are now the records at offset 0 (so you would need to force the offset to 0 for each call).\n\nIf there isn't to be a change to force an order by then I could update to docs to add a warning recommending that an order by be included. \n", "created_at": "2015-12-30T13:46:25Z" }, { "body": "> I still think that the chunk method should require an order by clause as recommended by both the postgresql and MySQL docs.\n\nThat's not a bug though. You just add an orderby...\n", "created_at": "2015-12-30T13:51:56Z" }, { "body": "EspadaV8, I'm not particularly familiar with how the query builder's internal work, but it appears that at least in MySQL, one can sort by _rowid, which I think might fix the issue and may be something that could automatically be appended to queries even when you don't know the primary key's.\n\nI don't know if this is what you're looking for, though. I'm pretty new to the internals of Laravel, and don't know if doing special casing based on the database type is something that may be done in the query builder or not.\n", "created_at": "2016-01-06T05:34:20Z" }, { "body": "If it's not going to be changed, then it should be noted in the Laravel docs.\n", "created_at": "2016-03-24T16:47:41Z" }, { "body": "We're open to PRs to the docs. Thank you everyone! :heart:\n", "created_at": "2016-06-17T14:55:56Z" }, { "body": "I had submitted https://github.com/laravel/docs/pull/2227, but it wasn't committed in its entirety. Taylor committed my changes to the sample code for chunk() to include orderBy(), but not the explanation about _why_ one should use orderBy() with chunk(). I can write a more complete explanation if that would help. I just think leaving this issue out there without any explanation is creating confusion.\n", "created_at": "2016-07-26T18:18:29Z" } ], "number": 11302, "title": "[5.1] [5.2] Error with `chunk` not saving second batch" }
{ "body": "This is in reference to #11302 \n\nThis change makes sure that before chunking the results an `orderBy` has been set. If nothing was set by the user then the function will default to setting it to `id`. This can cause issues if a table doesn't have an `id` field.\n\nThe alternative would be to throw an exception if no `orderBy` has been set, but that would possibly be a huge breaking change.\n\nI've added some tests to make sure that an `order by` statement is added to the SQL that's generated, but I'm not sure if the tests cover enough (there currently aren't any tests at all for the `chunk` method).\n\nI'm open to all suggestions as to better/different ways to fix this.\n\nRelated to: #11490, #11489 \n", "number": 11510, "review_comments": [ { "body": "please use the is_null function\n", "created_at": "2015-12-24T13:46:09Z" }, { "body": "Please import this class.\n", "created_at": "2015-12-24T13:46:27Z" }, { "body": "same.\n", "created_at": "2015-12-24T13:46:36Z" }, { "body": "don#t make this uneeded method\n", "created_at": "2015-12-24T13:47:08Z" }, { "body": "just write `$property = $this->unions ? 'unionOrders' : 'orders';`\n", "created_at": "2015-12-24T13:47:24Z" }, { "body": "Did you mean `getOrderBys`???\n", "created_at": "2015-12-24T14:14:40Z" }, { "body": "Please include a leading slash.\n", "created_at": "2015-12-25T01:35:38Z" }, { "body": "Same\n", "created_at": "2015-12-25T01:35:44Z" } ], "title": "[5.3] Chunk should require orderBy" }
{ "commits": [ { "message": "Throw an exception when chunking without setting an orderBy" } ], "files": [ { "diff": "@@ -10,6 +10,7 @@\n use Illuminate\\Pagination\\LengthAwarePaginator;\n use Illuminate\\Database\\Eloquent\\Relations\\Relation;\n use Illuminate\\Database\\Query\\Builder as QueryBuilder;\n+use RuntimeException;\n \n class Builder\n {\n@@ -261,9 +262,15 @@ public function value($column)\n * @param int $count\n * @param callable $callback\n * @return void\n+ *\n+ * @throws \\RuntimeException\n */\n public function chunk($count, callable $callback)\n {\n+ if (is_null($this->getOrderBys())) {\n+ throw new RuntimeException('Chunk requires an orderby clause.');\n+ }\n+\n $results = $this->forPage($page = 1, $count)->get();\n \n while (count($results) > 0) {", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -14,6 +14,7 @@\n use Illuminate\\Database\\Query\\Grammars\\Grammar;\n use Illuminate\\Pagination\\LengthAwarePaginator;\n use Illuminate\\Database\\Query\\Processors\\Processor;\n+use RuntimeException;\n \n class Builder\n {\n@@ -1545,9 +1546,15 @@ protected function restoreFieldsForCount()\n * @param int $count\n * @param callable $callback\n * @return bool\n+ *\n+ * @throws \\RuntimeException\n */\n public function chunk($count, callable $callback)\n {\n+ if (is_null($this->getOrderBys())) {\n+ throw new RuntimeException('Chunk requires an orderby clause.');\n+ }\n+\n $results = $this->forPage($page = 1, $count)->get();\n \n while (count($results) > 0) {\n@@ -1566,6 +1573,18 @@ public function chunk($count, callable $callback)\n return true;\n }\n \n+ /**\n+ * Returns the currently set ordering.\n+ *\n+ * @return array|null\n+ */\n+ public function getOrderBys()\n+ {\n+ $property = $this->unions ? 'unionOrders' : 'orders';\n+\n+ return $this->{$property};\n+ }\n+\n /**\n * Get an array with the values of a given column.\n *", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -153,10 +153,11 @@ public function testValueMethodWithModelNotFound()\n \n public function testChunkExecuteCallbackOverPaginatedRequest()\n {\n- $builder = m::mock('Illuminate\\Database\\Eloquent\\Builder[forPage,get]', [$this->getMockQueryBuilder()]);\n+ $builder = m::mock('Illuminate\\Database\\Eloquent\\Builder[forPage,get,getOrderBys]', [$this->getMockQueryBuilder()]);\n $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturn($builder);\n $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturn($builder);\n $builder->shouldReceive('forPage')->once()->with(3, 2)->andReturn($builder);\n+ $builder->shouldReceive('getOrderBys')->once()->with()->andReturn('id');\n $builder->shouldReceive('get')->times(3)->andReturn(['foo1', 'foo2'], ['foo3'], []);\n \n $callbackExecutionAssertor = m::mock('StdClass');\n@@ -173,9 +174,10 @@ public function testChunkExecuteCallbackOverPaginatedRequest()\n \n public function testChunkCanBeStoppedByReturningFalse()\n {\n- $builder = m::mock('Illuminate\\Database\\Eloquent\\Builder[forPage,get]', [$this->getMockQueryBuilder()]);\n+ $builder = m::mock('Illuminate\\Database\\Eloquent\\Builder[forPage,get,getOrderBys]', [$this->getMockQueryBuilder()]);\n $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturn($builder);\n $builder->shouldReceive('forPage')->never()->with(2, 2);\n+ $builder->shouldReceive('getOrderBys')->once()->with()->andReturn('id');\n $builder->shouldReceive('get')->times(1)->andReturn(['foo1', 'foo2']);\n \n $callbackExecutionAssertor = m::mock('StdClass');\n@@ -192,6 +194,17 @@ public function testChunkCanBeStoppedByReturningFalse()\n });\n }\n \n+ /**\n+ * @expectedException \\RuntimeException\n+ */\n+ public function testChunkThrowsExceptionWithoutOrderBy()\n+ {\n+ $builder = m::mock('Illuminate\\Database\\Eloquent\\Builder[getOrderBys]', [$this->getMockQueryBuilder()]);\n+ $builder->shouldReceive('getOrderBys')->once()->with()->andReturn(null);\n+\n+ $builder->chunk(2, function () { return true; });\n+ }\n+\n public function testPluckReturnsTheMutatedAttributesOfAModel()\n {\n $builder = $this->getBuilder();", "filename": "tests/Database/DatabaseEloquentBuilderTest.php", "status": "modified" }, { "diff": "@@ -1356,6 +1356,26 @@ public function testCaseInsensitiveLeadingBooleansAreRemoved()\n $this->assertEquals('select * from \"users\" where \"name\" = ?', $builder->toSql());\n }\n \n+ /**\n+ * @expectedException \\RuntimeException\n+ */\n+ public function testChunkThrowsExceptionWithoutOrderBy()\n+ {\n+ $builder = $this->getBuilder();\n+ $builder->chunk(10, function () { return true; });\n+ }\n+\n+ public function testChunkWithOrderBy()\n+ {\n+ $builder = $this->getBuilder();\n+ $query = 'select * from \"users\" order by \"sort_order\" asc limit 10 offset 0';\n+ $builder->getConnection()->shouldReceive('select')->once()->with($query, [], true)->andReturn([]);\n+ $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturn([]);\n+ $builder->select('*')->from('users')->orderBy('sort_order')->chunk(10, function () {return true; });\n+\n+ $this->assertEquals($query, $builder->toSql());\n+ }\n+\n protected function getBuilder()\n {\n $grammar = new Illuminate\\Database\\Query\\Grammars\\Grammar;", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "I've come across a bug when trying to update a database in a migration using `chunk` where some records aren't being saved. In our case we're adding a nullable column, setting the values for that column and then making it nullable within a single migration. Using `chunk` though attempting to remove the `nullable` option from the column would throw an error because some records didn't have the values set.\n\nI've created a minimal example to show this off - https://github.com/EspadaV8/laravel-chunking-non-persistance/tree/develop - cloning this and running `php artisan migrate:refresh --seed` should produce something like the following output\n\n```\nEmpty example table\n+----+------+----------+\n| id | name | new-name |\n+----+------+----------+\n\nPopulated example table with `name`\n+----+------------+----------+\n| id | name | new-name |\n+----+------------+----------+\n| 1 | mM4YJMR3i2 | |\n| 2 | ZYNNY6DBqi | |\n| 3 | okKt4kIARY | |\n| 4 | VHJ6ni85c8 | |\n+----+------------+----------+\n\nPopulated example table with `name-new` using `chuck`\n+----+------------+----------------+\n| id | name | new-name |\n+----+------------+----------------+\n| 1 | mM4YJMR3i2 | mM4YJMR3i2-new |\n| 2 | ZYNNY6DBqi | ZYNNY6DBqi-new |\n| 3 | okKt4kIARY | okKt4kIARY-new |\n| 4 | VHJ6ni85c8 | |\n+----+------------+----------------+\n```\n\nThe one row without a `new-name` set should've been set in the second `chunk` batch.\n", "comments": [ { "body": "Are you able to send a PR please?\n", "created_at": "2015-12-19T22:49:05Z" }, { "body": "I did try having a go at fixing this but I wasn't able to work out where the issue is. If I get a chance to have another look at it I'll see if I can submit something (if you have any pointers as to where to start looking that'd be great).\r\n", "created_at": "2015-12-20T12:48:45Z" }, { "body": "Made a slight change to the seeder so that it appends to the `name-new` column instead of just setting it to a known value and it now produces the following output\n\n```\nespadav8@dolores:~/Workspace/chunking-non-persistance (*)\n> php artisan migrate:refresh --seed develop [7fd9127] modified\nRolled back: 2015_12_10_235952_create_tables\nMigrated: 2015_12_10_235952_create_tables\n\nEmpty example table\n+----+------+----------+\n| id | name | name-new |\n+----+------+----------+\n\nPopulated example table with `name`\n+----+------------+------------+\n| id | name | name-new |\n+----+------------+------------+\n| 1 | kVmjtZUXTH | ZoerIsEvoZ |\n| 2 | 0VkvI2TSIF | DZ1R4Joz26 |\n| 3 | TKaJTOiVzH | W3eOttRChc |\n| 4 | bS6TeDg3xB | DJgjzlQBX5 |\n+----+------------+------------+\n\nPopulated example table with `name-new` using `chuck`\n+----+------------+--------------------+\n| id | name | name-new |\n+----+------------+--------------------+\n| 1 | kVmjtZUXTH | ZoerIsEvoZ-new |\n| 2 | 0VkvI2TSIF | DZ1R4Joz26-new |\n| 3 | TKaJTOiVzH | W3eOttRChc-new-new |\n| 4 | bS6TeDg3xB | DJgjzlQBX5 |\n+----+------------+--------------------+\n```\n\nFor some reason the second `chunk` call returns just 1 record, but it's a record that's already been returned (in this case record 3).\n\nIt looks like the queries that are being created are correct (`$this->forPage($page, $count)->toSql()`)\n\n``` sql\nselect * from \"example\" limit 3 offset 0;\nselect * from \"example\" limit 3 offset 3;\nselect * from \"example\" limit 3 offset 6;\n```\n", "created_at": "2015-12-20T22:40:21Z" }, { "body": "Looks like this might actually be an issue with the postgresql PDO driver. I've submitted it to PHP - https://bugs.php.net/bug.php?id=71176. There's a new script I've added that only uses PDO and shows the same kind of output\n\nhttps://github.com/EspadaV8/laravel-chunking-non-persistance/blob/develop/public/pg-pdo-test.php\n", "created_at": "2015-12-20T23:30:34Z" }, { "body": "So, that bug was closed as `Not a bug`. It looks like it's expected behaviour, at least with postgresql - http://www.postgresql.org/docs/current/static/queries-limit.html\n\nBecause the `chunk` doesn't have any kind of `ORDER BY` the results can be returned in any order. The simple fix would be to `ORDER BY` the primary key (unless something else has been set). Does that sound like an okay fix for you @GrahamCampbell ?\n", "created_at": "2015-12-21T02:14:15Z" }, { "body": "Feel free to send a PR, and we'll review it.\n", "created_at": "2015-12-21T10:53:45Z" }, { "body": "I managed to lose a comment here somehow :confused:\n\nTo have `chunk` use an `ORDER BY` it would need to know what the primary key for a table is, however, there's no way of knowing that within the `Builder` class. It could check to see if an `ORDER BY` has been set and try to use `id` but that could fail, or it could throw an exception if no `ORDER BY` has been set.\n\nNeither of those sound too nice to me. Is there another way that I might be missing that you can think of?\n", "created_at": "2015-12-22T10:08:01Z" }, { "body": "@EspadaV8 You can call `$this->model->getKeyName()` in the Builder to get the primary key column. Does that help?\n", "created_at": "2015-12-22T17:15:27Z" }, { "body": "As far as I know, the Builder doesn't have a reference to an particular model since it can be used by itself. Something like... \n\n```\nDB::table('users')->chunk(...);\n```\n\nDoesn't know what columns are in that table or what the tables primary key is. Currently it will work but in an unsupported way since is should require an `orderBy`. \n", "created_at": "2015-12-23T07:40:42Z" }, { "body": "Well, eloquent Builder does, query builder doesn't. Both have chunk method.\n", "created_at": "2015-12-23T07:50:53Z" }, { "body": "Ah, okay. I was talking about the query builder in this case. The issue could exist within the eloquent builder too though.\n", "created_at": "2015-12-23T11:01:16Z" }, { "body": "What actually needs fixing then?\n", "created_at": "2015-12-30T13:32:50Z" }, { "body": "I still think that the `chunk` method should require an `order by` clause as recommended by both the postgresql and MySQL docs. I wanted to do a quick test of what @taylorotwell mentioned in his comment https://github.com/laravel/framework/pull/11510#issuecomment-167334145 because I don't think you can do any kind of `chunk` when the where includes a field that you are updating because the second call would then skip a whole chunk that are now the records at offset 0 (so you would need to force the offset to 0 for each call).\n\nIf there isn't to be a change to force an order by then I could update to docs to add a warning recommending that an order by be included. \n", "created_at": "2015-12-30T13:46:25Z" }, { "body": "> I still think that the chunk method should require an order by clause as recommended by both the postgresql and MySQL docs.\n\nThat's not a bug though. You just add an orderby...\n", "created_at": "2015-12-30T13:51:56Z" }, { "body": "EspadaV8, I'm not particularly familiar with how the query builder's internal work, but it appears that at least in MySQL, one can sort by _rowid, which I think might fix the issue and may be something that could automatically be appended to queries even when you don't know the primary key's.\n\nI don't know if this is what you're looking for, though. I'm pretty new to the internals of Laravel, and don't know if doing special casing based on the database type is something that may be done in the query builder or not.\n", "created_at": "2016-01-06T05:34:20Z" }, { "body": "If it's not going to be changed, then it should be noted in the Laravel docs.\n", "created_at": "2016-03-24T16:47:41Z" }, { "body": "We're open to PRs to the docs. Thank you everyone! :heart:\n", "created_at": "2016-06-17T14:55:56Z" }, { "body": "I had submitted https://github.com/laravel/docs/pull/2227, but it wasn't committed in its entirety. Taylor committed my changes to the sample code for chunk() to include orderBy(), but not the explanation about _why_ one should use orderBy() with chunk(). I can write a more complete explanation if that would help. I just think leaving this issue out there without any explanation is creating confusion.\n", "created_at": "2016-07-26T18:18:29Z" } ], "number": 11302, "title": "[5.1] [5.2] Error with `chunk` not saving second batch" }
{ "body": "This is in reference to #11302 \n\nThis change makes sure that before chunking the results an `orderBy` has been set. If nothing was set by the user then the function will default to setting it to `id`. This can cause issues if a table doesn't have an `id` field.\n\nThe alternative would be to throw an exception if no `orderBy` has been set, but that would possibly be a huge breaking change.\n\nI've added some tests to make sure that an `order by` statement is added to the SQL that's generated, but I'm not sure if the tests cover enough (there currently aren't any tests at all for the `chunk` method).\n\nI'm open to all suggestions as to better/different ways to fix this.\n", "number": 11490, "review_comments": [ { "body": "Laravel normally uses the `is_null` function.\n", "created_at": "2015-12-23T14:31:49Z" } ], "title": "[5.1] [WIP] Chunk should require orderBy" }
{ "commits": [ { "message": "Attempt to set a default orderBy when chunking" } ], "files": [ { "diff": "@@ -1564,6 +1564,10 @@ protected function restoreFieldsForCount()\n */\n public function chunk($count, callable $callback)\n {\n+ if ($this->getOrderBys() === null) {\n+ $this->orderBy('id', 'asc');\n+ }\n+\n $results = $this->forPage($page = 1, $count)->get();\n \n while (count($results) > 0) {\n@@ -1582,6 +1586,18 @@ public function chunk($count, callable $callback)\n return true;\n }\n \n+ /**\n+ * Returns the currently set ordering.\n+ *\n+ * @return array|null\n+ */\n+ public function getOrderBys()\n+ {\n+ $property = $this->unions ? 'unionOrders' : 'orders';\n+\n+ return $this->{$property};\n+ }\n+\n /**\n * Get an array with the values of a given column.\n *", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -1335,6 +1335,28 @@ public function testCaseInsensitiveLeadingBooleansAreRemoved()\n $this->assertEquals('select * from \"users\" where \"name\" = ?', $builder->toSql());\n }\n \n+ public function testChunkWithoutOrderBy()\n+ {\n+ $builder = $this->getBuilder();\n+ $query = 'select * from \"users\" order by \"id\" asc limit 10 offset 0';\n+ $builder->getConnection()->shouldReceive('select')->once()->with($query, [], true)->andReturn([]);\n+ $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturn([]);\n+ $builder->select('*')->from('users')->chunk(10, function () {return true; });\n+\n+ $this->assertEquals($query, $builder->toSql());\n+ }\n+\n+ public function testChunkWithOrderBy()\n+ {\n+ $builder = $this->getBuilder();\n+ $query = 'select * from \"users\" order by \"sort_order\" asc limit 10 offset 0';\n+ $builder->getConnection()->shouldReceive('select')->once()->with($query, [], true)->andReturn([]);\n+ $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturn([]);\n+ $builder->select('*')->from('users')->orderBy('sort_order')->chunk(10, function () {return true; });\n+\n+ $this->assertEquals($query, $builder->toSql());\n+ }\n+\n protected function getBuilder()\n {\n $grammar = new Illuminate\\Database\\Query\\Grammars\\Grammar;", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "I've come across a bug when trying to update a database in a migration using `chunk` where some records aren't being saved. In our case we're adding a nullable column, setting the values for that column and then making it nullable within a single migration. Using `chunk` though attempting to remove the `nullable` option from the column would throw an error because some records didn't have the values set.\n\nI've created a minimal example to show this off - https://github.com/EspadaV8/laravel-chunking-non-persistance/tree/develop - cloning this and running `php artisan migrate:refresh --seed` should produce something like the following output\n\n```\nEmpty example table\n+----+------+----------+\n| id | name | new-name |\n+----+------+----------+\n\nPopulated example table with `name`\n+----+------------+----------+\n| id | name | new-name |\n+----+------------+----------+\n| 1 | mM4YJMR3i2 | |\n| 2 | ZYNNY6DBqi | |\n| 3 | okKt4kIARY | |\n| 4 | VHJ6ni85c8 | |\n+----+------------+----------+\n\nPopulated example table with `name-new` using `chuck`\n+----+------------+----------------+\n| id | name | new-name |\n+----+------------+----------------+\n| 1 | mM4YJMR3i2 | mM4YJMR3i2-new |\n| 2 | ZYNNY6DBqi | ZYNNY6DBqi-new |\n| 3 | okKt4kIARY | okKt4kIARY-new |\n| 4 | VHJ6ni85c8 | |\n+----+------------+----------------+\n```\n\nThe one row without a `new-name` set should've been set in the second `chunk` batch.\n", "comments": [ { "body": "Are you able to send a PR please?\n", "created_at": "2015-12-19T22:49:05Z" }, { "body": "I did try having a go at fixing this but I wasn't able to work out where the issue is. If I get a chance to have another look at it I'll see if I can submit something (if you have any pointers as to where to start looking that'd be great).\r\n", "created_at": "2015-12-20T12:48:45Z" }, { "body": "Made a slight change to the seeder so that it appends to the `name-new` column instead of just setting it to a known value and it now produces the following output\n\n```\nespadav8@dolores:~/Workspace/chunking-non-persistance (*)\n> php artisan migrate:refresh --seed develop [7fd9127] modified\nRolled back: 2015_12_10_235952_create_tables\nMigrated: 2015_12_10_235952_create_tables\n\nEmpty example table\n+----+------+----------+\n| id | name | name-new |\n+----+------+----------+\n\nPopulated example table with `name`\n+----+------------+------------+\n| id | name | name-new |\n+----+------------+------------+\n| 1 | kVmjtZUXTH | ZoerIsEvoZ |\n| 2 | 0VkvI2TSIF | DZ1R4Joz26 |\n| 3 | TKaJTOiVzH | W3eOttRChc |\n| 4 | bS6TeDg3xB | DJgjzlQBX5 |\n+----+------------+------------+\n\nPopulated example table with `name-new` using `chuck`\n+----+------------+--------------------+\n| id | name | name-new |\n+----+------------+--------------------+\n| 1 | kVmjtZUXTH | ZoerIsEvoZ-new |\n| 2 | 0VkvI2TSIF | DZ1R4Joz26-new |\n| 3 | TKaJTOiVzH | W3eOttRChc-new-new |\n| 4 | bS6TeDg3xB | DJgjzlQBX5 |\n+----+------------+--------------------+\n```\n\nFor some reason the second `chunk` call returns just 1 record, but it's a record that's already been returned (in this case record 3).\n\nIt looks like the queries that are being created are correct (`$this->forPage($page, $count)->toSql()`)\n\n``` sql\nselect * from \"example\" limit 3 offset 0;\nselect * from \"example\" limit 3 offset 3;\nselect * from \"example\" limit 3 offset 6;\n```\n", "created_at": "2015-12-20T22:40:21Z" }, { "body": "Looks like this might actually be an issue with the postgresql PDO driver. I've submitted it to PHP - https://bugs.php.net/bug.php?id=71176. There's a new script I've added that only uses PDO and shows the same kind of output\n\nhttps://github.com/EspadaV8/laravel-chunking-non-persistance/blob/develop/public/pg-pdo-test.php\n", "created_at": "2015-12-20T23:30:34Z" }, { "body": "So, that bug was closed as `Not a bug`. It looks like it's expected behaviour, at least with postgresql - http://www.postgresql.org/docs/current/static/queries-limit.html\n\nBecause the `chunk` doesn't have any kind of `ORDER BY` the results can be returned in any order. The simple fix would be to `ORDER BY` the primary key (unless something else has been set). Does that sound like an okay fix for you @GrahamCampbell ?\n", "created_at": "2015-12-21T02:14:15Z" }, { "body": "Feel free to send a PR, and we'll review it.\n", "created_at": "2015-12-21T10:53:45Z" }, { "body": "I managed to lose a comment here somehow :confused:\n\nTo have `chunk` use an `ORDER BY` it would need to know what the primary key for a table is, however, there's no way of knowing that within the `Builder` class. It could check to see if an `ORDER BY` has been set and try to use `id` but that could fail, or it could throw an exception if no `ORDER BY` has been set.\n\nNeither of those sound too nice to me. Is there another way that I might be missing that you can think of?\n", "created_at": "2015-12-22T10:08:01Z" }, { "body": "@EspadaV8 You can call `$this->model->getKeyName()` in the Builder to get the primary key column. Does that help?\n", "created_at": "2015-12-22T17:15:27Z" }, { "body": "As far as I know, the Builder doesn't have a reference to an particular model since it can be used by itself. Something like... \n\n```\nDB::table('users')->chunk(...);\n```\n\nDoesn't know what columns are in that table or what the tables primary key is. Currently it will work but in an unsupported way since is should require an `orderBy`. \n", "created_at": "2015-12-23T07:40:42Z" }, { "body": "Well, eloquent Builder does, query builder doesn't. Both have chunk method.\n", "created_at": "2015-12-23T07:50:53Z" }, { "body": "Ah, okay. I was talking about the query builder in this case. The issue could exist within the eloquent builder too though.\n", "created_at": "2015-12-23T11:01:16Z" }, { "body": "What actually needs fixing then?\n", "created_at": "2015-12-30T13:32:50Z" }, { "body": "I still think that the `chunk` method should require an `order by` clause as recommended by both the postgresql and MySQL docs. I wanted to do a quick test of what @taylorotwell mentioned in his comment https://github.com/laravel/framework/pull/11510#issuecomment-167334145 because I don't think you can do any kind of `chunk` when the where includes a field that you are updating because the second call would then skip a whole chunk that are now the records at offset 0 (so you would need to force the offset to 0 for each call).\n\nIf there isn't to be a change to force an order by then I could update to docs to add a warning recommending that an order by be included. \n", "created_at": "2015-12-30T13:46:25Z" }, { "body": "> I still think that the chunk method should require an order by clause as recommended by both the postgresql and MySQL docs.\n\nThat's not a bug though. You just add an orderby...\n", "created_at": "2015-12-30T13:51:56Z" }, { "body": "EspadaV8, I'm not particularly familiar with how the query builder's internal work, but it appears that at least in MySQL, one can sort by _rowid, which I think might fix the issue and may be something that could automatically be appended to queries even when you don't know the primary key's.\n\nI don't know if this is what you're looking for, though. I'm pretty new to the internals of Laravel, and don't know if doing special casing based on the database type is something that may be done in the query builder or not.\n", "created_at": "2016-01-06T05:34:20Z" }, { "body": "If it's not going to be changed, then it should be noted in the Laravel docs.\n", "created_at": "2016-03-24T16:47:41Z" }, { "body": "We're open to PRs to the docs. Thank you everyone! :heart:\n", "created_at": "2016-06-17T14:55:56Z" }, { "body": "I had submitted https://github.com/laravel/docs/pull/2227, but it wasn't committed in its entirety. Taylor committed my changes to the sample code for chunk() to include orderBy(), but not the explanation about _why_ one should use orderBy() with chunk(). I can write a more complete explanation if that would help. I just think leaving this issue out there without any explanation is creating confusion.\n", "created_at": "2016-07-26T18:18:29Z" } ], "number": 11302, "title": "[5.1] [5.2] Error with `chunk` not saving second batch" }
{ "body": "This is in reference to #11302 \n\nThis change makes sure that before chunking the results an `orderBy` has been set. If nothing was set by the user then the function will default to setting it to `id`. This can cause issues if a table doesn't have an `id` field.\n\nThe alternative would be to throw an exception if no `orderBy` has been set, but that would possibly be a huge breaking change.\n\nI've added some tests to make sure that an `order by` statement is added to the SQL that's generated, but I'm not sure if the tests cover enough (there currently aren't any tests at all for the `chunk` method).\n\nI'm open to all suggestions as to better/different ways to fix this.\n", "number": 11489, "review_comments": [], "title": "[5.2] [WIP] Chunk should require orderBy" }
{ "commits": [ { "message": "Attempt to set a default orderBy when chunking" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n use Closure;\n use BadMethodCallException;\n use Illuminate\\Support\\Arr;\n+use Illuminate\\Support\\Facades\\Log;\n use Illuminate\\Support\\Str;\n use InvalidArgumentException;\n use Illuminate\\Pagination\\Paginator;\n@@ -1548,6 +1549,10 @@ protected function restoreFieldsForCount()\n */\n public function chunk($count, callable $callback)\n {\n+ if ($this->getOrderBys() === null) {\n+ $this->orderBy('id', 'asc');\n+ }\n+\n $results = $this->forPage($page = 1, $count)->get();\n \n while (count($results) > 0) {\n@@ -1566,6 +1571,18 @@ public function chunk($count, callable $callback)\n return true;\n }\n \n+ /**\n+ * Returns the currently set ordering\n+ *\n+ * @return array|null\n+ */\n+ public function getOrderBys()\n+ {\n+ $property = $this->unions ? 'unionOrders' : 'orders';\n+\n+ return $this->{$property};\n+ }\n+\n /**\n * Get an array with the values of a given column.\n *", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -1356,6 +1356,28 @@ public function testCaseInsensitiveLeadingBooleansAreRemoved()\n $this->assertEquals('select * from \"users\" where \"name\" = ?', $builder->toSql());\n }\n \n+ public function testChunkWithoutOrderBy()\n+ {\n+ $builder = $this->getBuilder();\n+ $query = 'select * from \"users\" order by \"id\" asc limit 10 offset 0';\n+ $builder->getConnection()->shouldReceive('select')->once()->with($query, [], true)->andReturn([]);\n+ $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturn([]);\n+ $builder->select('*')->from('users')->chunk(10, function() {return true;});\n+\n+ $this->assertEquals($query, $builder->toSql());\n+ }\n+\n+ public function testChunkWithOrderBy()\n+ {\n+ $builder = $this->getBuilder();\n+ $query = 'select * from \"users\" order by \"sort_order\" asc limit 10 offset 0';\n+ $builder->getConnection()->shouldReceive('select')->once()->with($query, [], true)->andReturn([]);\n+ $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturn([]);\n+ $builder->select('*')->from('users')->orderBy('sort_order')->chunk(10, function() {return true;});\n+\n+ $this->assertEquals($query, $builder->toSql());\n+ }\n+\n protected function getBuilder()\n {\n $grammar = new Illuminate\\Database\\Query\\Grammars\\Grammar;", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "First, failing test case.\n\n// fails in 5.2 beta, passes in 5.1\n\n``` php\npublic function testCustomValidationMessages()\n{\n $userdata = array (\n 'fix_elevation' => '5',\n );\n\n // Declare the rules for the form validation.\n $rules = array (\n 'fix_elevation' => 'boolean',\n );\n\n $messages = array (\n 'boolean' => 'is invalid',\n 'xxx.in' => 'is invalid',\n );\n\n // Validate the inputs.\n $validator = Validator::make($userdata, $rules, $messages);\n\n $this->assertEquals(['fix_elevation' => [0 => 'is invalid']], $validator->messages()->toArray(), 'Custom validation messages are wrong');\n}\n```\n\nIf you remove `'xxx.in' => 'is invalid',` or change `is invalid` to something else, it will pass.\n", "comments": [ { "body": "Array validation changed in L5.2.\n", "created_at": "2015-12-20T12:21:41Z" }, { "body": "Fixed.\n", "created_at": "2015-12-20T16:23:20Z" }, { "body": ":+1:\n", "created_at": "2015-12-20T16:23:57Z" } ], "number": 11426, "title": "[5.2] Identical custom validation messages for different rules not working" }
{ "body": "To prevent #11426 in the future\n", "number": 11473, "review_comments": [], "title": "[5.1] Validation test" }
{ "commits": [ { "message": "Validation test" } ], "files": [ { "diff": "@@ -231,6 +231,37 @@ public function testInlineValidationMessagesAreRespected()\n $this->assertEquals('require it please!', $v->messages()->first('name'));\n }\n \n+ public function testSeveralSameInlineValidationMessagesAreRespected()\n+ {\n+ $trans = $this->getRealTranslator();\n+ \n+ $data = [\n+ 'name' => '',\n+ 'foo' => 'bar',\n+ 'laravel' => 'framework',\n+ ];\n+\n+ $rules = [\n+ 'name' => 'Required',\n+ 'foo' => 'Boolean',\n+ 'laravel' => 'Numeric',\n+ ];\n+\n+ $messages = [\n+ 'name.required' => 'validation failed',\n+ 'foo.boolean' => 'validation failed',\n+ 'laravel.numeric' => 'another failure',\n+ ];\n+\n+ $v = new Validator($trans, $data, $rules, $messages);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+\n+ $this->assertEquals('validation failed', $v->messages()->first('name'));\n+ $this->assertEquals('validation failed', $v->messages()->first('foo'));\n+ $this->assertEquals('another failure', $v->messages()->first('laravel'));\n+ }\n+\n public function testValidateRequired()\n {\n $trans = $this->getRealTranslator();", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "First, failing test case.\n\n// fails in 5.2 beta, passes in 5.1\n\n``` php\npublic function testCustomValidationMessages()\n{\n $userdata = array (\n 'fix_elevation' => '5',\n );\n\n // Declare the rules for the form validation.\n $rules = array (\n 'fix_elevation' => 'boolean',\n );\n\n $messages = array (\n 'boolean' => 'is invalid',\n 'xxx.in' => 'is invalid',\n );\n\n // Validate the inputs.\n $validator = Validator::make($userdata, $rules, $messages);\n\n $this->assertEquals(['fix_elevation' => [0 => 'is invalid']], $validator->messages()->toArray(), 'Custom validation messages are wrong');\n}\n```\n\nIf you remove `'xxx.in' => 'is invalid',` or change `is invalid` to something else, it will pass.\n", "comments": [ { "body": "Array validation changed in L5.2.\n", "created_at": "2015-12-20T12:21:41Z" }, { "body": "Fixed.\n", "created_at": "2015-12-20T16:23:20Z" }, { "body": ":+1:\n", "created_at": "2015-12-20T16:23:57Z" } ], "number": 11426, "title": "[5.2] Identical custom validation messages for different rules not working" }
{ "body": "To prevent #11426 in the future\n", "number": 11472, "review_comments": [], "title": "[5.2] Validation test" }
{ "commits": [ { "message": "Validation test" } ], "files": [ { "diff": "@@ -282,6 +282,37 @@ public function testInlineValidationMessagesAreRespectedWithAsterisks()\n $this->assertEquals('all must be required!', $v->messages()->first('name.1'));\n }\n \n+ public function testSeveralSameInlineValidationMessagesAreRespected()\n+ {\n+ $trans = $this->getRealTranslator();\n+\n+ $data = [\n+ 'name' => '',\n+ 'foo' => 'bar',\n+ 'laravel' => 'framework',\n+ ];\n+\n+ $rules = [\n+ 'name' => 'Required',\n+ 'foo' => 'Boolean',\n+ 'laravel' => 'Numeric',\n+ ];\n+\n+ $messages = [\n+ 'name.required' => 'validation failed',\n+ 'foo.boolean' => 'validation failed',\n+ 'laravel.numeric' => 'another failure',\n+ ];\n+\n+ $v = new Validator($trans, $data, $rules, $messages);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+\n+ $this->assertEquals('validation failed', $v->messages()->first('name'));\n+ $this->assertEquals('validation failed', $v->messages()->first('foo'));\n+ $this->assertEquals('another failure', $v->messages()->first('laravel'));\n+ }\n+\n public function testValidateRequired()\n {\n $trans = $this->getRealTranslator();", "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": "Since the Authenticatable trait is in the same namespace, it is defaulting to it. Aliasing to AuthenticatableContract makes it work properly.\n\nOtherwise, I get this error running phpunit:\n\n```\nPHP Fatal error: Cannot use Illuminate\\Contracts\\Auth\\Authenticatable as Authenticatable because the name is already in use in /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php on line 12\nPHP Fatal error: Uncaught Illuminate\\Contracts\\Container\\BindingResolutionException: Target [Illuminate\\Contracts\\Debug\\ExceptionHandler] is not instantiable. in /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Container/Container.php:744\nStack trace:\n#0 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\\Container\\Container->build('Illuminate\\\\Cont...', Array)\n#1 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\\Container\\Container->make('Illuminate\\\\Cont...', Array)\n#2 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(154): Illuminate\\Foundation\\Application->make('Illuminate\\\\Cont...')\n#3 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(79): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->getExceptionHandler()\n#4 /PhpStorm/ in /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 744\n```\n", "number": 11394, "review_comments": [], "title": "[5.1] SessionGuard and SessionHelpers needs to alias the Authenticatable interface" }
{ "commits": [ { "message": "SessionGuard needs to alias the Authenticatable interface\n\nSince the Authenticatable trait is in the same namespace, it is defaulting to it. Aliasing to AuthenticatableContract makes it work properly.\r\n\r\nOtherwise, I get this error running phpunit:\r\n\r\n```\r\nPHP Fatal error: Cannot use Illuminate\\Contracts\\Auth\\Authenticatable as Authenticatable because the name is already in use in /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php on line 12\r\nPHP Fatal error: Uncaught Illuminate\\Contracts\\Container\\BindingResolutionException: Target [Illuminate\\Contracts\\Debug\\ExceptionHandler] is not instantiable. in /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Container/Container.php:744\r\nStack trace:\r\n#0 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\\Container\\Container->build('Illuminate\\\\Cont...', Array)\r\n#1 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\\Container\\Container->make('Illuminate\\\\Cont...', Array)\r\n#2 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(154): Illuminate\\Foundation\\Application->make('Illuminate\\\\Cont...')\r\n#3 /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(79): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->getExceptionHandler()\r\n#4 /PhpStorm/ in /PhpStorm/Projects/ProjectManagement/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 744\r\n```" }, { "message": "SessionHelpers needs to alias the Authenticatable interface\n\nSame goes for this one." } ], "files": [ { "diff": "@@ -2,7 +2,7 @@\n \n namespace Illuminate\\Auth;\n \n-use Illuminate\\Contracts\\Auth\\Authenticatable;\n+use Illuminate\\Contracts\\Auth\\Authenticatable as AuthenticatableContract;\n \n /**\n * These methods are typically the same across all guards.\n@@ -61,7 +61,7 @@ public function id()\n * @param \\Illuminate\\Contracts\\Auth\\Authenticatable $user\n * @return void\n */\n- public function setUser(Authenticatable $user)\n+ public function setUser(AuthenticatableContract $user)\n {\n $this->user = $user;\n }", "filename": "src/Illuminate/Auth/GuardHelpers.php", "status": "modified" }, { "diff": "@@ -9,7 +9,7 @@\n use Illuminate\\Contracts\\Auth\\StatefulGuard;\n use Symfony\\Component\\HttpFoundation\\Request;\n use Symfony\\Component\\HttpFoundation\\Response;\n-use Illuminate\\Contracts\\Auth\\Authenticatable;\n+use Illuminate\\Contracts\\Auth\\Authenticatable as AuthenticatableContract;\n use Illuminate\\Contracts\\Auth\\SupportsBasicAuth;\n use Illuminate\\Contracts\\Cookie\\QueueingFactory as CookieJar;\n use Symfony\\Component\\HttpFoundation\\Session\\SessionInterface;\n@@ -408,7 +408,7 @@ public function attempting($callback)\n * @param bool $remember\n * @return void\n */\n- public function login(Authenticatable $user, $remember = false)\n+ public function login(AuthenticatableContract $user, $remember = false)\n {\n $this->updateSession($user->getAuthIdentifier());\n \n@@ -495,7 +495,7 @@ public function onceUsingId($id)\n * @param \\Illuminate\\Contracts\\Auth\\Authenticatable $user\n * @return void\n */\n- protected function queueRecallerCookie(Authenticatable $user)\n+ protected function queueRecallerCookie(AuthenticatableContract $user)\n {\n $value = $user->getAuthIdentifier().'|'.$user->getRememberToken();\n \n@@ -565,7 +565,7 @@ protected function clearUserDataFromStorage()\n * @param \\Illuminate\\Contracts\\Auth\\Authenticatable $user\n * @return void\n */\n- protected function refreshRememberToken(Authenticatable $user)\n+ protected function refreshRememberToken(AuthenticatableContract $user)\n {\n $user->setRememberToken($token = Str::random(60));\n \n@@ -578,7 +578,7 @@ protected function refreshRememberToken(Authenticatable $user)\n * @param \\Illuminate\\Contracts\\Auth\\Authenticatable $user\n * @return void\n */\n- protected function createRememberTokenIfDoesntExist(Authenticatable $user)\n+ protected function createRememberTokenIfDoesntExist(AuthenticatableContract $user)\n {\n if (empty($user->getRememberToken())) {\n $this->refreshRememberToken($user);\n@@ -680,7 +680,7 @@ public function getUser()\n * @param \\Illuminate\\Contracts\\Auth\\Authenticatable $user\n * @return void\n */\n- public function setUser(Authenticatable $user)\n+ public function setUser(AuthenticatableContract $user)\n {\n $this->user = $user;\n ", "filename": "src/Illuminate/Auth/SessionGuard.php", "status": "modified" } ] }
{ "body": "I think I've found an issue with the Middleware routing syntax. \n\nI have the following code in my routes file:\n\n```\nRoute::group(['middleware' => 'role:admin'], function () {\n Route::post('users/new', 'UsersController@doNew')->middleware(['clean.user']);\n});\n```\n\nNotice that the 'role:admin' in the group is just a string, which, according to the docs, is valid syntax. \n\nBut when I browse to the users/new route, I get an exception because because lines 276-278 of Laravel's Illuminate/Routing/Route.php expects both 'role.admin' in the route group and 'clean.user' in the 'users/new' route to be arrays so it can use array_merge() to apply both middlewares. \n\nIf I change the group to ['role:admin'] instead, it works just fine: \n\n```\nRoute::group(['middleware' => ['role:admin']], function () {\n Route::post('users/new', 'UsersController@doNew')->middleware(['clean.user']);\n});\n```\n\nMaybe the accepted Middleware syntax should be changed to only allow arrays? \n", "comments": [], "number": 11116, "title": "Routing syntax inconsistency" }
{ "body": "Bugfix for #11116\n", "number": 11118, "review_comments": [ { "body": "Only one argument is allowed per line in a multi-line function call\n", "created_at": "2015-12-01T02:35:39Z" }, { "body": "PHP-CS-fix did not complain about that.\n", "created_at": "2015-12-01T02:37:32Z" }, { "body": "Just ignore nitpick. ;)\n", "created_at": "2015-12-01T08:34:32Z" } ], "title": "[5.1] Allow Route::group 'middleware' attribute to be passed as string" }
{ "commits": [ { "message": "Allow Route::group 'middleware' attribute to be passed as string.\nIlluminate\\Routing\\Route will properly cast it when necessary." }, { "message": "PHP-CS-fix" } ], "files": [ { "diff": "@@ -274,7 +274,7 @@ public function middleware($middleware = null)\n }\n \n $this->action['middleware'] = array_merge(\n- Arr::get($this->action, 'middleware', []), $middleware\n+ (array) Arr::get($this->action, 'middleware', []), $middleware\n );\n \n return $this;", "filename": "src/Illuminate/Routing/Route.php", "status": "modified" }, { "diff": "@@ -682,6 +682,20 @@ public function testNestedRouteGroupingWithAs()\n $this->assertEquals('foo/bar/baz', $route->getPath());\n }\n \n+ public function testRouteMiddlewareMergeWithMiddlewareAttributesAsStrings()\n+ {\n+ $router = $this->getRouter();\n+ $router->group(['prefix' => 'foo', 'middleware' => 'boo:foo'], function () use ($router) {\n+ $router->get('bar', function () {return 'hello';})->middleware('baz:gaz');\n+ });\n+ $routes = $router->getRoutes()->getRoutes();\n+ $route = $routes[0];\n+ $this->assertEquals(\n+ ['boo:foo', 'baz:gaz'],\n+ $route->middleware()\n+ );\n+ }\n+\n public function testRoutePrefixing()\n {\n /*", "filename": "tests/Routing/RoutingRouteTest.php", "status": "modified" } ] }
{ "body": "The Illuminate\\Database\\Query\\Grammars\\Grammer.php function compileUpdate returns a final construct like this:\n`return trim(\"update {$table}{$joins} set $columns $where\");`\n\nThis fails using SqlServer. It produces incorrect SQL, for example:\n\n``` sql\nupdate [InventoryCodes] inner join [Products] on [InventoryCodes].[ProductID] = [Products].[ProductID] \nset [InventoryCodes].[StockQty] = [InventoryCodes].[StockQty] - 2 \nwhere [InventoryCodes].[FullSKU] = '1827-11' and [Products].[TrackInventory] = '1'\n```\n\nLooks great, but fails in actual use. \n\nCorrect SqlServer format will be like this (note the set command is before the join, the table name is actually listed twice, alternately an alias could be used but needs to be extracted from the $table variable first):\n\n``` sql\nupdate [InventoryCodes] set [InventoryCodes].[StockQty] = [InventoryCodes].[StockQty] - 2 \nfrom [InventoryCodes] inner join [Products] on [InventoryCodes].[ProductID] = [Products].[ProductID] \nwhere [InventoryCodes].[FullSKU] = '1827-11' and [Products].[TrackInventory] = '1'\n```\n\nThis implies that the SqlServerGrammer.php file should override the compileUpdates function, check if there is a join, and return something like this:\n\n``` php\n if (!empty($joins))\n {\n $sql = trim(\"update {$table} set $columns from {$table} {$joins} $where\");\n }\n else\n {\n $sql = trim(\"update {$table} set $columns $where\");\n }\n\n return $sql;\n```\n\nTable aliases will cause the above to fail (eg [InventoryCodes as ic]). So it would make sense to also set up a method to extract the table alias from the $table variable to use as the first table name argument in the result. Then the resultant SQL would look like this:\n\n``` sql\nupdate [ic] set [ic].[StockQty] = [ic].[StockQty] - 2 \nfrom [InventoryCodes as ic] inner join [Products] on [ic].[ProductID] = [Products].[ProductID] \nwhere [ic].[FullSKU] = '1827-11' and [Products].[TrackInventory] = '1'\n```\n\nAnd the $sql returned for a join would be this:\n`$sql = trim(\"update {$table_alias} set $columns from {$table} {$joins} $where\");`\n\nIf there was no table alias, the $table_alias value would simply be $table. \n\nI don't have time in the near future to set up a pull request with a final resolution, but if this issue sits around long enough I will eventually try to do so.\n", "comments": [ { "body": "Closing since we have a PR open now.\n", "created_at": "2015-11-29T12:22:41Z" } ], "number": 10368, "title": "MS SqlServer Update with Join is not correctly implemented" }
{ "body": "Fixes #10368 \n\nGenerate valid T-SQL code for `UPDATE` statements with `JOIN`s. Generated SQL verified working with SQL Server 2012 SP2.\n", "number": 11089, "review_comments": [ { "body": "Expected 0 spaces after opening bracket; 1 found\n", "created_at": "2015-11-27T11:54:30Z" } ], "title": "[5.1] Fix SQL Server UPDATEs with JOINs" }
{ "commits": [ { "message": "Fix SQL Server UPDATEs with JOINs" } ], "files": [ { "diff": "@@ -264,4 +264,53 @@ protected function wrapValue($value)\n \n return '['.str_replace(']', ']]', $value).']';\n }\n+\n+ /**\n+ * Compile an update statement into SQL.\n+ *\n+ * @param \\Illuminate\\Database\\Query\\Builder $query\n+ * @param array $values\n+ * @return string\n+ */\n+ public function compileUpdate(Builder $query, $values)\n+ {\n+ $table = $alias = $this->wrapTable($query->from);\n+\n+ if (strpos(strtolower($table), '] as [') !== false) {\n+ $segments = explode('] as [', $table);\n+\n+ $alias = '['.$segments[1];\n+ }\n+\n+ // Each one of the columns in the update statements needs to be wrapped in the\n+ // keyword identifiers, also a place-holder needs to be created for each of\n+ // the values in the list of bindings so we can make the sets statements.\n+ $columns = [];\n+\n+ foreach ($values as $key => $value) {\n+ $columns[] = $this->wrap($key).' = '.$this->parameter($value);\n+ }\n+\n+ $columns = implode(', ', $columns);\n+\n+ // If the query has any \"join\" clauses, we will setup the joins on the builder\n+ // and compile them so we can attach them to this update, as update queries\n+ // can get join statements to attach to other tables when they're needed.\n+ if (isset($query->joins)) {\n+ $joins = ' '.$this->compileJoins($query, $query->joins);\n+ } else {\n+ $joins = '';\n+ }\n+\n+ // Of course, update queries may also be constrained by where clauses so we'll\n+ // need to compile the where clauses and attach it to the query so only the\n+ // intended records are updated by the SQL statements we generate to run.\n+ $where = $this->compileWheres($query);\n+\n+ if (! empty($joins)) {\n+ return trim(\"update {$alias} set {$columns} from {$table}{$joins} {$where}\");\n+ }\n+\n+ return trim(\"update {$table}{$joins} set $columns $where\");\n+ }\n }", "filename": "src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -1003,6 +1003,22 @@ public function testUpdateMethodWithJoins()\n $this->assertEquals(1, $result);\n }\n \n+ public function testUpdateMethodWithJoinsOnSqlServer()\n+ {\n+ $builder = $this->getSqlServerBuilder();\n+ $builder->getConnection()->shouldReceive('update')->once()->with('update [users] set [email] = ?, [name] = ? from [users] inner join [orders] on [users].[id] = [orders].[user_id] where [users].[id] = ?', ['foo', 'bar', 1])->andReturn(1);\n+ $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']);\n+ $this->assertEquals(1, $result);\n+ }\n+\n+ public function testUpdateMethodWithJoinsAndAliasesOnSqlServer()\n+ {\n+ $builder = $this->getSqlServerBuilder();\n+ $builder->getConnection()->shouldReceive('update')->once()->with('update [u] set [email] = ?, [name] = ? from [users] as [u] inner join [orders] on [u].[id] = [orders].[user_id] where [u].[id] = ?', ['foo', 'bar', 1])->andReturn(1);\n+ $result = $builder->from('users as u')->join('orders', 'u.id', '=', 'orders.user_id')->where('u.id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']);\n+ $this->assertEquals(1, $result);\n+ }\n+\n public function testUpdateMethodWithoutJoinsOnPostgres()\n {\n $builder = $this->getPostgresBuilder();", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "For a join between two tables, I am using column aliases to avoid having multiple fields with the same name. More specifically, both tables have `id` and `name` columns, so I want the generated SQL to look something like this:\n\n```\nSELECT a.id as a_id, a.name as a_name, b.id as b_id, b.name as b_name FROM ...\n```\n\nThat works just fine using the following code:\n\n```\n$results = DB::table('a')\n ->join('b', 'a.b_id', '=', 'b.id')\n ->get([\n 'a.id as a_id',\n 'a.name as a_name',\n 'b.id as b_id',\n 'b.name as b_name'\n ]);\n```\n\nI want to paginate these results and I thought that the simplest way to do that was this:\n\n```\n$results = DB::table('a')\n ->join('b', 'a.b_id', '=', 'b.id')\n ->paginate(20, [\n 'a.id as a_id',\n 'a.name as a_name',\n 'b.id as b_id',\n 'b.name as b_name'\n ]);\n```\n\nHowever, PostgreSQL gives the following error:\n\n```\nERROR: syntax error at or near \"as\"\n```\n\nHere is the query that it generates:\n\n```\nselect count(a.id as a_id, a.name as a_name, b.id as b_id, b.name as b_name) as aggregate\nfrom a inner join b on a.b_id = b.id\n```\n\nI determined that when I remove all of the aliases, the pagination works as expected.\n\nFurther testing reveals that this _does_ work properly in a longer form:\n\n```\n$results = DB::table('a')\n ->join('b', 'a.b_id', '=', 'b.id')\n ->select([\n 'a.id as a_id',\n 'a.name as a_name',\n 'b.id as b_id',\n 'b.name as b_name'\n ])\n ->paginate(20);\n```\n\nThe problem appears to be that the query builder is supposed to be removing all the column names before it does an aggregate - in this case the `count` needed for getting the number of pages - but it only does that if the columns have been specified in the `select` method, not in the `paginate` method.\n\nThe shortcut syntax is very nice, but it clearly doesn't work the same way as the longer syntax does!\n", "comments": [ { "body": "Possibly related to #9385, #9528, #9509 (though those are about the Eloquent version)\n", "created_at": "2015-08-19T19:24:41Z" } ], "number": 9993, "title": "[5.1] Column aliases break PostgreSQL query for count for pagination" }
{ "body": "Discussion in #9993\n", "number": 10649, "review_comments": [ { "body": "``` php\nif (! is_string($column) || ($aliasPosition = strpos(strtolower($column), ' as ')) === false) {\n continue;\n}\n\n$column = substr($column, 0, $aliasPosition);\n```\n", "created_at": "2015-10-18T13:00:29Z" }, { "body": "that would reduce the nesting here ^^^\n", "created_at": "2015-10-18T13:00:37Z" }, { "body": "cs\n", "created_at": "2015-10-18T13:00:50Z" } ], "title": "[5.1] Clear column aliases in count queries" }
{ "commits": [ { "message": "Clear column aliases in count queries" } ], "files": [ { "diff": "@@ -1461,7 +1461,7 @@ public function getCountForPagination($columns = ['*'])\n {\n $this->backupFieldsForCount();\n \n- $this->aggregate = ['function' => 'count', 'columns' => $columns];\n+ $this->aggregate = ['function' => 'count', 'columns' => $this->clearSelectAliases($columns)];\n \n $results = $this->get();\n \n@@ -2056,4 +2056,21 @@ public function __call($method, $parameters)\n \n throw new BadMethodCallException(\"Call to undefined method {$className}::{$method}()\");\n }\n+\n+ /**\n+ * Clear column aliases.\n+ *\n+ * @param array $columns\n+ * @return array\n+ */\n+ protected function clearSelectAliases(array $columns)\n+ {\n+ foreach ($columns as &$column) {\n+ if (is_string($column) && ($aliasPosition = strpos(strtolower($column), ' as ')) !== false) {\n+ $column = substr($column, 0, $aliasPosition);\n+ }\n+ }\n+\n+ return $columns;\n+ }\n }", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -560,6 +560,19 @@ public function testGetCountForPaginationWithBindings()\n $this->assertEquals([4], $builder->getBindings());\n }\n \n+ public function testGetCountForPaginationWithColumns()\n+ {\n+ $builder = $this->getBuilder();\n+ $columns = ['body as post_body', 'teaser', 'posts.created as published'];\n+ $builder->from('posts')->select($columns);\n+\n+ $builder->getConnection()->shouldReceive('select')->once()->with('select count(\"body\", \"teaser\", \"posts\".\"created\") as aggregate from \"posts\"', [], true)->andReturn([['aggregate' => 1]]);\n+ $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function ($builder, $results) { return $results; });\n+\n+ $count = $builder->getCountForPagination($columns);\n+ $this->assertEquals(1, $count);\n+ }\n+\n public function testWhereShortcut()\n {\n $builder = $this->getBuilder();", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "Using the following code:\n\n```\n $builder->where('tim', '=', 'bob', 'AND');\n $statement = $builder->toSql();\n```\n\n`$statement` will build something similar to:\n\n```\n select * where AND `tim` = ?\n```\n\nexpected:\n\n```\n select * where `tim` = ?\n```\n\nA simple fix might just be to add a case insensitive flag to `removeLeadingBoolean` in `Illuminate\\Database\\Query\\Grammars\\Grammar`\n", "comments": [ { "body": "Ping @taylorotwell.\n", "created_at": "2015-09-07T19:51:28Z" }, { "body": "@timgws is there any scenario in which you would need to distinguish between case? Just thinking if it needs to be a flag or if we could just rewrite it with a `strtolower`\n", "created_at": "2015-09-14T19:21:25Z" }, { "body": "@phroggyy not that I know of. I don't think there is any database that is case sensitive for the conditions. Changing all of the operators/booleans with `strtolower` was my first thought, but there are so many functions that would need to be changed. This is why I thought changing the regular expression in `removeLeadingBoolean` might be better, as less code would need to be updated.\n", "created_at": "2015-09-14T23:36:18Z" } ], "number": 10173, "title": "removeLeadingBoolean does not remove upper case AND/OR" }
{ "body": "This resolves #10173 by extending the `preg_replace` being used to ensure both `and` and `AND` are treated the same way.\n", "number": 10356, "review_comments": [], "title": "[5.1] Allow uppercase booleans" }
{ "commits": [ { "message": "Replace both upper and lower-case booleans" }, { "message": "Added tests for case insensitivity of leading booleans" } ], "files": [ { "diff": "@@ -756,6 +756,6 @@ protected function concatenate($segments)\n */\n protected function removeLeadingBoolean($value)\n {\n- return preg_replace('/and |or /', '', $value, 1);\n+ return preg_replace('/and |AND |or |OR /', '', $value, 1);\n }\n }", "filename": "src/Illuminate/Database/Query/Grammars/Grammar.php", "status": "modified" }, { "diff": "@@ -1248,6 +1248,20 @@ public function testSubSelect()\n $this->assertEquals($expectedBindings, $builder->getBindings());\n }\n \n+ public function testUppercaseLeadingBooleansAreRemoved()\n+ {\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->where('name', '=', 'Taylor', 'AND');\n+ $this->assertEquals('select * from \"users\" where \"name\" = ?', $builder->toSql());\n+ }\n+\n+ public function testLowercaseLeadingBooleansAreRemoved()\n+ {\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->where('name', '=', 'Taylor', 'and');\n+ $this->assertEquals('select * from \"users\" where \"name\" = ?', $builder->toSql());\n+ }\n+\n protected function getBuilder()\n {\n $grammar = new Illuminate\\Database\\Query\\Grammars\\Grammar;", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "Following piece of code:\n\n```\n$parent->child()->attach(\n [\n 1 => [ 'value' => 'one' , 'created_at' => time()],\n 10 => ['value' => 'ten' ] \n ]\n);\n```\n\n(where `$parent` model and its `$parent->child` property are linked via `belongsToMany()` reciprocally) yields an error message similar to:\n\n```\nIlluminate\\Database\\QueryException with message \n'SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 2 \n(SQL: insert into `parent_child` (`created_at`, `field_id`, `profile_id`, `value`) values (1438695572, 1, 1, one), (10, 1, ten))'\n```\n\nAs you can see, it tries to guess the columns in first set of data to be valid for the remainder of the sets. But since `created_at` field hasn't been provided for set-2, column mismatch occurs.\n\nAlso we can see that Db Insertion has been made via `INSERT INTO ... (columns, go, here) VALUES (values, go, here)` method, instead of `INSERT INTO ... SET column1 = value1, column2 = value2` method. I believe using the latter method would solve the problem. RDBMS used/tested is MySQL. As a side note: as far as I remember, the latter method I propose here doesn't work on other RDBMS's, and isn't SQL92-compliant.\n\nTests have been performed via `./artisan tinker`. I can provide step-by-step repeat scenario if needed.\n\nAny ideas? If necessary, after discussing I can send PR with possible fix.\n", "comments": [ { "body": "Reference docs at: http://laravel.com/docs/master/eloquent-relationships#inserting-many-to-many-relationships\n", "created_at": "2015-08-04T14:05:11Z" }, { "body": "Bump.\n", "created_at": "2015-08-12T14:13:57Z" } ], "number": 9837, "title": "[5.1] Many-to-Many relations, attach() and \"Column count doesn't match\" error" }
{ "body": "Proposed fix for #9837\n", "number": 10354, "review_comments": [], "title": "[5.1] Ensure that all records being attached have the same number of columns" }
{ "commits": [ { "message": "Ensure that all records being inserted have the same number of columns" } ], "files": [ { "diff": "@@ -912,6 +912,8 @@ protected function createAttachRecords($ids, array $attributes)\n $timed = ($this->hasPivotColumn($this->createdAt()) ||\n $this->hasPivotColumn($this->updatedAt()));\n \n+ $ids = $this->normalizeAttachColumnLists($ids);\n+\n // To create the attachment records, we will simply spin through the IDs given\n // and create a new record to insert for each ID. Each ID may actually be a\n // key in the array, with extra attributes to be placed in other columns.\n@@ -1248,4 +1250,66 @@ public function getRelationName()\n {\n return $this->relationName;\n }\n+\n+ /**\n+ * Normalize the column list for attaching records\n+ *\n+ * @param $ids\n+ * @return array\n+ */\n+ protected function normalizeAttachColumnLists($ids)\n+ {\n+ if ( ! $this->hasExtraAttachColumns($ids)) {\n+ return $ids;\n+ }\n+\n+ $normalized = [];\n+ $columnList = $this->getAttachColumnList($ids);\n+\n+ foreach ($ids as $key => $value) {\n+ if (is_array($value)) {\n+ $normalized[$key] = array_merge($columnList, $value);\n+ } else {\n+ $normalized[$value] = $columnList;\n+ }\n+ }\n+\n+ return $normalized;\n+ }\n+\n+ /**\n+ * Determine whether records being attached have extra columns\n+ *\n+ * @param $ids\n+ * @return bool\n+ */\n+ protected function hasExtraAttachColumns($ids)\n+ {\n+ foreach ($ids as $key => $value) {\n+ if (is_array($value)) {\n+ return true;\n+ }\n+ }\n+\n+ return false;\n+ }\n+\n+ /**\n+ * Get list of all columns being attached\n+ *\n+ * @param $ids\n+ * @return array\n+ */\n+ protected function getAttachColumnList($ids)\n+ {\n+ $arrayColumns = [];\n+\n+ foreach ($ids as $key => $value) {\n+ if (is_array($value)) {\n+ $arrayColumns[] = $value;\n+ }\n+ }\n+\n+ return array_fill_keys(array_keys(Arr::collapse($arrayColumns)), null);\n+ }\n }", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsToMany.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": "Lately, I have upgraded my website from L 4.2.11 to the latest one. The Encryption cipher used before was MCRYPT_RIJNDAEL_256 which uses an IV with a length of 32. Since the payload in the cookies in users was encrypted using the old cipher, the EncryptCookies middleware threw an exception with this trace:\n\n```\nproduction.ERROR: exception 'ErrorException' with message 'openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating' in /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:95\nStack trace:\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'openssl_decrypt...', '/home/www/...', 95, Array)\n#1 /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php(95): openssl_decrypt('Dbyr0401XlXcY6N...', 'AES-256-CBC', 'VyZn2WxfW9UgMrI...', 0, 'h\\x82\\x9Co\\t\\x9Fqx\\\\\\x84\\x8B\\x16\\x8B\\x82P...')\n#2 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(95): Illuminate\\Encryption\\Encrypter->decrypt('eyJpdiI6ImFJS2N...')\n#3 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(76): Illuminate\\Cookie\\Middleware\\EncryptCookies->decryptCookie('eyJpdiI6ImFJS2N...')\n#4 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\\Cookie\\Middleware\\EncryptCookies->decrypt(Object(Illuminate\\Http\\Request))\n#5 [internal function]: Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#6 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)\n#7 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#8 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#9 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(122): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#10 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(87): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\n#11 /home/www/MY/public/index.php(54): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\n#12 {main} \n```\n\nThis commit will allow the the decrypt method to handle non `Illuminate\\Contracts\\Encryption\\DecryptException` exceptions. Since sometimes that class can't cover all the decryption issues since cookies can be set from other third parties in the browser.\n", "number": 10080, "review_comments": [], "title": "[5.1] Decrypting cookies encrypted with a different Cipher" }
{ "commits": [ { "message": "[5.1] Decrypting cookies encrypted with a different Cipher\n\nLately, I have upgraded my website from L 4.2.11 to the latest one. The Encryption cipher used before was MCRYPT_RIJNDAEL_128 which uses an IV with a length of 32. Since the payload in the cookies in users was encrypted using the old cipher, the EncryptCookies middleware threw an exception with this trace:\r\n\r\n```\r\nproduction.ERROR: exception 'ErrorException' with message 'openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating' in /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:95\r\nStack trace:\r\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'openssl_decrypt...', '/home/www/...', 95, Array)\r\n#1 /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php(95): openssl_decrypt('Dbyr0401XlXcY6N...', 'AES-256-CBC', 'VyZn2WxfW9UgMrI...', 0, 'h\\x82\\x9Co\\t\\x9Fqx\\\\\\x84\\x8B\\x16\\x8B\\x82P...')\r\n#2 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(95): Illuminate\\Encryption\\Encrypter->decrypt('eyJpdiI6ImFJS2N...')\r\n#3 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(76): Illuminate\\Cookie\\Middleware\\EncryptCookies->decryptCookie('eyJpdiI6ImFJS2N...')\r\n#4 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\\Cookie\\Middleware\\EncryptCookies->decrypt(Object(Illuminate\\Http\\Request))\r\n#5 [internal function]: Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\r\n#6 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)\r\n#7 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\r\n#8 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\r\n#9 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(122): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\r\n#10 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(87): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\r\n#11 /home/www/MY/public/index.php(54): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\r\n#12 {main} \r\n```\r\nThis commit will allow the the decrypt method to handle non `Illuminate\\Contracts\\Encryption\\DecryptException` exceptions. Since sometimes that class can't cover all the decryption issues since cookies can be set from other third parties in the browser." } ], "files": [ { "diff": "@@ -3,10 +3,10 @@\n namespace Illuminate\\Cookie\\Middleware;\n \n use Closure;\n+use Exception;\n use Symfony\\Component\\HttpFoundation\\Cookie;\n use Symfony\\Component\\HttpFoundation\\Request;\n use Symfony\\Component\\HttpFoundation\\Response;\n-use Illuminate\\Contracts\\Encryption\\DecryptException;\n use Illuminate\\Contracts\\Encryption\\Encrypter as EncrypterContract;\n \n class EncryptCookies\n@@ -74,7 +74,7 @@ protected function decrypt(Request $request)\n \n try {\n $request->cookies->set($key, $this->decryptCookie($c));\n- } catch (DecryptException $e) {\n+ } catch (Exception $e) {\n $request->cookies->set($key, null);\n }\n }", "filename": "src/Illuminate/Cookie/Middleware/EncryptCookies.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": "Lately, I have upgraded my website from L 4.2.11 to the latest one. The Encryption cipher used before was MCRYPT_RIJNDAEL_128 which uses an IV with a length of 32. Since the payload in the cookies in users was encrypted using the old cipher, the EncryptCookies middleware threw an exception with this trace:\n\n```\nproduction.ERROR: exception 'ErrorException' with message 'openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating' in /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:95\nStack trace:\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'openssl_decrypt...', '/home/www/...', 95, Array)\n#1 /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php(95): openssl_decrypt('Dbyr0401XlXcY6N...', 'AES-256-CBC', 'VyZn2WxfW9UgMrI...', 0, 'h\\x82\\x9Co\\t\\x9Fqx\\\\\\x84\\x8B\\x16\\x8B\\x82P...')\n#2 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(95): Illuminate\\Encryption\\Encrypter->decrypt('eyJpdiI6ImFJS2N...')\n#3 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(76): Illuminate\\Cookie\\Middleware\\EncryptCookies->decryptCookie('eyJpdiI6ImFJS2N...')\n#4 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\\Cookie\\Middleware\\EncryptCookies->decrypt(Object(Illuminate\\Http\\Request))\n#5 [internal function]: Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#6 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)\n#7 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#8 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#9 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(122): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#10 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(87): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\n#11 /home/www/MY/public/index.php(54): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\n#12 {main} \n```\n\nThe obvious and simple trick would be to wrap the openssl_decrypt() in Encrypter.php:95 in a try catch block throwing a DecryptException exception, but this could be prevented since the beginning in the invalidPayload() method in the BaseEncrypter class by testing the length of the IV.\n\nSince getIvSize() is used in the invalidPayload() method in the abstract invalidPayload() class, I declared it as an abstract method in it.\nI would go ahead and define getIvSize() in the baseEnrypter class using openssl_cipher_iv_length() method, since the IV length might change in the future depending on the cipher declared in the config file.\n\nAt the end, I believe this might be considered as supporting an old version of laravel which is no longer done.\n", "number": 10049, "review_comments": [ { "body": "Wait, shouldn;t this be `!==`?\n", "created_at": "2015-08-26T12:11:03Z" }, { "body": "It's not invalid if the length is correct?\n", "created_at": "2015-08-26T12:11:27Z" }, { "body": "```\n! isset($data['iv']) && strlen($data['iv']) !== $this->getIvSize()\n```\n\nThis whole thing needs brackets.\n", "created_at": "2015-08-26T12:12:13Z" } ], "title": "[5.1] Encryption: Test the IV length in invalidPayload method" }
{ "commits": [ { "message": "[5.2] Encryption: Test the IV length in invalidPayload method\n\nLately, I have upgraded my website from L 4.2.11 to the latest one. The Encryption cipher used before was MCRYPT_RIJNDAEL_128 which uses an IV with a length of 32. Since the payload in the cookies in users was encrypted using the old cipher, the EncryptCookies middleware threw an exception with this trace:\n\n```\nproduction.ERROR: exception 'ErrorException' with message 'openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating' in /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:95\nStack trace:\n```\n\nThe obvious and simple trick would be to wrap the openssl_decrypt() in Encrypter.php:95 in a try catch block throwing a DecryptException exception, but this could be prevented since the beginning in the invalidPayload() method in the BaseEncrypter class by testing the length of the IV.\n\nSince getIvSize() is used in the invalidPayload() method in the abstract invalidPayload() class, I declared it as an abstract method in it.\nI would go ahead and define getIvSize() in the baseEnrypter class using openssl_cipher_iv_length() method, since the IV length might change in the future depending on the cipher declared in the config file.\n\nAt the end, I believe this might be considered as supporting an old version of laravel which is no longer done." } ], "files": [ { "diff": "@@ -60,7 +60,7 @@ protected function getJsonPayload($payload)\n */\n protected function invalidPayload($data)\n {\n- return ! is_array($data) || ! isset($data['iv']) || ! isset($data['value']) || ! isset($data['mac']);\n+ return ! is_array($data) || ! isset($data['iv']) || ! (strlen(base64_decode($data['iv'])) === $this->getIvSize()) || ! isset($data['value']) || ! isset($data['mac']);\n }\n \n /**\n@@ -79,4 +79,11 @@ protected function validMac(array $payload)\n \n return Str::equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);\n }\n+\n+ /**\n+ * Needs to be implemented by child class to be used in payload validation.\n+ *\n+ * @return int\n+ */\n+ abstract protected function getIvSize();\n }", "filename": "src/Illuminate/Encryption/BaseEncrypter.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": "Lately, I have upgraded my website from L 4.2.11 to the latest one. The Encryption cipher used before was MCRYPT_RIJNDAEL_128 which uses an IV with a length of 32. Since the payload in the cookies in users was encrypted using the old cipher, the EncryptCookies middleware threw an exception with this trace:\n\n```\nproduction.ERROR: exception 'ErrorException' with message 'openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating' in /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:95\nStack trace:\n#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'openssl_decrypt...', '/home/www/...', 95, Array)\n#1 /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php(95): openssl_decrypt('Dbyr0401XlXcY6N...', 'AES-256-CBC', 'VyZn2WxfW9UgMrI...', 0, 'h\\x82\\x9Co\\t\\x9Fqx\\\\\\x84\\x8B\\x16\\x8B\\x82P...')\n#2 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(95): Illuminate\\Encryption\\Encrypter->decrypt('eyJpdiI6ImFJS2N...')\n#3 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(76): Illuminate\\Cookie\\Middleware\\EncryptCookies->decryptCookie('eyJpdiI6ImFJS2N...')\n#4 /home/www/MY/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\\Cookie\\Middleware\\EncryptCookies->decrypt(Object(Illuminate\\Http\\Request))\n#5 [internal function]: Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))\n#6 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array)\n#7 [internal function]: Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))\n#8 /home/www/MY/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\\Http\\Request))\n#9 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(122): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))\n#10 /home/www/MY/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(87): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))\n#11 /home/www/MY/public/index.php(54): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))\n#12 {main} \n```\n\nThe obvious and simple trick would be to wrap the openssl_decrypt() in Encrypter.php:95 in a try catch block throwing a DecryptException exception, but this could be prevented since the beginning in the invalidPayload() method in the BaseEncrypter class by testing the length of the IV.\n\nSince getIvSize() is used in the invalidPayload() method in the abstract invalidPayload() class, I declared it as an abstract method in it.\nI would go ahead and define getIvSize() in the baseEnrypter class using openssl_cipher_iv_length() method, since the IV length might change in the future depending on the cipher declared in the config file.\n\nAt the end, I believe this might be considered as supporting an old version of laravel which is no longer done.\n", "number": 10047, "review_comments": [], "title": "[5.2] Encryption: Test the IV length in invalidPayload method" }
{ "commits": [ { "message": "[5.1] Encryption: Test the IV length in invalidPayload method\n\nLately, I have upgraded my website from L 4.2.11 to the latest one. The Encryption cipher used before was MCRYPT_RIJNDAEL_128 which uses an IV with a length of 32. Since the payload in the cookies in users was encrypted using the old cipher, the EncryptCookies middleware threw an exception with this trace:\r\n\r\nproduction.ERROR: exception 'ErrorException' with message 'openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating' in /home/www/MY/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:95\r\n\r\nThe obvious and simple trick would be to wrap the openssl_decrypt() in Encrypter.php:95 in a try catch block throwing a DecryptException exception, but this could be prevented since the beginning in the invalidPayload() method in the BaseEncrypter class by testing the length of the IV.\r\n\r\nSince getIvSize() is used in the invalidPayload() method in the abstract invalidPayload() class, I declared it as an abstract method in it.\r\nI would go ahead and define getIvSize() in the baseEnrypter class using openssl_cipher_iv_length() method, since the IV length might change in the future depending on the cipher declared in the config file.\r\n\r\nAt the end, this might be considered as supporting an old version of laravel which is no longer done." } ], "files": [ { "diff": "@@ -60,7 +60,7 @@ protected function getJsonPayload($payload)\n */\n protected function invalidPayload($data)\n {\n- return ! is_array($data) || ! isset($data['iv']) || ! isset($data['value']) || ! isset($data['mac']);\n+ return ! is_array($data) || ! isset($data['iv']) && strlen($data['iv']) === $this->getIvSize() || ! isset($data['value']) || ! isset($data['mac']);\n }\n \n /**\n@@ -79,4 +79,11 @@ protected function validMac(array $payload)\n \n return Str::equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);\n }\n+\n+ /**\n+ * Needs to be implemented by child class to be used in payload validation.\n+ *\n+ * @return int\n+ */\n+ abstract protected function getIvSize();\n }", "filename": "src/Illuminate/Encryption/BaseEncrypter.php", "status": "modified" } ] }
{ "body": "Resolves bug #9357: [5.1] Terminable Middleware not called during integration tests\n", "comments": [ { "body": "Works for me! +1 for merge, thanks!\n", "created_at": "2015-07-17T12:35:36Z" } ], "number": 9659, "title": "[5.1] Fixes Terminable Middleware During Tests" }
{ "body": "If a test uses the WithoutMiddleware trait, all middleware (including terminable\nmiddleware) should be skipped over.\n\nThis PR builds on top of #9659.\n\nTo clarify: Before #9659 terminable middleware was never executed in tests. After #9659 terminable middleware was always executed in tests, even if the `WithoutMiddleware` trait is used by the test.\n\nThis PR fixes that behavior. Middleware should always be executed in tests if there is no `WithoutMiddleware` trait, and never be executed in tests if `WithoutMiddleware` is used.\n\nRegarding backwards compatibility: This fix would break any tests that falsely rely on the execution of terminable middleware in tests that use `WithoutMiddleware`. Please take this into consideration.\n", "number": 9702, "review_comments": [], "title": "[5.1] Fix execution of terminable middleware in combination with WithoutMiddleware" }
{ "commits": [ { "message": "Fix execution of terminable middleware in combination with WithoutMiddleware\n\nIf a test uses the WithoutMiddleware trait, all middleware (including terminable\nmiddleware) should be skipped over." } ], "files": [ { "diff": "@@ -135,9 +135,15 @@ protected function sendRequestThroughRouter($request)\n */\n public function terminate($request, $response)\n {\n- $routeMiddlewares = $this->gatherRouteMiddlewares($request);\n+ $shouldSkipMiddleware = $this->app->bound('middleware.disable') &&\n+ $this->app->make('middleware.disable') === true;\n+\n+ $middlewares = $shouldSkipMiddleware ? [] : array_merge(\n+ $this->gatherRouteMiddlewares($request),\n+ $this->middleware\n+ );\n \n- foreach (array_merge($routeMiddlewares, $this->middleware) as $middleware) {\n+ foreach ($middlewares as $middleware) {\n list($name, $parameters) = $this->parseMiddleware($middleware);\n \n $instance = $this->app->make($name);", "filename": "src/Illuminate/Foundation/Http/Kernel.php", "status": "modified" } ] }
{ "body": "Hey,\n\nThis route returns Undefined offset: 1 on the line 200 from Illuminate/Routing/Route.php\n\n``` php\nRoute::get('/', [\n 'as' => 'home',\n 'uses' => 'HomeController'\n]);\n```\n\nWill be good a throw Exception instead a Notice and checking if @ exists on the uses key.\n", "comments": [ { "body": "@GrahamCampbell I wouldn't say this is a bug. It's a proposal/request to improve the handling of a wrong `uses` option.\n", "created_at": "2015-06-09T14:43:59Z" }, { "body": "Closing as a PR has been sent. Thank you everyone. :)\n", "created_at": "2015-06-09T16:27:18Z" } ], "number": 9154, "title": "Undefined offset: 1 on Route" }
{ "body": "see #9154\n", "number": 9160, "review_comments": [ { "body": "Please use a slash at the start.\n", "created_at": "2015-06-09T16:26:50Z" }, { "body": "Fixed\n", "created_at": "2015-06-09T16:37:37Z" } ], "title": "[5.1] Better handling of invalid controller action reference" }
{ "commits": [ { "message": "Validate 'uses' value" } ], "files": [ { "diff": "@@ -6,6 +6,7 @@\n use LogicException;\n use ReflectionFunction;\n use Illuminate\\Http\\Request;\n+use UnexpectedValueException;\n use Illuminate\\Container\\Container;\n use Illuminate\\Routing\\Matching\\UriValidator;\n use Illuminate\\Routing\\Matching\\HostValidator;\n@@ -598,6 +599,8 @@ protected function replaceDefaults(array $parameters)\n *\n * @param callable|array $action\n * @return array\n+ *\n+ * @throws \\UnexpectedValueException\n */\n protected function parseAction($action)\n {\n@@ -615,6 +618,11 @@ protected function parseAction($action)\n $action['uses'] = $this->findCallable($action);\n }\n \n+ // Verify if provided \"uses\" property is valid Controller@action string\n+ elseif (substr_count($action['uses'], '@', 1) != 1 || substr($action['uses'], -1, 1) == '@') {\n+ throw new UnexpectedValueException(sprintf('Invalid route action: %s', $action['uses']));\n+ }\n+\n return $action;\n }\n ", "filename": "src/Illuminate/Routing/Route.php", "status": "modified" }, { "diff": "@@ -660,34 +660,43 @@ public function testMergingControllerUses()\n {\n $router = $this->getRouter();\n $router->group(['namespace' => 'Namespace'], function () use ($router) {\n- $router->get('foo/bar', 'Controller');\n+ $router->get('foo/bar', 'Controller@action');\n });\n $routes = $router->getRoutes()->getRoutes();\n $action = $routes[0]->getAction();\n \n- $this->assertEquals('Namespace\\\\Controller', $action['controller']);\n+ $this->assertEquals('Namespace\\\\Controller@action', $action['controller']);\n \n $router = $this->getRouter();\n $router->group(['namespace' => 'Namespace'], function () use ($router) {\n $router->group(['namespace' => 'Nested'], function () use ($router) {\n- $router->get('foo/bar', 'Controller');\n+ $router->get('foo/bar', 'Controller@action');\n });\n });\n $routes = $router->getRoutes()->getRoutes();\n $action = $routes[0]->getAction();\n \n- $this->assertEquals('Namespace\\\\Nested\\\\Controller', $action['controller']);\n+ $this->assertEquals('Namespace\\\\Nested\\\\Controller@action', $action['controller']);\n \n $router = $this->getRouter();\n $router->group(['prefix' => 'baz'], function () use ($router) {\n $router->group(['namespace' => 'Namespace'], function () use ($router) {\n- $router->get('foo/bar', 'Controller');\n+ $router->get('foo/bar', 'Controller@action');\n });\n });\n $routes = $router->getRoutes()->getRoutes();\n $action = $routes[0]->getAction();\n \n- $this->assertEquals('Namespace\\\\Controller', $action['controller']);\n+ $this->assertEquals('Namespace\\\\Controller@action', $action['controller']);\n+ }\n+\n+ /**\n+ * @expectedException UnexpectedValueException\n+ */\n+ public function testInvalidActionException()\n+ {\n+ $router = $this->getRouter();\n+ $router->get('/', ['uses' => 'Controller']);\n }\n \n public function testResourceRouting()", "filename": "tests/Routing/RoutingRouteTest.php", "status": "modified" } ] }
{ "body": "When using the new unit testing functionality and the form filling function `type` it wont let me target form field with a name containing a square bracket.\n\n``` html\n<input type=\"text\" name=\"address[line_1]\" />\n```\n\n``` php\n$this->type($faker->streetAddress, 'address[line_1]');\n```\n\nIt has trouble with the bracket and returns the following\n\n```\nSymfony\\Component\\CssSelector\\Exception\\SyntaxErrorException: Expected \"]\", but <delimiter \"[\" at 33> found.\n```\n\nEscaping the square brackets doesn't seem to be an option either.\n", "comments": [], "number": 9090, "title": "[5.1] phpunit 'type' function doesn't support square brackets for the name" }
{ "body": "This should fix #9090 \n\nIf you are using the type method like this:\n\n```\n$this->type($faker->streetAddress, 'address[line_1]');\n```\n\nIt will now generate a selection string like this:\n\n```\n*#email[address], *[name='email[address]']\n```\n", "number": 9120, "review_comments": [], "title": "[5.1] Fixes issue selecting name attribute containing brackets" }
{ "commits": [ { "message": "Update filter selection string" } ], "files": [ { "diff": "@@ -578,7 +578,7 @@ protected function filterByNameOrId($name, $element = '*')\n {\n $name = str_replace('#', '', $name);\n \n- return $this->crawler->filter(\"{$element}#{$name}, {$element}[name={$name}]\");\n+ return $this->crawler->filter(\"{$element}#{$name}, {$element}[name='{$name}']\");\n }\n \n /**", "filename": "src/Illuminate/Foundation/Testing/CrawlerTrait.php", "status": "modified" } ] }
{ "body": "When using the new unit testing functionality and the form filling function `type` it wont let me target form field with a name containing a square bracket.\n\n``` html\n<input type=\"text\" name=\"address[line_1]\" />\n```\n\n``` php\n$this->type($faker->streetAddress, 'address[line_1]');\n```\n\nIt has trouble with the bracket and returns the following\n\n```\nSymfony\\Component\\CssSelector\\Exception\\SyntaxErrorException: Expected \"]\", but <delimiter \"[\" at 33> found.\n```\n\nEscaping the square brackets doesn't seem to be an option either.\n", "comments": [], "number": 9090, "title": "[5.1] phpunit 'type' function doesn't support square brackets for the name" }
{ "body": "This should fix #9090 \n\nIf you are using the type method like this:\n\n```\n$this->type($faker->streetAddress, 'address[line_1]');\n```\n\nIt will now generate a selection string like this:\n\n```\n*#email[address], *[name='email[address]']\n```\n", "number": 9119, "review_comments": [], "title": "Fixes issue selecting name attribute containing brackets (#9090)" }
{ "commits": [ { "message": "Update filter selection string" } ], "files": [ { "diff": "@@ -578,7 +578,7 @@ protected function filterByNameOrId($name, $element = '*')\n {\n $name = str_replace('#', '', $name);\n \n- return $this->crawler->filter(\"{$element}#{$name}, {$element}[name={$name}]\");\n+ return $this->crawler->filter(\"{$element}#{$name}, {$element}[name='{$name}']\");\n }\n \n /**", "filename": "src/Illuminate/Foundation/Testing/CrawlerTrait.php", "status": "modified" } ] }
{ "body": "// cc @0xbb\n", "comments": [ { "body": "@GrahamCampbell thanks! looks good to me\n", "created_at": "2015-06-03T16:33:21Z" } ], "number": 9033, "title": "[5.0] Make sure our random strings are the correct length" }
{ "body": "Applies #9033 to 5.1.\n", "number": 9034, "review_comments": [], "title": "[5.1] Make sure our random strings are the correct length" }
{ "commits": [ { "message": "Make sure our random strings are the correct length\n\nApplies #9033 to 5.1." } ], "files": [ { "diff": "@@ -233,7 +233,13 @@ public static function random($length = 16)\n throw new RuntimeException('OpenSSL extension is required for PHP 5 users.');\n }\n \n- return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);\n+ $string = substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);\n+\n+ while (($len = strlen($string)) < $length) {\n+ $string .= static::random($length - $len);\n+ }\n+\n+ return $string;\n }\n \n /**", "filename": "src/Illuminate/Support/Str.php", "status": "modified" } ] }
{ "body": "_Fixes #8795_\n\nThe relation shouldn't add a table prefix, this is taken care of in `\\Illuminate\\Database\\Grammar@wrapTable`.\n\nSince adding just a few integration test methods that use a connection with table prefix would be needlessly complicated, I decided to add a test class that extends the original integration test and runs the same checks with prefixed tables.\n", "comments": [ { "body": "Looks good to me. :)\n", "created_at": "2015-05-31T18:20:21Z" }, { "body": "@lukasgeiter Please could you send a PR for this to 5.1. In it's current form, the tests fail.\n", "created_at": "2015-06-02T15:48:12Z" }, { "body": "Sure, will do.\n", "created_at": "2015-06-02T16:02:52Z" }, { "body": "Thank you. We were having trouble with it. :)\n", "created_at": "2015-06-02T16:23:39Z" }, { "body": "Done. I think the problem was that you added the relationship methods (`childPosts` and `parentPost`) to the wrong test model...\n", "created_at": "2015-06-02T17:14:02Z" }, { "body": "Oh, thank you. :)\n", "created_at": "2015-06-02T17:38:03Z" } ], "number": 8859, "title": "[5.0] Fix has() on self referencing relationship with table prefix" }
{ "body": "#8859 for 5.1\n", "number": 8998, "review_comments": [], "title": "[5.1] Fix has() on self referencing relationship with table prefix" }
{ "commits": [ { "message": "Fix has() on self referencing relationship with table prefix" } ], "files": [ { "diff": "@@ -107,9 +107,7 @@ public function getRelationCountQueryForSelfRelation(Builder $query, Builder $pa\n {\n $query->select(new Expression('count(*)'));\n \n- $tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n-\n- $query->from($query->getModel()->getTable().' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+ $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());\n \n $key = $this->wrap($this->getQualifiedForeignKey());\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsTo.php", "status": "modified" }, { "diff": "@@ -325,9 +325,7 @@ public function getRelationCountQueryForSelfJoin(Builder $query, Builder $parent\n {\n $query->select(new Expression('count(*)'));\n \n- $tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n-\n- $query->from($this->table.' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+ $query->from($this->table.' as '.$hash = $this->getRelationCountHash());\n \n $key = $this->wrap($this->getQualifiedParentKeyName());\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php", "status": "modified" }, { "diff": "@@ -81,9 +81,7 @@ public function getRelationCountQueryForSelfRelation(Builder $query, Builder $pa\n {\n $query->select(new Expression('count(*)'));\n \n- $tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n-\n- $query->from($query->getModel()->getTable().' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+ $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());\n \n $key = $this->wrap($this->getQualifiedParentKeyName());\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php", "status": "modified" }, { "diff": "@@ -52,6 +52,7 @@ public function setUp()\n $this->schema()->create('posts', function ($table) {\n $table->increments('id');\n $table->integer('user_id');\n+ $table->integer('parent_id')->nullable();\n $table->string('name');\n $table->timestamps();\n });\n@@ -262,6 +263,28 @@ public function testHasOnSelfReferencingBelongsToManyRelationship()\n $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n }\n \n+ public function testHasOnSelfReferencingBelongsToRelationship()\n+ {\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);\n+\n+ $results = EloquentTestPost::has('parentPost')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Child Post', $results->first()->name);\n+ }\n+\n+ public function testHasOnSelfReferencingHasManyRelationship()\n+ {\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);\n+\n+ $results = EloquentTestPost::has('childPosts')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Parent Post', $results->first()->name);\n+ }\n+\n public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()\n {\n $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n@@ -441,6 +464,14 @@ public function photos()\n {\n return $this->morphMany('EloquentTestPhoto', 'imageable');\n }\n+ public function childPosts()\n+ {\n+ return $this->hasMany('EloquentTestPost', 'parent_id');\n+ }\n+ public function parentPost()\n+ {\n+ return $this->belongsTo('EloquentTestPost', 'parent_id');\n+ }\n }\n \n class EloquentTestPhoto extends Eloquent", "filename": "tests/Database/DatabaseEloquentIntegrationTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,36 @@\n+<?php\n+\n+use Illuminate\\Database\\Eloquent\\Model as Eloquent;\n+\n+class DatabaseEloquentIntegrationWithTablePrefixTest extends DatabaseEloquentIntegrationTest\n+{\n+ /**\n+ * Bootstrap Eloquent.\n+ *\n+ * @return void\n+ */\n+ public static function setUpBeforeClass()\n+ {\n+ $resolver = new DatabaseIntegrationTestConnectionResolver;\n+ $resolver->connection()->setTablePrefix('prefix_');\n+ Eloquent::setConnectionResolver($resolver);\n+\n+ Eloquent::setEventDispatcher(\n+ new Illuminate\\Events\\Dispatcher\n+ );\n+ }\n+\n+ public function testBasicModelHydration()\n+ {\n+ EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ EloquentTestUser::create(['email' => 'abigailotwell@gmail.com']);\n+\n+ $models = EloquentTestUser::hydrateRaw('SELECT * FROM prefix_users WHERE email = ?', ['abigailotwell@gmail.com'], 'foo_connection');\n+\n+ $this->assertInstanceOf('Illuminate\\Database\\Eloquent\\Collection', $models);\n+ $this->assertInstanceOf('EloquentTestUser', $models[0]);\n+ $this->assertEquals('abigailotwell@gmail.com', $models[0]->email);\n+ $this->assertEquals('foo_connection', $models[0]->getConnectionName());\n+ $this->assertEquals(1, $models->count());\n+ }\n+}", "filename": "tests/Database/DatabaseEloquentIntegrationWithTablePrefixTest.php", "status": "added" } ] }
{ "body": "_Fixes #8795_\n\nThe relation shouldn't add a table prefix, this is taken care of in `\\Illuminate\\Database\\Grammar@wrapTable`.\n\nSince adding just a few integration test methods that use a connection with table prefix would be needlessly complicated, I decided to add a test class that extends the original integration test and runs the same checks with prefixed tables.\n", "comments": [ { "body": "Looks good to me. :)\n", "created_at": "2015-05-31T18:20:21Z" }, { "body": "@lukasgeiter Please could you send a PR for this to 5.1. In it's current form, the tests fail.\n", "created_at": "2015-06-02T15:48:12Z" }, { "body": "Sure, will do.\n", "created_at": "2015-06-02T16:02:52Z" }, { "body": "Thank you. We were having trouble with it. :)\n", "created_at": "2015-06-02T16:23:39Z" }, { "body": "Done. I think the problem was that you added the relationship methods (`childPosts` and `parentPost`) to the wrong test model...\n", "created_at": "2015-06-02T17:14:02Z" }, { "body": "Oh, thank you. :)\n", "created_at": "2015-06-02T17:38:03Z" } ], "number": 8859, "title": "[5.0] Fix has() on self referencing relationship with table prefix" }
{ "body": "This is a port of #8859 that was merged into 5.0, for 5.1.\n", "number": 8996, "review_comments": [], "title": "[5.1] Fix has() on self referencing relationship with table prefix" }
{ "commits": [ { "message": "Fix has() on self referencing relationship with table prefix\n\nThis is a port of #8859 that was merged into 5.0, for 5.1." } ], "files": [ { "diff": "@@ -107,9 +107,7 @@ public function getRelationCountQueryForSelfRelation(Builder $query, Builder $pa\n {\n $query->select(new Expression('count(*)'));\n \n- $tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n-\n- $query->from($query->getModel()->getTable().' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+ $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());\n \n $key = $this->wrap($this->getQualifiedForeignKey());\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsTo.php", "status": "modified" }, { "diff": "@@ -325,9 +325,7 @@ public function getRelationCountQueryForSelfJoin(Builder $query, Builder $parent\n {\n $query->select(new Expression('count(*)'));\n \n- $tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n-\n- $query->from($this->table.' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+ $query->from($this->table.' as '.$hash = $this->getRelationCountHash());\n \n $key = $this->wrap($this->getQualifiedParentKeyName());\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php", "status": "modified" }, { "diff": "@@ -81,9 +81,7 @@ public function getRelationCountQueryForSelfRelation(Builder $query, Builder $pa\n {\n $query->select(new Expression('count(*)'));\n \n- $tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n-\n- $query->from($query->getModel()->getTable().' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+ $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());\n \n $key = $this->wrap($this->getQualifiedParentKeyName());\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php", "status": "modified" }, { "diff": "@@ -52,6 +52,7 @@ public function setUp()\n $this->schema()->create('posts', function ($table) {\n $table->increments('id');\n $table->integer('user_id');\n+ $table->integer('parent_id')->nullable();\n $table->string('name');\n $table->timestamps();\n });\n@@ -262,6 +263,28 @@ public function testHasOnSelfReferencingBelongsToManyRelationship()\n $this->assertEquals('taylorotwell@gmail.com', $results->first()->email);\n }\n \n+ public function testHasOnSelfReferencingBelongsToRelationship()\n+ {\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);\n+\n+ $results = EloquentTestPost::has('parentPost')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Child Post', $results->first()->name);\n+ }\n+\n+ public function testHasOnSelfReferencingHasManyRelationship()\n+ {\n+ $parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);\n+ $childPost = EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);\n+\n+ $results = EloquentTestPost::has('childPosts')->get();\n+\n+ $this->assertEquals(1, count($results));\n+ $this->assertEquals('Parent Post', $results->first()->name);\n+ }\n+\n public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()\n {\n $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n@@ -427,6 +450,14 @@ public function photos()\n {\n return $this->morphMany('EloquentTestPhoto', 'imageable');\n }\n+ public function childPosts()\n+ {\n+ return $this->hasMany('EloquentTestPost', 'parent_id');\n+ }\n+ public function parentPost()\n+ {\n+ return $this->belongsTo('EloquentTestPost', 'parent_id');\n+ }\n }\n \n class EloquentTestPost extends Eloquent", "filename": "tests/Database/DatabaseEloquentIntegrationTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,38 @@\n+<?php\n+\n+use Illuminate\\Database\\Eloquent\\Model as Eloquent;\n+\n+class DatabaseEloquentIntegrationWithTablePrefixTest extends DatabaseEloquentIntegrationTest\n+{\n+ /**\n+ * Bootstrap Eloquent.\n+ *\n+ * @return void\n+ */\n+ public static function setUpBeforeClass()\n+ {\n+ $resolver = new DatabaseIntegrationTestConnectionResolver;\n+ $resolver->connection()->setTablePrefix('prefix_');\n+ Eloquent::setConnectionResolver($resolver);\n+\n+ Eloquent::setEventDispatcher(\n+ new Illuminate\\Events\\Dispatcher\n+ );\n+ }\n+\n+ public function testBasicModelHydration()\n+ {\n+ EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);\n+ EloquentTestUser::create(['email' => 'abigailotwell@gmail.com']);\n+\n+ $models = EloquentTestUser::hydrateRaw(\n+ 'SELECT * FROM prefix_users WHERE email = ?', ['abigailotwell@gmail.com'], 'foo_connection'\n+ );\n+\n+ $this->assertInstanceOf('Illuminate\\Database\\Eloquent\\Collection', $models);\n+ $this->assertInstanceOf('EloquentTestUser', $models[0]);\n+ $this->assertEquals('abigailotwell@gmail.com', $models[0]->email);\n+ $this->assertEquals('foo_connection', $models[0]->getConnectionName());\n+ $this->assertEquals(1, $models->count());\n+ }\n+}", "filename": "tests/Database/DatabaseEloquentIntegrationWithTablePrefixTest.php", "status": "added" } ] }
{ "body": "If you have 20 items per page on the paginator and you have 21 items, if someone else comes along and deletes one item leaving only 20, now there's only 1 page if the other person then refreshes they are still on page 2 and the paginator returns no results.\n\n``` php\n$model->paginate(20);\n```\n\nShould the paginator not throw an Exception to catch them being out of bounds, or as most paginators do show the last possible page if there are any results at all.\n", "comments": [ { "body": "I would quite like to see something like this also, I've encountered this problem before. I think an Exception should be thrown that can be dealt with personally.\n", "created_at": "2015-04-14T20:13:39Z" }, { "body": "Apparently there's some weird issue where this occurs on another installation on the latest 5.0.\\* and 5.0.5 it appears to be working.\n", "created_at": "2015-04-26T22:04:49Z" }, { "body": "I noticed this same behavior today and did a little digging. If you navigate beyond the last page, it's supposed to show you the last page. The cause of the issue is in [`Illuminate\\Database\\Eloquent\\Builder`](https://github.com/laravel/framework/blob/45495066373ff6daa314f6550cab2b3de16f26f7/src/Illuminate/Database/Eloquent/Builder.php#L265). It [resolves the current page number](https://github.com/laravel/framework/blob/79f15d98809a48274a281dfae7fa69d66bf734d7/src/Illuminate/Pagination/PaginationServiceProvider.php#L21) and uses the result without validating it like [`Illuminate\\Pagination\\LengthAwarePaginator`](https://github.com/laravel/framework/blob/57695c173ffddaa45eb5b5d958b80086bb3c9547/src/Illuminate/Pagination/LengthAwarePaginator.php#L64-L72) does. The resulting query still offsets the results by the out-of-bounds page number instead of the corrected page number used in the paginator.\n", "created_at": "2015-05-31T23:00:01Z" }, { "body": "@cs475x If you could send a PR, though would be great. :)\n", "created_at": "2015-06-01T09:16:46Z" } ], "number": 8252, "title": "Paginator Exceeding Pages" }
{ "body": "… current page being used.\n\nI.e you have 61 items 30 per page, you have 3 pages, one user deletes an item now you have 2 pages of 60 items, another user refreshes on page 3 and they are stuck on a page without any results or pagination links.\n\nFixes #8252\n", "number": 8968, "review_comments": [ { "body": "Don't align these please.\n", "created_at": "2015-06-01T12:58:00Z" }, { "body": "You can't have a parameter without a default following parameters with a default.\n", "created_at": "2015-06-01T12:58:40Z" }, { "body": "Please don't change this\n", "created_at": "2015-06-01T14:31:19Z" } ], "title": "[5.2] Added fix for last page on pagination query builder being ignored and…" }
{ "commits": [ { "message": "Added fix for last page on pagination query builder being ignored and current page being used.\n\nI.e you have 61 items 30 per page, you have 3 pages, one user deletes an item now you have 2 pages of 60 items, another user refreshes on page 3 and they are stuck on a page without any results or pagination links." }, { "message": "Update AbstractPaginator.php" }, { "message": "Update AbstractPaginator.php" } ], "files": [ { "diff": "@@ -261,9 +261,12 @@ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page')\n \t{\n \t\t$total = $this->query->getCountForPagination();\n \n+\t\t$perPage = $perPage ?: $this->model->getPerPage();\n+\t\t$lastPage = ceil($total / $perPage);\n+\n \t\t$this->query->forPage(\n-\t\t\t$page = Paginator::resolveCurrentPage($pageName),\n-\t\t\t$perPage = $perPage ?: $this->model->getPerPage()\n+\t\t\t$page = Paginator::resolveCurrentPage($pageName, 1, $lastPage),\n+\t\t\t$perPage\n \t\t);\n \n \t\treturn new LengthAwarePaginator($this->get($columns), $total, $perPage, $page, [", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -307,13 +307,16 @@ public static function currentPathResolver(Closure $resolver)\n \t *\n \t * @param string $pageName\n \t * @param int $default\n+\t * @param int $lastPage\n \t * @return int\n \t */\n-\tpublic static function resolveCurrentPage($pageName = 'page', $default = 1)\n+\tpublic static function resolveCurrentPage($pageName = 'page', $default = 1, $lastPage = 1)\n \t{\n \t\tif (isset(static::$currentPageResolver))\n \t\t{\n-\t\t\treturn call_user_func(static::$currentPageResolver, $pageName);\n+\t\t\t$page = call_user_func(static::$currentPageResolver, $pageName);\n+\n+\t\t\treturn ($page > $lastPage) ? $lastPage : $page;\n \t\t}\n \n \t\treturn $default;", "filename": "src/Illuminate/Pagination/AbstractPaginator.php", "status": "modified" } ] }
{ "body": "Fixes #6386 in 5.0.\n", "comments": [ { "body": "Let's just check if the relation is empty as was suggested instead of adding this to the collection.\n", "created_at": "2015-03-24T20:53:56Z" }, { "body": "Also if transform is an array_map shouldn't you be returning a value in your Closure?\n", "created_at": "2015-03-24T20:59:32Z" }, { "body": "I'm just a little nervous this hasn't even been tested since the transform had absolutely no return.\n", "created_at": "2015-03-26T15:10:06Z" }, { "body": "@taylorotwell I'm testing a few scenarios first as per your first suggestion (check if empty and perhaps not add this to Collection). I'll update the PR ASAP. I'm just lagging behind.\n", "created_at": "2015-03-26T15:12:21Z" }, { "body": "Can be re-opened when ready to merge.\n", "created_at": "2015-04-04T14:32:19Z" } ], "number": 8128, "title": "[5.0] Add touchOwners method to DB/Eloquent/Collection" }
{ "body": "Fixes #6386 in 5.0. Re-post of #8128 after testing several scenarios.\n", "number": 8371, "review_comments": [], "title": "[5.0] Adjusting Model::touchOwners to not touch on creation" }
{ "commits": [ { "message": "Adjusting Model::touchOwners to not touch on creation" }, { "message": "Using both not null and count now" } ], "files": [ { "diff": "@@ -1622,7 +1622,7 @@ public function touchOwners()\n \t\t{\n \t\t\t$this->$relation()->touch();\n \n-\t\t\tif ( ! is_null($this->$relation))\n+\t\t\tif (!is_null($this->$relation) && count($this->$relation))\n \t\t\t{\n \t\t\t\t$this->$relation->touchOwners();\n \t\t\t}", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" } ] }
{ "body": "You can set up a pair of Eloquent models like this:\n\n```\nclass Product extends \\Eloquent {\n public function assets() {\n return $this->belongsToMany('Asset');\n }\n}\n\nclass Asset extends \\Eloquent {\n protected $touches = [ 'products' ];\n\n public function products() {\n return $this->belongsToMany('Product');\n }\n}\n```\n\nBy doing this, you can call\n\n```\nProduct::find( $validProductId )->assets()->attach( $validAssetId );\n```\n\nthe `Asset` will go and update the `updated_at` field on every related `Product` to indicate that its relations have changed.\n\nHowever, if you make a new `Asset`, or take an `Asset` which has no related `Product`s yet, you'll get a fatal error as the `Model::touchOwners` method only checks if `$this->relation` isn't null:\n\n```\npublic function touchOwners()\n{\n foreach ($this->touches as $relation)\n {\n $this->$relation()->touch();\n\n if ( ! is_null($this->$relation)) // this is the problem\n {\n $this->$relation->touchOwners();\n }\n }\n}\n```\n\nI have a tentative fix in place locally (for now) by just adding in a check for `&& ! $this->$relation->isEmpty()`, but that may affect other relations, I'm not sure:\n\n```\npublic function touchOwners()\n{\n foreach ($this->touches as $relation)\n {\n $this->$relation()->touch();\n\n if ( ! is_null($this->$relation) && ! $this->$relation->isEmpty())\n {\n $this->$relation->touchOwners();\n }\n }\n}\n```\n", "comments": [ { "body": "The problem exists since 4.2.9, but **solution suggested doesn't solve it** AND **it causes error on any other relation**. The error is not triggered, when there are no related models in that collection, but because `Eloquent\\Collection` has no `touchOwners` method defined.\nAlso, it doesn't matter whether there are or not any related models. Your example with `attach` works differently, for it calls `touch` directly on the involved models.\n\nSo that method needs to be added and handle the propagation for all its elements.\n\nNow, your way of handling it is wrong, because there's no `isEmpty` method on the `Model`.\nYou could use `count` instead (see this http://stackoverflow.com/a/23911985/784588):\n\n```\nif (count($this->$relation))\n{\n $this->$relation->touchOwners();\n}\n```\n\nthis way it wouldn't call the method for empty relation, which is slightly better.\n", "created_at": "2014-11-29T15:07:43Z" }, { "body": "is this still an issue please?\n", "created_at": "2014-12-28T14:20:37Z" }, { "body": "Another example (from #6932):\n\n``` php\nclass Address extends Eloquent\n{\n public $touches = ['people'];\n\n public function people()\n {\n return $this->morphedByMany('Person', 'addressable');\n }\n}\n```\n\n``` php\nclass Person extends Eloquent\n{\n public function addresses()\n {\n return $this->morphToMany('Address', 'addressable');\n }\n}\n```\n\nSaving an Address throws `'Symfony\\Component\\Debug\\Exception\\FatalErrorException' with message 'Call to undefined method Illuminate\\Database\\Eloquent\\Collection::touchOwners()`. I'm guessing the model's touchOwners should be looping through the collection since I cannot seem to find a touchOwners() method anywhere but on the Model.\n", "created_at": "2015-01-07T18:10:37Z" }, { "body": "Can someone please send a pull to fix this?\n", "created_at": "2015-01-30T20:47:07Z" }, { "body": "Still an issue... isn't it? Have to stay at 4.2.6 to avoid that \n", "created_at": "2015-03-24T07:04:10Z" }, { "body": "Added PR for 4.2. Looks like it can apply to 5.0 pretty easily.\n", "created_at": "2015-03-24T16:41:02Z" }, { "body": "@impleri Could you send a pull to 5.0 please?\n", "created_at": "2015-03-24T17:34:09Z" }, { "body": "Sure can. Patch applied cleanly from original PR and local testing still passes.\n", "created_at": "2015-03-24T17:56:38Z" }, { "body": "Thanks guys. Further discussion can take place on the pull. :)\n", "created_at": "2015-03-24T17:57:12Z" } ], "number": 6386, "title": "$touches causes fatal error if no ManyToMany relations exist" }
{ "body": "Fixes #6386 in 5.0. Re-post of #8128 after testing several scenarios.\n", "number": 8371, "review_comments": [], "title": "[5.0] Adjusting Model::touchOwners to not touch on creation" }
{ "commits": [ { "message": "Adjusting Model::touchOwners to not touch on creation" }, { "message": "Using both not null and count now" } ], "files": [ { "diff": "@@ -1622,7 +1622,7 @@ public function touchOwners()\n \t\t{\n \t\t\t$this->$relation()->touch();\n \n-\t\t\tif ( ! is_null($this->$relation))\n+\t\t\tif (!is_null($this->$relation) && count($this->$relation))\n \t\t\t{\n \t\t\t\t$this->$relation->touchOwners();\n \t\t\t}", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" } ] }
{ "body": "", "comments": [ { "body": "I've just came to idea that we can allow root mapping for index and create.\nAnd also we can implement extra option to set wildcard and allow root mapping with it.\n", "created_at": "2015-04-08T11:38:20Z" } ], "number": 8335, "title": "[5.0] Prevent resource route root binding" }
{ "body": "Alternative to #8335\nAllows to map root uri only if it has `wildcard` option or does not require any wildcard.\n", "number": 8339, "review_comments": [], "title": "[5.0] Wildcard option for resource routing" }
{ "commits": [ { "message": "Prevent resource route root binding" }, { "message": "Fix coding style" }, { "message": "Wildcard option for resource routing" } ], "files": [ { "diff": "@@ -1,5 +1,7 @@\n <?php namespace Illuminate\\Routing;\n \n+use InvalidArgumentException;\n+\n class ResourceRegistrar {\n \n \t/**\n@@ -34,9 +36,23 @@ public function __construct(Router $router)\n \t * @param string $controller\n \t * @param array $options\n \t * @return void\n+\t *\n+\t * @throws \\InvalidArgumentException\n \t */\n \tpublic function register($name, $controller, array $options = array())\n \t{\n+\t\t$methods = $this->getResourceMethods($this->resourceDefaults, $options);\n+\n+\t\tif (empty($name) || $name == '/')\n+\t\t{\n+\t\t\t$check = array_intersect($methods, ['store', 'show', 'edit', 'update', 'destroy']);\n+\n+\t\t\tif (!empty($check) && !isset($options['wildcard']))\n+\t\t\t{\n+\t\t\t\tthrow new InvalidArgumentException('Resource routing is not available for root url');\n+\t\t\t}\n+\t\t}\n+\n \t\t// If the resource name contains a slash, we will assume the developer wishes to\n \t\t// register these resource routes with a prefix so we will set that up out of\n \t\t// the box so they don't have to mess with it. Otherwise, we will continue.\n@@ -50,11 +66,9 @@ public function register($name, $controller, array $options = array())\n \t\t// We need to extract the base resource from the resource name. Nested resources\n \t\t// are supported in the framework, but we need to know what name to use for a\n \t\t// place-holder on the route wildcards, which should be the base resources.\n-\t\t$base = $this->getResourceWildcard(last(explode('.', $name)));\n-\n-\t\t$defaults = $this->resourceDefaults;\n+\t\t$base = (isset($options['wildcard'])) ? $options['wildcard'] : $this->getResourceWildcard(last(explode('.', $name)));\n \n-\t\tforeach ($this->getResourceMethods($defaults, $options) as $m)\n+\t\tforeach ($methods as $m)\n \t\t{\n \t\t\t$this->{'addResource'.ucfirst($m)}($name, $base, $controller, $options);\n \t\t}\n@@ -195,7 +209,8 @@ protected function getResourceName($resource, $method, $options)\n \n \t\tif ( ! $this->router->hasGroupStack())\n \t\t{\n-\t\t\treturn $prefix.$resource.'.'.$method;\n+\t\t\t$resource = $prefix.$resource;\n+\t\t\treturn (!empty($resource)) ? $resource.'.'.$method : $method;\n \t\t}\n \n \t\treturn $this->getGroupResourceName($prefix, $resource, $method);", "filename": "src/Illuminate/Routing/ResourceRegistrar.php", "status": "modified" }, { "diff": "@@ -724,6 +724,36 @@ public function testResourceRouting()\n \t}\n \n \n+\tpublic function testResourceWildcard()\n+\t{\n+\t\t$router = $this->getRouter();\n+\t\t$router->resource('foo', 'FooController', array('only' => array('show'), 'wildcard' => 'bar'));\n+\t\t$routes = $router->getRoutes();\n+\t\t$routes = $routes->getRoutes();\n+\n+\t\t$this->assertEquals('foo/{bar}', $routes[0]->getUri());\n+\t\t$this->assertEquals('foo.show', $routes[0]->getName());\n+\n+\t\t$router = $this->getRouter();\n+\t\t$router->resource('/', 'FooController', array('only' => array('show'), 'wildcard' => 'bar'));\n+\t\t$routes = $router->getRoutes();\n+\t\t$routes = $routes->getRoutes();\n+\n+\t\t$this->assertEquals('{bar}', $routes[0]->getUri());\n+\t\t$this->assertEquals('show', $routes[0]->getName());\n+\t}\n+\n+\n+\t/**\n+\t * @expectedException InvalidArgumentException\n+\t */\n+\tpublic function testResourceRoutingException()\n+\t{\n+\t\t$router = $this->getRouter();\n+\t\t$router->resource('/', 'FooController');\n+\t}\n+\n+\n \tpublic function testResourceRouteNaming()\n \t{\n \t\t$router = $this->getRouter();", "filename": "tests/Routing/RoutingRouteTest.php", "status": "modified" } ] }
{ "body": "I have:\n\n``` <?php\nclass Category extends Eloquent\n{\n public function parent()\n {\n return $this->belongsTo('Category', 'par_cat');\n }\n\n public function children()\n {\n return $this->hasMany('Category', 'par_cat', 'id');\n }\n}\n```\n\nWhen I use code:\n\n```\n$cat = Category::with('children', 'parent')->get();\n\nforeach ($cat as $c) {\n echo $c->name.' ';\n\n echo \" children: \".count($c->children);\n echo \" parent: \".(($c->parent) ? $c->parent->name : 'none');\n\n\necho \"<br />\";\n}\n```\n\neverything is fine, I get:\n\n```\na children: 5 parent: none\nb children: 5 parent: none\nc children: 0 parent: none\nd children: 0 parent: none\ne children: 0 parent: none\na1 children: 0 parent: a\na2 children: 0 parent: a\na3 children: 0 parent: a\na4 children: 0 parent: a\na5 children: 0 parent: a\nb1 children: 0 parent: b\nb2 children: 0 parent: b\nb3 children: 0 parent: b\nb4 children: 0 parent: b\nb5 children: 0 parent: b\n```\n\nSo everything works fine here.\n\nNow I want to get only categories that has children (only 2 categories should be selected - a and b (they both have 5 children).\n\nSo I use:\n\n```\n$cat = Category::has('children')->get();\necho count($cat);\n```\n\nExpected result here is 2 and I get 0.\n\nThe query that is being launched using above code is:\n\n```\nselect * from `categories` where (select count(*) from `categories` where `categories`.`par_cat` = `categories`.`id`) >= 1;\n```\n\nand it should be probably:\n\n```\nselect * from `categories` where (select count(*) from `categories` `c2` inner join `categories` `c3` on `c2`.`par_cat` = `c3`.`id` where `c3`.`id` = `categories`.`id`) >= 1;\n```\n\nto get desired effect\n", "comments": [ { "body": "Maybe you could submit a failing test case or even a fix for this? A failing test can be useful if anyone else is up for fixing this, so they can implement a fix knowing it does what you want.\n", "created_at": "2014-10-22T21:24:16Z" } ], "number": 6190, "title": "Querying self relationship - has" }
{ "body": "Fix issue #6190\n", "number": 8193, "review_comments": [], "title": "[5.0] Fix Querying self relationship" }
{ "commits": [ { "message": "Self relation fix" } ], "files": [ { "diff": "@@ -84,13 +84,48 @@ public function addConstraints()\n \t */\n \tpublic function getRelationCountQuery(Builder $query, Builder $parent)\n \t{\n+\t\tif ($parent->getQuery()->from == $query->getQuery()->from)\n+\t\t{\n+\t\t\treturn $this->getRelationCountQueryForSelfRelation($query, $parent);\n+\t\t}\n+\n \t\t$query->select(new Expression('count(*)'));\n \n \t\t$otherKey = $this->wrap($query->getModel()->getTable().'.'.$this->otherKey);\n \n \t\treturn $query->where($this->getQualifiedForeignKey(), '=', new Expression($otherKey));\n \t}\n \n+\t/**\n+\t * Add the constraints for a relationship count query on the same table.\n+\t *\n+\t * @param \\Illuminate\\Database\\Eloquent\\Builder $query\n+\t * @param \\Illuminate\\Database\\Eloquent\\Builder $parent\n+\t * @return \\Illuminate\\Database\\Eloquent\\Builder\n+\t */\n+\tpublic function getRelationCountQueryForSelfRelation(Builder $query, Builder $parent)\n+\t{\n+\t\t$query->select(new Expression('count(*)'));\n+\n+\t\t$tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n+\n+\t\t$query->from($query->getModel()->getTable().' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+\n+\t\t$key = $this->wrap($this->getQualifiedForeignKey());\n+\n+\t\treturn $query->where($hash.'.'.$query->getModel()->getKeyName(), '=', new Expression($key));\n+\t}\n+\n+\t/**\n+\t * Get a relationship join table hash.\n+\t *\n+\t * @return string\n+\t */\n+\tpublic function getRelationCountHash()\n+\t{\n+\t\treturn 'self_'.md5(microtime(true));\n+\t}\n+\n \t/**\n \t * Set the constraints for an eager load of the relation.\n \t *", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsTo.php", "status": "modified" }, { "diff": "@@ -2,6 +2,7 @@\n \n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Database\\Eloquent\\Builder;\n+use Illuminate\\Database\\Query\\Expression;\n use Illuminate\\Database\\Eloquent\\Collection;\n \n abstract class HasOneOrMany extends Relation {\n@@ -50,6 +51,53 @@ public function addConstraints()\n \t\t}\n \t}\n \n+\t/**\n+\t * Add the constraints for a relationship count query.\n+\t *\n+\t * @param \\Illuminate\\Database\\Eloquent\\Builder $query\n+\t * @param \\Illuminate\\Database\\Eloquent\\Builder $parent\n+\t * @return \\Illuminate\\Database\\Eloquent\\Builder\n+\t */\n+\tpublic function getRelationCountQuery(Builder $query, Builder $parent)\n+\t{\n+\t\tif ($parent->getQuery()->from == $query->getQuery()->from)\n+\t\t{\n+\t\t\treturn $this->getRelationCountQueryForSelfRelation($query, $parent);\n+\t\t}\n+\n+\t\treturn parent::getRelationCountQuery($query, $parent);\n+\t}\n+\n+\t/**\n+\t * Add the constraints for a relationship count query on the same table.\n+\t *\n+\t * @param \\Illuminate\\Database\\Eloquent\\Builder $query\n+\t * @param \\Illuminate\\Database\\Eloquent\\Builder $parent\n+\t * @return \\Illuminate\\Database\\Eloquent\\Builder\n+\t */\n+\tpublic function getRelationCountQueryForSelfRelation(Builder $query, Builder $parent)\n+\t{\n+\t\t$query->select(new Expression('count(*)'));\n+\n+\t\t$tablePrefix = $this->query->getQuery()->getConnection()->getTablePrefix();\n+\n+\t\t$query->from($query->getModel()->getTable().' as '.$tablePrefix.$hash = $this->getRelationCountHash());\n+\n+\t\t$key = $this->wrap($this->getQualifiedParentKeyName());\n+\n+\t\treturn $query->where($hash.'.'.$this->getPlainForeignKey(), '=', new Expression($key));\n+\t}\n+\n+\t/**\n+\t * Get a relationship join table hash.\n+\t *\n+\t * @return string\n+\t */\n+\tpublic function getRelationCountHash()\n+\t{\n+\t\treturn 'self_'.md5(microtime(true));\n+\t}\n+\n \t/**\n \t * Set the constraints for an eager load of the relation.\n \t *", "filename": "src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php", "status": "modified" }, { "diff": "@@ -98,15 +98,24 @@ public function testModelsAreProperlyMatchedToParents()\n \tpublic function testRelationCountQueryCanBeBuilt()\n \t{\n \t\t$relation = $this->getRelation();\n-\t\t$query = m::mock('Illuminate\\Database\\Eloquent\\Builder');\n-\t\t$query->shouldReceive('select')->once()->with(m::type('Illuminate\\Database\\Query\\Expression'));\n+\t\t$builder = m::mock('Illuminate\\Database\\Eloquent\\Builder');\n+\n+\t\t$baseQuery = m::mock('Illuminate\\Database\\Query\\Builder');\n+\t\t$baseQuery->from = 'one';\n+\t\t$parentQuery = m::mock('Illuminate\\Database\\Query\\Builder');\n+\t\t$parentQuery->from = 'two';\n+\n+\t\t$builder->shouldReceive('getQuery')->once()->andReturn($baseQuery);\n+\t\t$builder->shouldReceive('getQuery')->once()->andReturn($parentQuery);\n+\n+\t\t$builder->shouldReceive('select')->once()->with(m::type('Illuminate\\Database\\Query\\Expression'));\n \t\t$relation->getParent()->shouldReceive('getTable')->andReturn('table');\n-\t\t$query->shouldReceive('where')->once()->with('table.foreign_key', '=', m::type('Illuminate\\Database\\Query\\Expression'));\n+\t\t$builder->shouldReceive('where')->once()->with('table.foreign_key', '=', m::type('Illuminate\\Database\\Query\\Expression'));\n \t\t$relation->getQuery()->shouldReceive('getQuery')->andReturn($parentQuery = m::mock('StdClass'));\n \t\t$parentQuery->shouldReceive('getGrammar')->once()->andReturn($grammar = m::mock('StdClass'));\n \t\t$grammar->shouldReceive('wrap')->once()->with('table.id');\n \n-\t\t$relation->getRelationCountQuery($query, $query);\n+\t\t$relation->getRelationCountQuery($builder, $builder);\n \t}\n \n ", "filename": "tests/Database/DatabaseEloquentHasOneTest.php", "status": "modified" } ] }
{ "body": "Fixes #7207\n", "comments": [ { "body": "This needs more explanation I think. I don't understand why the \"and\" is hard-coded and all that. If you want to re-submit it, send it to 5.0 branch with more explanation of the fix.\n", "created_at": "2015-02-11T20:34:49Z" }, { "body": "@taylorotwell Have you read that thread linked in the issue? \n1. `and` must be hard-coded for the _inner_ count queries, while `$operator` passed by the developer is used for the _outer_ query. Currently these 2 are swapped:\n2. `$count`, on the other hand, must be placed in the furthest nested query so it concerns `posts` in the below example, while for any relations on the way (`categories` only in this case) it must be hard-coded `1` - but it already works this way, doesn't change with the fix.\n\n```\n// currently:\n[17] > User::where('field', 'value')->orHas('categories.posts')->toSql();\n// 'select * from `users` where `field` = ? \nand // should be OR\n(select count(*) from `categories` inner join `category_user` on `categories`.`id` = `category_user`.`category_id` where `category_user`.`user_id` = `users`.`id` \n or // should be AND\n (select count(*) from `posts` where `posts`.`category_id` = `categories`.`id`) >= 1\n) >= 1'\n```\n\nI will submit to 5\n", "created_at": "2015-02-11T21:37:03Z" } ], "number": 7214, "title": "[4.2] fix or hasNested" }
{ "body": "The same as #7214 only for ver 5.\n\n@taylorotwell As for the explanation you asked for - check the closed PR to 4.2 and mind that I created this `hasNested` feature with this bug to begin with.. \nIt's rather edge case, to call `whereHas(..)->orWhereHas(..)` but still a bug.\n", "number": 8171, "review_comments": [], "title": "[5.0] Fix hasNested boolean operator" }
{ "commits": [ { "message": "[5.0] Fix hasNested boolean operator" } ], "files": [ { "diff": "@@ -593,11 +593,11 @@ protected function hasNested($relations, $operator = '>=', $count = 1, $boolean\n \t\t\t}\n \t\t\telse\n \t\t\t{\n-\t\t\t\t$q->has(array_shift($relations), $operator, $count, $boolean, $callback);\n+\t\t\t\t$q->has(array_shift($relations), $operator, $count, 'and', $callback);\n \t\t\t}\n \t\t};\n \n-\t\treturn $this->whereHas(array_shift($relations), $closure);\n+\t\treturn $this->has(array_shift($relations), '>=', 1, $boolean, $closure);\n \t}\n \n \t/**", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -459,6 +459,22 @@ public function testHasNested()\n \t}\n \n \n+\tpublic function testOrHasNested()\n+\t{\n+\t\t$model = new EloquentBuilderTestModelParentStub;\n+\n+\t\t$builder = $model->whereHas('foo', function ($q) {\n+\t\t\t$q->has('bar');\n+\t\t})->orWhereHas('foo', function ($q) {\n+\t\t\t$q->has('baz');\n+\t\t});\n+\n+\t\t$result = $model->has('foo.bar')->orHas('foo.baz')->toSql();\n+\n+\t\t$this->assertEquals($builder->toSql(), $result);\n+\t}\n+\n+\n \tprotected function mockConnectionForModel($model, $database)\n \t{\n \t\t$grammarClass = 'Illuminate\\Database\\Query\\Grammars\\\\'.$database.'Grammar';\n@@ -541,6 +557,10 @@ public function bar()\n \t{\n \t\treturn $this->hasMany('EloquentBuilderTestModelFarRelatedStub');\n \t}\n+\tpublic function baz()\n+\t{\n+\t\treturn $this->hasMany('EloquentBuilderTestModelFarRelatedStub');\n+\t}\n }\n \n class EloquentBuilderTestModelFarRelatedStub extends Illuminate\\Database\\Eloquent\\Model {}", "filename": "tests/Database/DatabaseEloquentBuilderTest.php", "status": "modified" } ] }
{ "body": "You can set up a pair of Eloquent models like this:\n\n```\nclass Product extends \\Eloquent {\n public function assets() {\n return $this->belongsToMany('Asset');\n }\n}\n\nclass Asset extends \\Eloquent {\n protected $touches = [ 'products' ];\n\n public function products() {\n return $this->belongsToMany('Product');\n }\n}\n```\n\nBy doing this, you can call\n\n```\nProduct::find( $validProductId )->assets()->attach( $validAssetId );\n```\n\nthe `Asset` will go and update the `updated_at` field on every related `Product` to indicate that its relations have changed.\n\nHowever, if you make a new `Asset`, or take an `Asset` which has no related `Product`s yet, you'll get a fatal error as the `Model::touchOwners` method only checks if `$this->relation` isn't null:\n\n```\npublic function touchOwners()\n{\n foreach ($this->touches as $relation)\n {\n $this->$relation()->touch();\n\n if ( ! is_null($this->$relation)) // this is the problem\n {\n $this->$relation->touchOwners();\n }\n }\n}\n```\n\nI have a tentative fix in place locally (for now) by just adding in a check for `&& ! $this->$relation->isEmpty()`, but that may affect other relations, I'm not sure:\n\n```\npublic function touchOwners()\n{\n foreach ($this->touches as $relation)\n {\n $this->$relation()->touch();\n\n if ( ! is_null($this->$relation) && ! $this->$relation->isEmpty())\n {\n $this->$relation->touchOwners();\n }\n }\n}\n```\n", "comments": [ { "body": "The problem exists since 4.2.9, but **solution suggested doesn't solve it** AND **it causes error on any other relation**. The error is not triggered, when there are no related models in that collection, but because `Eloquent\\Collection` has no `touchOwners` method defined.\nAlso, it doesn't matter whether there are or not any related models. Your example with `attach` works differently, for it calls `touch` directly on the involved models.\n\nSo that method needs to be added and handle the propagation for all its elements.\n\nNow, your way of handling it is wrong, because there's no `isEmpty` method on the `Model`.\nYou could use `count` instead (see this http://stackoverflow.com/a/23911985/784588):\n\n```\nif (count($this->$relation))\n{\n $this->$relation->touchOwners();\n}\n```\n\nthis way it wouldn't call the method for empty relation, which is slightly better.\n", "created_at": "2014-11-29T15:07:43Z" }, { "body": "is this still an issue please?\n", "created_at": "2014-12-28T14:20:37Z" }, { "body": "Another example (from #6932):\n\n``` php\nclass Address extends Eloquent\n{\n public $touches = ['people'];\n\n public function people()\n {\n return $this->morphedByMany('Person', 'addressable');\n }\n}\n```\n\n``` php\nclass Person extends Eloquent\n{\n public function addresses()\n {\n return $this->morphToMany('Address', 'addressable');\n }\n}\n```\n\nSaving an Address throws `'Symfony\\Component\\Debug\\Exception\\FatalErrorException' with message 'Call to undefined method Illuminate\\Database\\Eloquent\\Collection::touchOwners()`. I'm guessing the model's touchOwners should be looping through the collection since I cannot seem to find a touchOwners() method anywhere but on the Model.\n", "created_at": "2015-01-07T18:10:37Z" }, { "body": "Can someone please send a pull to fix this?\n", "created_at": "2015-01-30T20:47:07Z" }, { "body": "Still an issue... isn't it? Have to stay at 4.2.6 to avoid that \n", "created_at": "2015-03-24T07:04:10Z" }, { "body": "Added PR for 4.2. Looks like it can apply to 5.0 pretty easily.\n", "created_at": "2015-03-24T16:41:02Z" }, { "body": "@impleri Could you send a pull to 5.0 please?\n", "created_at": "2015-03-24T17:34:09Z" }, { "body": "Sure can. Patch applied cleanly from original PR and local testing still passes.\n", "created_at": "2015-03-24T17:56:38Z" }, { "body": "Thanks guys. Further discussion can take place on the pull. :)\n", "created_at": "2015-03-24T17:57:12Z" } ], "number": 6386, "title": "$touches causes fatal error if no ManyToMany relations exist" }
{ "body": "Fixes #6386 in 5.0.\n", "number": 8128, "review_comments": [ { "body": "Please try to avoid singe line statements like this. They're fine for the tests, but not for src.\n", "created_at": "2015-03-26T15:00:09Z" }, { "body": "Sure can. Was trying to match the styling as in modelKeys()\n\n``` php\npublic function modelKeys()\n{\n return array_map(function($m) { return $m->getKey(); }, $this->items);\n}\n```\n", "created_at": "2015-03-26T15:04:34Z" }, { "body": "@impleri Could you format it like this please: #8173.\n", "created_at": "2015-03-26T15:08:31Z" }, { "body": "@impleri Don't bother changing this btw. Taylor is fine with oneline.\n", "created_at": "2015-03-26T15:14:46Z" } ], "title": "[5.0] Add touchOwners method to DB/Eloquent/Collection" }
{ "commits": [ { "message": "Add touchOwners method to DB/Eloquent/Collection" } ], "files": [ { "diff": "@@ -131,6 +131,16 @@ public function modelKeys()\n \t\treturn array_map(function($m) { return $m->getKey(); }, $this->items);\n \t}\n \n+\t/**\n+\t * Touch the models in the collection.\n+\t *\n+\t * @return void\n+\t */\n+\tpublic function touchOwners()\n+\t{\n+\t\t$this->transform(function($m) { $m->touch(); });\n+\t}\n+\n \t/**\n \t * Merge the collection with the given items.\n \t *", "filename": "src/Illuminate/Database/Eloquent/Collection.php", "status": "modified" }, { "diff": "@@ -245,4 +245,14 @@ public function testExceptReturnsCollectionWithoutGivenModelKeys()\n \t\t$this->assertEquals(new Collection(array($one)), $c->except(array(2, 3)));\n \t}\n \n+\tpublic function testTouchOwnersTouchesModelsInCollection()\n+\t{\n+\t\t$one = m::mock('Illuminate\\Database\\Eloquent\\Model');\n+\t\t$one->shouldReceive('touch');\n+\n+\t\t$c = new Collection(array($one));\n+\n+\t\t$this->assertNull($c->touchOwners());\n+\t}\n+\n }", "filename": "tests/Database/DatabaseEloquentCollectionTest.php", "status": "modified" } ] }