issue
dict
pr
dict
pr_details
dict
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7\r\n- PHP Version: 7.3.14\r\n- Database Driver & Version: MySQL 8\r\n\r\n### Description:\r\nWhen MySQL has `sql_require_primary_key` enabled, migrations that call `->primary()` on a column during table creation fail because it appears as though two queries are ran. One to create the table, and then a second to alter the table and add the primary key.\r\n\r\nFor context, [DigitalOcean recently enforced primary keys on all newly created tables](https://www.digitalocean.com/docs/databases/#5-june-2020) in their managed databases.\r\n\r\n### Steps To Reproduce:\r\n1. Ensure `sql_require_primary_key` is enabled on the MySQL server\r\n2. Create a migration that creates a new table with a string as the primary key (we used `$table->string('string')->primary();`) and does not have a default `$table->id();` column\r\n3. Run the migration\r\n\r\nThe below error is generated when attempting to run the first query to create table.\r\n\r\n```\r\nGeneral error: 3750 Unable to create or change a table without a primary key, when the system variable 'sql_require_primary_key' is set. Add a primary key to the table or unset this variable to avoid this message. Note that tables without a primary key can cause performance problems in row-based replication, so please consult your DBA before changing this setting.\r\n```", "comments": [ { "body": "Hmm this is a tricky one. Apparently the SQL generated to create the table doesn't immediately adds the primary key and thus indeed causes this error. I'm not sure how (or if) this can be solved.", "created_at": "2020-06-18T11:48:46Z" }, { "body": "> Hmm this is a tricky one. Apparently the SQL generated to create the table doesn't immediately adds the primary key and thus indeed causes this error. I'm not sure how (or if) this can be solved.\r\n\r\nThanks for taking a look!\r\n\r\nI know it doesn't help in finding a resolution, but it appears that this also affects Passport install. See here: https://github.com/laravel/passport/blob/9.x/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php\r\n\r\n`$table->id();` appears to function without any issues, I think because of [this logic](https://github.com/laravel/framework/blob/be09eac00a2f750dc2d2209078cf61ae2eee85a1/src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php#L974).", "created_at": "2020-06-18T12:09:01Z" }, { "body": "In my case I use Digital Ocean as well, but this problem happened for pivot tables only and I had to edit the migrations by adding `$table->id();` and `$table->unique(['table1_id', table2_id']);`.", "created_at": "2020-06-18T13:27:44Z" }, { "body": "@erwinweber96 the problem is that that won't work for string based primary identifiers. Thinking password resets table, database notifications, passport, etc.", "created_at": "2020-06-18T13:30:21Z" }, { "body": "I agree that this needs to be solved, however I added that comment in case someone stumbles upon the issue (like I did) regarding sql_require_primary_key and laravel. There's very few info online on this matter atm.", "created_at": "2020-06-18T13:34:16Z" }, { "body": "I'm experiencing the same issue. Unsure if it was a recent change to DigitalOcean's config but Laravel applications utilising Passport are effectively incompatible with DigitalOcean Managed Databases at the moment.", "created_at": "2020-06-20T11:26:25Z" }, { "body": "**update** below solution won't work if you run tests in sqlite for example. See https://github.com/laravel/framework/issues/33238#issuecomment-648071415 for a simpler workaround. \r\n\r\nSame issue here, it affects the `sessions`, `password_resets` and the two Telescope tables `telescope_entries_tags` and `telescope_monitoring` as far as I know at this point.\r\n\r\nFor anyone that needs a fix, this is my workaround for now: \r\n- Run the default Laravel migrations (add a primary key where necessary) on a machine where the flag is turned off (Homestead for example)\r\n- Open your SQL editor and copy the `CREATE TABLE ... ` statement. (TablePlus: open table, at the bottom: [Structure] and then the button [Info] on the right). \r\n- Open your migration file, comment your original Laravel Schema (keep it as a reference). \r\n- Run the `CREATE TABLE ...` statement with: `\\DB::statement($query);`\r\n\r\n**sessions**\r\n```mysql\r\n\\Illuminate\\Support\\Facades\\DB::statement('CREATE TABLE `sessions` (\r\n `id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\r\n `user_id` bigint(20) unsigned DEFAULT NULL,\r\n `ip_address` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\r\n `user_agent` text COLLATE utf8mb4_unicode_ci,\r\n `payload` text COLLATE utf8mb4_unicode_ci NOT NULL,\r\n `last_activity` int(11) NOT NULL,\r\n PRIMARY KEY (`id`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;');\r\n```\r\n**password_resets**\r\nYou could probably also choose `email` as a primary key but in my case I have some extra (tenant related) columns in this table.\r\n```mysql\r\n\\Illuminate\\Support\\Facades\\DB::statement('CREATE TABLE `password_resets` (\r\n `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\r\n `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\r\n `created_at` timestamp NULL DEFAULT NULL,\r\n PRIMARY KEY (`token`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;')\r\n```\r\n\r\n## Laravel Telescope\r\nSee https://laravel.com/docs/7.x/telescope#migration-customization on how to use your own migrations instead of the default ones \r\n\r\n**telescope_entries_tags**\r\n```mysql\r\n\\Illuminate\\Support\\Facades\\DB::statement('CREATE TABLE `telescope_entries_tags` (\r\n `entry_uuid` char(36) COLLATE utf8mb4_unicode_ci NOT NULL,\r\n `tag` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\r\n PRIMARY KEY (`entry_uuid`,`tag`),\r\n KEY `telescope_entries_tags_tag_index` (`tag`),\r\n CONSTRAINT `telescope_entries_tags_entry_uuid_foreign` FOREIGN KEY (`entry_uuid`) REFERENCES `telescope_entries` (`uuid`) ON DELETE CASCADE\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;');\r\n```\r\n\r\n**telescope_monitoring**\r\n```mysql\r\nDB::statement('CREATE TABLE `telescope_monitoring` (\r\n `tag` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\r\n PRIMARY KEY (`tag`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;');\r\n```\r\n", "created_at": "2020-06-21T20:47:57Z" }, { "body": "Current workaround is setting \r\n`SET sql_require_primary_key=0`, and I set the sql variable.\r\n\r\nAnd I change to \r\n```\r\nalter table `TABLE_NAME` add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;\r\n```", "created_at": "2020-06-22T11:36:35Z" }, { "body": "> Current workaround is setting\r\n> `SET sql_require_primary_key=0`, and I set the sql variable.\r\n> \r\n> And I change to\r\n> \r\n> ```\r\n> alter table `TABLE_NAME` add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;\r\n> ```\r\n\r\nUnable to do this on managed database instances (DigitalOcean) as far as I'm aware?", "created_at": "2020-06-22T11:43:52Z" }, { "body": "Yep, this is following a recent [change to their config](https://www.digitalocean.com/docs/databases/#5-june-2020)\r\nIf it wasn't for DO mandating it, I'd have disabled the setting and moved on. Because they are mandating it, I thought our team wouldn't be the only ones having issues.\r\n\r\nFrom the tagging of this issue (by Dries as a bug and help wanted), I think there is an acceptance that this needs to be resolved in the framework in some way. Although I acknowledge that is is a fairly sizeable job to sort!", "created_at": "2020-06-22T13:24:59Z" }, { "body": "If someone wants to submit a PR to somehow make this one query behind the scenes be our guest 😄 \r\n\r\nCurrently, this is not a \"bug\" in Laravel. It is a bug in DigitalOcean's configuration they are forcing upon you.", "created_at": "2020-06-22T13:40:00Z" }, { "body": "I've had the following response from DigitalOcean regarding this issue:\r\n\r\n\r\n>I understand you are getting error when trying to migrate database schemas. You can temporarily override the setting using SET SESSION sql_require_primary_key = 1;\r\n>\r\n> However, You will need to add a primary key after you import or you will receive notifications at a point that adding primary key is required. \r\n>\r\n>This setting is only for the current session though, it's not a permanent override.\r\n\r\nTherefore I managed to get this to work by calling `\\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0');` above my `Schema::create` command in the migrations causing issues.", "created_at": "2020-06-23T10:59:30Z" }, { "body": "> Therefore I managed to get this to work by calling `\\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0');` above my `Schema::create` command in the migrations causing issues.\r\n\r\nCan confirm this works for me as well. Thanks Alex!", "created_at": "2020-06-29T20:55:48Z" }, { "body": "Any latest update or any other solution as of now? The major tables that are affected are the pivot tables only.", "created_at": "2020-08-17T18:01:06Z" }, { "body": "> I've had the following response from DigitalOcean regarding this issue:\r\n> \r\n> > I understand you are getting error when trying to migrate database schemas. You can temporarily override the setting using SET SESSION sql_require_primary_key = 1;\r\n> > However, You will need to add a primary key after you import or you will receive notifications at a point that adding primary key is required.\r\n> > This setting is only for the current session though, it's not a permanent override.\r\n> \r\n> Therefore I managed to get this to work by calling `\\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0');` above my `Schema::create` command in the migrations causing issues.\r\n\r\nThank you works for me as well. You can add this into\r\n\r\n> src/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php\r\n\r\nso it works every time you use the migrate command.", "created_at": "2020-08-22T17:09:02Z" }, { "body": "> I've had the following response from DigitalOcean regarding this issue:\r\n> \r\n> > I understand you are getting error when trying to migrate database schemas. You can temporarily override the setting using SET SESSION sql_require_primary_key = 1;\r\n> > However, You will need to add a primary key after you import or you will receive notifications at a point that adding primary key is required.\r\n> > This setting is only for the current session though, it's not a permanent override.\r\n> \r\n> Therefore I managed to get this to work by calling `\\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0');` above my `Schema::create` command in the migrations causing issues.\r\n\r\nlove you so much", "created_at": "2020-09-09T14:46:01Z" }, { "body": "> I've had the following response from DigitalOcean regarding this issue:\r\n> \r\n> > I understand you are getting error when trying to migrate database schemas. You can temporarily override the setting using SET SESSION sql_require_primary_key = 1;\r\n> > However, You will need to add a primary key after you import or you will receive notifications at a point that adding primary key is required.\r\n> > This setting is only for the current session though, it's not a permanent override.\r\n> \r\n> Therefore I managed to get this to work by calling `\\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0');` above my `Schema::create` command in the migrations causing issues.\r\n\r\nI'm trying to import an existing Laravel database (MySQL 5.x) into DigitalOcean Managed Database (MySQL 8) and I'm getting that error. How would I set that variable? At the top of the dump file? Thank you!", "created_at": "2020-09-25T23:26:07Z" }, { "body": "> I'm trying to import an existing Laravel database (MySQL 5.x) into DigitalOcean Managed Database (MySQL 8) and I'm getting that error. How would I set that variable? At the top of the dump file? Thank you!\n\nAre you using a Tool like TablePlus? Then you can login to the database, execute `SET SESSION sql_require_primary_key=0` manually and import your dump. This works because it's the same session :-)", "created_at": "2020-09-26T06:35:18Z" }, { "body": "It works, thanks!\n\nAnd for some Laravel tables like password_resets? Should we add a primary key to a column of choice?\n\n> On 26 Sep 2020, at 08:35, Simon Hansen <notifications@github.com> wrote:\n> \n> \n> I've had the following response from DigitalOcean regarding this issue:\n> \n> I understand you are getting error when trying to migrate database schemas. You can temporarily override the setting using SET SESSION sql_require_primary_key = 1;\n> \n> However, You will need to add a primary key after you import or you will receive notifications at a point that adding primary key is required.\n> \n> This setting is only for the current session though, it's not a permanent override.\n> \n> Therefore I managed to get this to work by calling \\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0'); above my Schema::create command in the migrations causing issues.\n> \n> I'm trying to import an existing Laravel database (MySQL 5.x) into DigitalOcean Managed Database (MySQL 8) and I'm getting that error. How would I set that variable? At the top of the dump file? Thank you!\n> \n> Are you using a Tool like TablePlus? Then you can login to the database, execute SET SESSION sql_require_primary_key=0 manually and import your dump. This works because it's the same session :-)\n> \n> —\n> You are receiving this because you commented.\n> Reply to this email directly, view it on GitHub, or unsubscribe.\n", "created_at": "2020-09-26T06:49:32Z" }, { "body": "> It works, thanks!\n> \n> And for some Laravel tables like password_resets? Should we add a primary key to a column of choice?\n\n\nWe didn't make other changes because the error only occurs while creating the table.. after that everything should work as expected. But keep in mind that you cannot create more tables without a primary key (or you have to apply the workaround again).", "created_at": "2020-09-26T07:08:06Z" }, { "body": "> I've had the following response from DigitalOcean regarding this issue:\r\n> \r\n> > I understand you are getting error when trying to migrate database schemas. You can temporarily override the setting using SET SESSION sql_require_primary_key = 1;\r\n> > However, You will need to add a primary key after you import or you will receive notifications at a point that adding primary key is required.\r\n> > This setting is only for the current session though, it's not a permanent override.\r\n> \r\n> Therefore I managed to get this to work by calling `\\Illuminate\\Support\\Facades\\DB::statement('SET SESSION sql_require_primary_key=0');` above my `Schema::create` command in the migrations causing issues.\r\n\r\nTnx alot!!", "created_at": "2020-10-21T13:29:37Z" }, { "body": "> Thank you works for me as well. You can add this into\r\n> \r\n> > src/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php\r\n> \r\n> so it works every time you use the migrate command.\r\n\r\n\r\nWhere in that file should i use it ?\r\n", "created_at": "2020-11-19T11:52:51Z" }, { "body": "> > Thank you works for me as well. You can add this into\r\n> > > src/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php\r\n> > \r\n> > \r\n> > so it works every time you use the migrate command.\r\n> \r\n> Where in that file should i use it ?\r\n\r\nYeah where should we add in that file?\r\n", "created_at": "2020-11-24T08:57:35Z" }, { "body": "> > > Thank you works for me as well. You can add this into\r\n> > > > src/vendor/laravel/framework/src/Illuminate/Database/MigrationServiceProvider.php\r\n> > > \r\n> > > \r\n> > > so it works every time you use the migrate command.\r\n> > \r\n> > \r\n> > Where in that file should i use it ?\r\n> \r\n> Yeah where should we add in that file?\r\n\r\nPut at the migration file where didn't have primary key id, for example, 2014_10_12_100000_create_password_resets_table.php", "created_at": "2020-12-14T13:30:45Z" }, { "body": "I just want to add, if you use PostgreSQL, everything is working fine. Just for the people who doesn't know 😃", "created_at": "2020-12-16T18:02:55Z" }, { "body": "Hello, developers!\r\n\r\nI just faced the exact same issue.\r\n\r\nIf you are running migrations in the server, there is an even better wat, using tinker:\r\n\r\nAfter configuring the connection to the remote database, go to the console in your server and use `php artisan tinker`.\r\n\r\nOnce there, execute `DB::statement('SET SESSION sql_require_primary_key=0');` to disable the check and then execute `Artisan::call('migrate --force'); `to run all your migrations.\r\n\r\nOf course, if you are using an SQL file, so put `SET SESSION sql_require_primary_key=0;` in the top of that file and use it.\r\n", "created_at": "2020-12-29T07:23:46Z" }, { "body": "@adddz in order to make it compatible with both locally on MySQL 5.7 and on DigitalOcean MySQL 8 I had to add the following to the `CreateSessionsTable`:\r\n```php\r\nuse Illuminate\\Support\\Facades\\DB;\r\n\r\n$requirePrimaryKey = DB::selectOne('SHOW SESSION VARIABLES LIKE \"sql_require_primary_key\";')->Value ?? 'OFF';\r\nif ($requirePrimaryKey === 'ON') {\r\n DB::statement('SET SESSION sql_require_primary_key=0');\r\n}\r\n```\r\n\r\nThis would first check if if the sql_require_primary_key exists and is enabled before trying to temporarily disable it.", "created_at": "2021-01-12T10:12:24Z" }, { "body": "I dont understand why this is closed Surely the bug still stands? you need to a a ton of workarounds to get this working mostly to do with the wrong way the SQL statement is created. Surely the fix will be to fix the way its built?\r\n\r\nIts also worth noting the workarounds above are not always reliable. I'm getting inconsistent results.", "created_at": "2021-02-01T16:59:51Z" }, { "body": "In researching this issue, I came across this response from DO\r\n\r\n> I understand that you want to know if it is possible to turn off \"sql_require_primary_key.\" Unfortunately we cannot turn off primary key for our managed database. The lack of primary keys will leads to replication problems, and replication cannot be disabled as backups are done using that. As a managed database, we guarantee backups in case of failure or data loss, and you need to restore.\r\n\r\nSo, temporarily overwriting the flag is ok, but you need to still ensure you end up with a primary key on every table ... the inference being that DO will not be responsible if you cannot recover from a server issue.", "created_at": "2021-02-05T16:38:06Z" }, { "body": "> In researching this issue, I came across this response from DO\r\n> \r\n> > I understand that you want to know if it is possible to turn off \"sql_require_primary_key.\" Unfortunately we cannot turn off primary key for our managed database. The lack of primary keys will leads to replication problems, and replication cannot be disabled as backups are done using that. As a managed database, we guarantee backups in case of failure or data loss, and you need to restore.\r\n> \r\n> So, temporarily overwriting the flag is ok, but you need to still ensure you end up with a primary key on every table ... the inference being that DO will not be responsible if you cannot recover from a server issue.\r\n\r\nThat's is fine. That is how its meant to work.\r\nThe problem is the way Laravel constructs the SQL query by creating the table and then adding keys after. The workaround is just that and annoyingly clearly wont be fixed on Laravel's side likely because of this edge use case.", "created_at": "2021-02-05T16:40:33Z" } ], "number": 33238, "title": "sql_require_primary_key Causes Tables With String Primary Key To Fail" }
{ "body": "This PR created in the following of this issue #33238 & [here](https://github.com/BookStackApp/BookStack/issues/2612) to solve the migration problem for databases with `sql_require_primary_key` enabled, (e.g. DigitalOcean machines).\r\n\r\nIt was OK for the `auto-increment` fields, but it was not working for other fields which need to be `primary`, e.g. the `Passport Migration`:\r\n\r\n```php\r\n $this->schema->create('oauth_auth_codes', function (Blueprint $table) {\r\n $table->string('id', 100)->primary();\r\n //Other fields\r\n });\r\n``` \r\nIn this situation, at first, the table was created and then altered to have a `primary key` on `id`.\r\nSo there were two queries executed to create the above table.\r\n```sql\r\n#The first one:\r\ncreate table `oauth_auth_codes` (`id` varchar(100) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci';\r\n\r\n#The second one:\r\nalter table `oauth_auth_codes` add primary key `users_id_primary`(`id`);\r\n```\r\nThis PR modifies the grammar to produce **ONLY SINGLE QUERY** like this:\r\n```sql\r\ncreate table `users` (`id` varchar(100) primary key not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci'\r\n```\r\nThis causes a tiny improvement during migrations especially for tests using `RefreshDatabase` middleware.\r\nAlso, the changes include `MySQL`, `Postgres`, `SQL Server` and `SQLite` with the required **TESTS** for all grammars.\r\n\r\n\r\n\r\n", "number": 37715, "review_comments": [], "title": "[8.x] Solve the Primary Key issue in databases with sql_require_primary_key enabled" }
{ "commits": [ { "message": "Execute creating the Primary Key in single Query\nRemove the primary item from the fluent indexes and add it to the modifiers" }, { "message": "Create Tests for MySql, Postgres, SqlServer & SQLite to assert the creating primary key in single query without altering table" }, { "message": "formatting" } ], "files": [ { "diff": "@@ -208,7 +208,7 @@ protected function addImpliedCommands(Grammar $grammar)\n protected function addFluentIndexes()\n {\n foreach ($this->columns as $column) {\n- foreach (['primary', 'unique', 'index', 'spatialIndex'] as $index) {\n+ foreach (['unique', 'index', 'spatialIndex'] as $index) {\n // If the index has been specified on the given column, but is simply equal\n // to \"true\" (boolean), no name has been specified for this index so the\n // index method can be called without a name and it will generate one.", "filename": "src/Illuminate/Database/Schema/Blueprint.php", "status": "modified" }, { "diff": "@@ -15,7 +15,7 @@ class MySqlGrammar extends Grammar\n * @var string[]\n */\n protected $modifiers = [\n- 'Unsigned', 'Charset', 'Collate', 'VirtualAs', 'StoredAs', 'Nullable',\n+ 'Primary', 'Unsigned', 'Charset', 'Collate', 'VirtualAs', 'StoredAs', 'Nullable',\n 'Srid', 'Default', 'Increment', 'Comment', 'After', 'First',\n ];\n \n@@ -927,30 +927,30 @@ protected function typeComputed(Fluent $column)\n }\n \n /**\n- * Get the SQL for a generated virtual column modifier.\n+ * Get the SQL for a primary column modifier.\n *\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n * @param \\Illuminate\\Support\\Fluent $column\n * @return string|null\n */\n- protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column)\n+ public function modifyPrimary(Blueprint $blueprint, Fluent $column)\n {\n- if (! is_null($column->virtualAs)) {\n- return \" as ({$column->virtualAs})\";\n+ if (! $column->autoIncrement && ! is_null($column->primary)) {\n+ return ' primary key';\n }\n }\n \n /**\n- * Get the SQL for a generated stored column modifier.\n+ * Get the SQL for an auto-increment column modifier.\n *\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n * @param \\Illuminate\\Support\\Fluent $column\n * @return string|null\n */\n- protected function modifyStoredAs(Blueprint $blueprint, Fluent $column)\n+ protected function modifyIncrement(Blueprint $blueprint, Fluent $column)\n {\n- if (! is_null($column->storedAs)) {\n- return \" as ({$column->storedAs}) stored\";\n+ if (in_array($column->type, $this->serials) && $column->autoIncrement) {\n+ return ' auto_increment primary key';\n }\n }\n \n@@ -1029,16 +1029,30 @@ protected function modifyDefault(Blueprint $blueprint, Fluent $column)\n }\n \n /**\n- * Get the SQL for an auto-increment column modifier.\n+ * Get the SQL for a generated virtual column modifier.\n *\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n * @param \\Illuminate\\Support\\Fluent $column\n * @return string|null\n */\n- protected function modifyIncrement(Blueprint $blueprint, Fluent $column)\n+ protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column)\n {\n- if (in_array($column->type, $this->serials) && $column->autoIncrement) {\n- return ' auto_increment primary key';\n+ if (! is_null($column->virtualAs)) {\n+ return \" as ({$column->virtualAs})\";\n+ }\n+ }\n+\n+ /**\n+ * Get the SQL for a generated stored column modifier.\n+ *\n+ * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n+ * @param \\Illuminate\\Support\\Fluent $column\n+ * @return string|null\n+ */\n+ protected function modifyStoredAs(Blueprint $blueprint, Fluent $column)\n+ {\n+ if (! is_null($column->storedAs)) {\n+ return \" as ({$column->storedAs}) stored\";\n }\n }\n ", "filename": "src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php", "status": "modified" }, { "diff": "@@ -19,7 +19,7 @@ class PostgresGrammar extends Grammar\n *\n * @var string[]\n */\n- protected $modifiers = ['Collate', 'Increment', 'Nullable', 'Default', 'VirtualAs', 'StoredAs'];\n+ protected $modifiers = ['Primary', 'Collate', 'Increment', 'Nullable', 'Default', 'VirtualAs', 'StoredAs'];\n \n /**\n * The columns available as serials.\n@@ -979,6 +979,20 @@ protected function modifyNullable(Blueprint $blueprint, Fluent $column)\n return $column->nullable ? ' null' : ' not null';\n }\n \n+ /**\n+ * Get the SQL for a primary column modifier.\n+ *\n+ * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n+ * @param \\Illuminate\\Support\\Fluent $column\n+ * @return string|null\n+ */\n+ public function modifyPrimary(Blueprint $blueprint, Fluent $column)\n+ {\n+ if (! $column->autoIncrement && ! is_null($column->primary)) {\n+ return ' primary key';\n+ }\n+ }\n+\n /**\n * Get the SQL for a default column modifier.\n *", "filename": "src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php", "status": "modified" }, { "diff": "@@ -16,7 +16,7 @@ class SQLiteGrammar extends Grammar\n *\n * @var string[]\n */\n- protected $modifiers = ['VirtualAs', 'StoredAs', 'Nullable', 'Default', 'Increment'];\n+ protected $modifiers = ['Primary', 'VirtualAs', 'StoredAs', 'Nullable', 'Default', 'Increment'];\n \n /**\n * The columns available as serials.\n@@ -55,12 +55,11 @@ public function compileColumnListing($table)\n */\n public function compileCreate(Blueprint $blueprint, Fluent $command)\n {\n- return sprintf('%s table %s (%s%s%s)',\n+ return sprintf('%s table %s (%s%s)',\n $blueprint->temporary ? 'create temporary' : 'create',\n $this->wrapTable($blueprint),\n implode(', ', $this->getColumns($blueprint)),\n- (string) $this->addForeignKeys($blueprint),\n- (string) $this->addPrimaryKeys($blueprint)\n+ (string) $this->addForeignKeys($blueprint)\n );\n }\n \n@@ -849,30 +848,30 @@ protected function typeComputed(Fluent $column)\n }\n \n /**\n- * Get the SQL for a generated virtual column modifier.\n+ * Get the SQL for a primary column modifier.\n *\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n * @param \\Illuminate\\Support\\Fluent $column\n * @return string|null\n */\n- protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column)\n+ public function modifyPrimary(Blueprint $blueprint, Fluent $column)\n {\n- if (! is_null($column->virtualAs)) {\n- return \" as ({$column->virtualAs})\";\n+ if (! $column->autoIncrement && ! is_null($column->primary)) {\n+ return ' primary key';\n }\n }\n \n /**\n- * Get the SQL for a generated stored column modifier.\n+ * Get the SQL for an auto-increment column modifier.\n *\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n * @param \\Illuminate\\Support\\Fluent $column\n * @return string|null\n */\n- protected function modifyStoredAs(Blueprint $blueprint, Fluent $column)\n+ protected function modifyIncrement(Blueprint $blueprint, Fluent $column)\n {\n- if (! is_null($column->storedAs)) {\n- return \" as ({$column->storedAs}) stored\";\n+ if (in_array($column->type, $this->serials) && $column->autoIncrement) {\n+ return ' primary key autoincrement';\n }\n }\n \n@@ -909,16 +908,30 @@ protected function modifyDefault(Blueprint $blueprint, Fluent $column)\n }\n \n /**\n- * Get the SQL for an auto-increment column modifier.\n+ * Get the SQL for a generated virtual column modifier.\n *\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n * @param \\Illuminate\\Support\\Fluent $column\n * @return string|null\n */\n- protected function modifyIncrement(Blueprint $blueprint, Fluent $column)\n+ protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column)\n {\n- if (in_array($column->type, $this->serials) && $column->autoIncrement) {\n- return ' primary key autoincrement';\n+ if (! is_null($column->virtualAs)) {\n+ return \" as ({$column->virtualAs})\";\n+ }\n+ }\n+\n+ /**\n+ * Get the SQL for a generated stored column modifier.\n+ *\n+ * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n+ * @param \\Illuminate\\Support\\Fluent $column\n+ * @return string|null\n+ */\n+ protected function modifyStoredAs(Blueprint $blueprint, Fluent $column)\n+ {\n+ if (! is_null($column->storedAs)) {\n+ return \" as ({$column->storedAs}) stored\";\n }\n }\n }", "filename": "src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php", "status": "modified" }, { "diff": "@@ -19,7 +19,7 @@ class SqlServerGrammar extends Grammar\n *\n * @var string[]\n */\n- protected $modifiers = ['Increment', 'Collate', 'Nullable', 'Default', 'Persisted'];\n+ protected $modifiers = ['Primary', 'Increment', 'Collate', 'Nullable', 'Default', 'Persisted'];\n \n /**\n * The columns available as serials.\n@@ -832,6 +832,20 @@ protected function typeComputed(Fluent $column)\n return \"as ({$column->expression})\";\n }\n \n+ /**\n+ * Get the SQL for a primary column modifier.\n+ *\n+ * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n+ * @param \\Illuminate\\Support\\Fluent $column\n+ * @return string|null\n+ */\n+ public function modifyPrimary(Blueprint $blueprint, Fluent $column)\n+ {\n+ if (! $column->autoIncrement && ! is_null($column->primary)) {\n+ return ' primary key';\n+ }\n+ }\n+\n /**\n * Get the SQL for a collation column modifier.\n *", "filename": "src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -47,6 +47,23 @@ public function testBasicCreateTable()\n $this->assertSame('alter table `users` add `id` int unsigned not null auto_increment primary key, add `email` varchar(255) not null', $statements[0]);\n }\n \n+ public function testBasicCreateWithPrimaryKey()\n+ {\n+ $blueprint = new Blueprint('users');\n+ $blueprint->create();\n+ $blueprint->string('foo')->primary();\n+\n+ $conn = $this->getConnection();\n+ $conn->shouldReceive('getConfig')->once()->with('charset')->andReturn('utf8');\n+ $conn->shouldReceive('getConfig')->once()->with('collation')->andReturn('utf8_unicode_ci');\n+ $conn->shouldReceive('getConfig')->once()->with('engine')->andReturn(null);\n+\n+ $statements = $blueprint->toSql($conn, $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame(\"create table `users` (`foo` varchar(255) primary key not null) default character set utf8 collate 'utf8_unicode_ci'\", $statements[0]);\n+ }\n+\n public function testAutoIncrementStartingValue()\n {\n $blueprint = new Blueprint('users');", "filename": "tests/Database/DatabaseMySqlSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -37,6 +37,17 @@ public function testBasicCreateTable()\n $this->assertSame('alter table \"users\" add column \"id\" serial primary key not null, add column \"email\" varchar(255) not null', $statements[0]);\n }\n \n+ public function testBasicCreateWithPrimaryKey()\n+ {\n+ $blueprint = new Blueprint('users');\n+ $blueprint->create();\n+ $blueprint->string('foo')->primary();\n+ $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame('create table \"users\" (\"foo\" varchar(255) primary key not null)', $statements[0]);\n+ }\n+\n public function testCreateTableWithAutoIncrementStartingValue()\n {\n $blueprint = new Blueprint('users');", "filename": "tests/Database/DatabasePostgresSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -196,7 +196,7 @@ public function testAddingPrimaryKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertCount(1, $statements);\n- $this->assertSame('create table \"users\" (\"foo\" varchar not null, primary key (\"foo\"))', $statements[0]);\n+ $this->assertSame('create table \"users\" (\"foo\" varchar primary key not null)', $statements[0]);\n }\n \n public function testAddingForeignKey()\n@@ -209,7 +209,7 @@ public function testAddingForeignKey()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertCount(1, $statements);\n- $this->assertSame('create table \"users\" (\"foo\" varchar not null, \"order_id\" varchar not null, foreign key(\"order_id\") references \"orders\"(\"id\"), primary key (\"foo\"))', $statements[0]);\n+ $this->assertSame('create table \"users\" (\"foo\" varchar primary key not null, \"order_id\" varchar not null, foreign key(\"order_id\") references \"orders\"(\"id\"))', $statements[0]);\n }\n \n public function testAddingUniqueKey()", "filename": "tests/Database/DatabaseSQLiteSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -45,6 +45,17 @@ public function testBasicCreateTable()\n $this->assertSame('create table \"prefix_users\" (\"id\" int identity primary key not null, \"email\" nvarchar(255) not null)', $statements[0]);\n }\n \n+ public function testBasicCreateWithPrimaryKey()\n+ {\n+ $blueprint = new Blueprint('users');\n+ $blueprint->create();\n+ $blueprint->string('foo')->primary();\n+ $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame('create table \"users\" (\"foo\" nvarchar(255) primary key not null)', $statements[0]);\n+ }\n+\n public function testCreateTemporaryTable()\n {\n $blueprint = new Blueprint('users');", "filename": "tests/Database/DatabaseSqlServerSchemaGrammarTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 8.12\r\n- PHP Version: 7.4\r\n- Database Driver & Version: MYSQL\r\n\r\n### Description:\r\n\r\n`Route::redirect` has a different priority after running `artisan route:cache`.\r\n\r\n### Steps To Reproduce:\r\n\r\nIn `web.php` I had routes set like this:\r\n```\r\nRoute::redirect('/organizations/{organization}', '/organizations/{organizations}/overview');\r\nRoute::patch('/organizations/{organization}', ...); \r\n```\r\n`get` and `patch` requests to these routes were working normally until I ran `artisan route:cache`. After the cache command all `patch` requests were intercepted by the redirect route.\r\n\r\nThe fix for me was to swap the ordering of these two routes, but I wonder, is there a code change that could be made to make this behavior more consistent? If not, maybe there can be more guidance around route order/priority in the documentation?\r\n", "comments": [ { "body": "Heya, thanks for reporting.\r\n\r\nI'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue and share the repository here? Please make sure that you have the [latest version of the Laravel installer](https://github.com/laravel/installer) in order to run this command. Please also make sure you have both Git & [the GitHub CLI tool](https://cli.github.com) properly set up.\r\n\r\n```bash\r\nlaravel new framework-issue-37639 --github=\"--public\"\r\n```\r\n\r\nAfter you've posted the repository, I'll try to reproduce the issue.\r\n\r\nThanks!", "created_at": "2021-06-10T16:06:43Z" }, { "body": "@driesvints here you go: https://github.com/imacrayon/framework-issue-37639\r\n\r\nClicking the submit button on the homepage will display \"Success\". But you get a different page on submit after running `artisan route:cache`.", "created_at": "2021-06-10T19:25:59Z" }, { "body": "Thanks, that was very helpful. I see the same thing happening. I'm trying to recollect what the expected behavior is here as I remember we've been looking into something similar when we introduced the new Symfony compiled routes feature. I'll take a look at this when I find some time. Otherwise we're also welcoming PR's.", "created_at": "2021-06-11T09:39:32Z" }, { "body": "Seems like this behavior has existed ever since we introduced route caching. I'm not sure on an easy way to solve this. Maybe we can re-order redirect routes.", "created_at": "2021-06-15T13:58:41Z" }, { "body": "I can't find a decent solution for this. I've tried to rewrite the `toSymfonyRouteCollection` method to the following:\r\n\r\n```\r\n public function toSymfonyRouteCollection()\r\n {\r\n $symfonyRoutes = new SymfonyRouteCollection;\r\n\r\n $routes = $this->getRoutes();\r\n $controller = $route->action['controller'] ?? '';\r\n\r\n // Add redirect routes...\r\n foreach ($routes as $route) {\r\n if (! $route->isFallback && is_a($controller, RedirectController::class, true)) {\r\n $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);\r\n }\r\n }\r\n\r\n // Add regular routes...\r\n foreach ($routes as $route) {\r\n if (! $route->isFallback && ! is_a($controller, RedirectController::class, true)) {\r\n $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);\r\n }\r\n }\r\n\r\n // Add fallback routes...\r\n foreach ($routes as $route) {\r\n if ($route->isFallback && ! is_a($controller, RedirectController::class, true)) {\r\n $symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);\r\n }\r\n }\r\n\r\n return $symfonyRoutes;\r\n }\r\n```\r\n\r\nBut that won't work because the conflicting route can also be above the redirect route. We can't just move all redirect routes to the bottom.", "created_at": "2021-06-15T15:11:01Z" }, { "body": "It's not really redirect only problem, it's a problem in general:\r\n\r\n```php\r\nRoute::any('/test', function () {\r\n return '1';\r\n});\r\n\r\nRoute::get('/test', function () {\r\n return '2';\r\n});\r\n```\r\n\r\nOutputs the same problem - `2` is displayed without cache and `1` is displayed with cache.", "created_at": "2021-06-15T17:27:01Z" }, { "body": "Why not cache the laravel route, but convert it into a symfony route for caching? @driesvints ", "created_at": "2021-06-16T10:24:27Z" }, { "body": "> * Laravel Version: 8.12\r\n> * PHP Version: 7.4\r\n> * Database Driver & Version: MYSQL\r\n> \r\n> ### Description:\r\n> `Route::redirect` has a different priority after running `artisan route:cache`.\r\n> \r\n> ### Steps To Reproduce:\r\n> In `web.php` I had routes set like this:\r\n> \r\n> ```\r\n> Route::redirect('/organizations/{organization}', '/organizations/{organizations}/overview');\r\n> Route::patch('/organizations/{organization}', ...); \r\n> ```\r\n> \r\n> `get` and `patch` requests to these routes were working normally until I ran `artisan route:cache`. After the cache command all `patch` requests were intercepted by the redirect route.\r\n> \r\n> The fix for me was to swap the ordering of these two routes, but I wonder, is there a code change that could be made to make this behavior more consistent? If not, maybe there can be more guidance around route order/priority in the documentation?\r\n\r\nYes this is true. Because cached routes of method `Route::redirect` and `Route::patch` with same path `'/somepath'` has the same method `PATCH` so the first written route will be the one being called which is `Route::redirect`. \r\n\r\nIf you investigate the cached route file and in array of `'/somepath'` it will has array of methods like this:\r\n```php\r\n// redirect \r\narray (\r\n 'GET' => 0,\r\n 'HEAD' => 1,\r\n 'POST' => 2,\r\n 'PUT' => 3,\r\n 'PATCH' => 4, // this will match the method of request\r\n 'DELETE' => 5,\r\n 'OPTIONS' => 6,\r\n ),\r\n\r\n// patch\r\narray (\r\n 'PATCH' => 0,\r\n),\r\n```\r\nIf you remove or commented out the `'PATCH' => 4`, value then it's gonna work like you expected. So I was wondering why the `Route::redirect` method generate all the http methods instead of only `GET`? @driesvints ", "created_at": "2021-06-22T08:40:10Z" }, { "body": "@aanfarhan this issue isn't specifically to PATCH. It's for all HTTP methods.", "created_at": "2021-06-22T08:46:25Z" }, { "body": "well, if you do a redirect, it's for every method, not only get requests.", "created_at": "2021-06-22T08:47:11Z" }, { "body": "What I'm trying to say is maybe it would be better if you can configure redirect route to work only on certain HTTP methods. Because logically if you call to the same endpoint with the same HTTP method it will only generate one result right? ", "created_at": "2021-06-22T09:06:37Z" }, { "body": "@aanfarhan that's not really in the scope of this issue. Let's keep this issue focused on the issue at hand.", "created_at": "2021-06-22T09:10:11Z" }, { "body": "@driesvints maybe just invert order in routes' list for cache file, like this:\r\n```\r\n protected function getFreshApplicationRoutes()\r\n {\r\n $collection = new Collection();\r\n $routes = new RouteCollection();\r\n foreach ($this->getFreshApplication()['router']->getRoutes() as $route) {\r\n $collection->prepend($route);\r\n }\r\n foreach ($collection as $route) {\r\n $routes->add($route);\r\n }\r\n return tap($routes, function ($routes) {\r\n $routes->refreshNameLookups();\r\n $routes->refreshActionLookups();\r\n });\r\n }\r\n```\r\n\r\nIn this case last routes override previous ones, but I don't know how to write it more beauty", "created_at": "2021-07-02T21:57:50Z" }, { "body": "The root cause of this problem is that when the routes are cached we use \"symfony matcher\" to match a route based on request data and when the routes are not cached we use \"Laravel matcher\". So the implementations of the `->match(` method are very different and they behave differently when there are two candidate routes to choose from.\r\n1- `Illuminate\\Routing\\CompiledRouteCollection@match`\r\n2- `Illuminate\\Routing\\RouteCollection@match`\r\n\r\nYou can run this in case of cache being present and being deleted to see the output of dd.\r\n![image](https://user-images.githubusercontent.com/6961695/126501322-db4302a8-9708-42e1-9f7d-a920ea5ed273.png)\r\n", "created_at": "2021-07-21T14:06:41Z" }, { "body": "https://laravel.com/docs/8.x/routing The docs now have callout about ordering route definitions unambiguously. So if a non-breaking code change can't be agreed upon, this issue can be closed.\r\n\r\n![route-me](https://user-images.githubusercontent.com/823566/135912772-65efc3e2-357d-4d8f-9149-2bc4b2ebf4cc.png)\r\n", "created_at": "2021-10-04T19:34:34Z" }, { "body": "@derekmd I agree that's the best solution to this really. It's a hard problem to solve otherwise.", "created_at": "2021-10-04T19:43:13Z" }, { "body": "@driesvints @taylorotwell Laravel can provide an artisan command so that the users can scan their routes to see if there is any overriding is going on and resolve the situation for themselves.\r\nI have already implemented such a thing almost year ago on laravel-microscope for inspection purposes.\r\n`php artisan check:routes` will do the job and informs if routes are conflicting.\r\n\r\nI think if laravel give the users a free tool to avoid the breaking fix, it can give laravel a good excuse to fix it after a while.", "created_at": "2021-10-04T21:26:48Z" } ], "number": 37639, "title": "Route::redirect changes priority after running route:cache" }
{ "body": "Fix #37639 \r\nWhen there are multiple URL matches, symfony will return the first match, but in laravel, it should return the last matching route.", "number": 37693, "review_comments": [], "title": "[8.x] Reverse routes in cache" }
{ "commits": [ { "message": "reverse routes" } ], "files": [ { "diff": "@@ -171,7 +171,9 @@ public function toSymfonyRouteCollection()\n {\n $symfonyRoutes = new SymfonyRouteCollection;\n \n- $routes = $this->getRoutes();\n+ // When there are multiple URL matches, symfony will return the first match,\n+ // but in laravel, it should return the last matching route.\n+ $routes = array_reverse($this->getRoutes());\n \n foreach ($routes as $route) {\n if (! $route->isFallback) {", "filename": "src/Illuminate/Routing/AbstractRouteCollection.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.x\r\n- PHP Version: All versions\r\n- Database Driver & Version: SQLServer vs. MySQL have different behaviour\r\n\r\n### Description:\r\n\r\nFollow up to https://github.com/laravel/framework/pull/37505 and https://github.com/laravel/framework/pull/37647.\r\n\r\nWhen applying multiple order by clauses on a builder with identical column names, Laravel currently includes multiple such clauses in the generated SQL. Clauses added by calling `orderBy()` on the Builder have precedence over those added by global scopes (i guess it applies to local scopes too?).\r\n\r\nWhile MySQL just uses the last defined clause, SQLServer fails with an error complaining about the duplicates. Thus, only one clause should be present in the generated SQL. Semantically, it makes sense to me that explicit `orderBy()` calls override order by clauses set in global scopes. Similarly, later calls to `orderBy()` should override earlier calls.\r\n\r\n### Steps To Reproduce:\r\n\r\nSee test cases of https://github.com/laravel/framework/pull/37505 and https://github.com/laravel/framework/pull/37647. I think both are equally valid and worth fixing. The previously attempted solution did not manage to fix both.\r\n", "comments": [ { "body": "Welcoming PR's.", "created_at": "2021-06-11T08:34:39Z" }, { "body": "Hello @spawnia, is there any chance that you could try my branch [patch-1](https://github.com/Javdu10/framework/tree/patch-1) ?\r\n", "created_at": "2021-06-11T13:45:26Z" }, { "body": "Call `reorder()`? https://laravel.com/docs/8.x/queries#removing-existing-orderings", "created_at": "2021-06-11T20:07:39Z" }, { "body": "> Call `reorder()`? https://laravel.com/docs/8.x/queries#removing-existing-orderings\n\nI wish this was the fix @derekmd,but unfortunately scopes are called at the end of the construction of the query. Thus overwrites reorders\n\nThis issue got ignored in the past so there are no regression test written, they have to be discovered from running applications, unless this issue is tackle by someone really knowledgeable of the framework, I can only offer to break things and move fast.", "created_at": "2021-06-12T00:00:25Z" }, { "body": "Unfortunately, the fact that scopes are being applied last makes it hard to achieve the semantics I would expect. My mental model of global scopes is that they are supposed to be the baseline for queries of the model. Subsequent manipulation of the query builder should have precedence over them.\r\n\r\nMechanically, I get why Laravel does it. Adding the scopes from the beginning and applying them just before sending the query allows adding/removing scopes without doing much cleanup inbetween. Thus, I think we could go one of two ways:\r\n1. Reify that scopes are applied last and accept that order by in scopes will have precedence. Write tests accordingly and direct the fix @Javdu10 proposed towards Laravel 9.x. At least, this will clarify the current semantics and fix a real issue for SQLServer users.\r\n2. Change the mechanics of how global scope application and direct builder manipulation interact, such that global scopes apply first and direct builder manipulation has precedence. That would result in what I consider to be the most intuitive semantics, but requires non-trivial changes to a core part of Eloquent.", "created_at": "2021-06-14T07:50:01Z" }, { "body": "@spawnia I agree with the above and would go for 1. 2 is unlikely to happen as it would indeed have massive implications across the ecosystem. I think it's best that we continue this discussion through PR's to both docs (to highlight the current 8.x behavior), the 8.x branch (tests that verify the current behavior) and master branch (to fix the issues for SQL Server users). If anyone can send those in so we can take the conversation from that'd be great. Thanks all.", "created_at": "2021-06-14T09:48:13Z" } ], "number": 37660, "title": "Deduplicate order by while preserving semantics" }
{ "body": "Hello, it's me again, lot of things break, and I'm sorry for it.\r\nContext: #37505, #37582, #37647\r\nI've found that using the function `debug_backtrace()` I could see if the orderBy were called by a `callScope()` \r\nand simply ignoring the call\r\nThe test that were wrote pass but I'll let github run all the others\r\nThis fixes: #37660", "number": 37663, "review_comments": [], "title": "[8.x] Columns in the order by list must be unique" }
{ "commits": [ { "message": "Columns in the order by list must be unique\n\nMySql is ok with it, but SqlServer error out.\nSee a similar issue here: https://github.com/laravel/nova-issues/issues/1621" }, { "message": "override with next call" }, { "message": "Update Builder.php" }, { "message": "fix: \"undefined index: column\" from #37581" }, { "message": "Merge branch 'patch-1' of https://github.com/Javdu10/framework into patch-1" }, { "message": "add a regression test" }, { "message": "Ensure order by overrides global scope" }, { "message": "Extract variable" }, { "message": "Fixes #37660\n\nIt was my first time cherry picking commits and just\nsaw that i've made #baefe52 my own, which is not, sorry!" } ], "files": [ { "diff": "@@ -1983,7 +1983,24 @@ public function orderBy($column, $direction = 'asc')\n throw new InvalidArgumentException('Order direction must be \"asc\" or \"desc\".');\n }\n \n- $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [\n+ $ordersProperty = $this->unions ? 'unionOrders' : 'orders';\n+\n+ if (is_array($this->{$ordersProperty})) {\n+ foreach ($this->{$ordersProperty} as $key => $value) {\n+ if (isset($value['column']) && $value['column'] === $column) {\n+ $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);\n+\n+ if($trace[5]['function'] === 'callScope')\n+ return $this;\n+\n+ $this->{$ordersProperty}[$key]['direction'] = $direction;\n+\n+ return $this;\n+ }\n+ }\n+ }\n+\n+ $this->{$ordersProperty}[] = [\n 'column' => $column,\n 'direction' => $direction,\n ];", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -35,6 +35,16 @@ public function testGlobalScopeIsApplied()\n $this->assertEquals([1], $query->getBindings());\n }\n \n+ public function testOrderByOverridesGlobalScope()\n+ {\n+ $model = new EloquentGlobalScopeOrderTestModel;\n+ $query = $model->newQuery();\n+ $this->assertSame('select * from \"table\" order by \"name\" asc', $query->toSql());\n+\n+ $query = $model->newQuery()->orderBy('name', 'desc');\n+ $this->assertSame('select * from \"table\" order by \"name\" desc', $query->toSql());\n+ }\n+\n public function testGlobalScopeCanBeRemoved()\n {\n $model = new EloquentGlobalScopesTestModel;\n@@ -152,6 +162,20 @@ public function scopeOrApproved($query)\n }\n }\n \n+class EloquentGlobalScopeOrderTestModel extends Model\n+{\n+ protected $table = 'table';\n+\n+ public static function boot()\n+ {\n+ static::addGlobalScope(function ($query) {\n+ $query->orderBy('name', 'asc');\n+ });\n+\n+ parent::boot();\n+ }\n+}\n+\n class EloquentGlobalScopesWithRelationModel extends EloquentClosureGlobalScopesTestModel\n {\n protected $table = 'table2';", "filename": "tests/Database/DatabaseEloquentGlobalScopesTest.php", "status": "modified" }, { "diff": "@@ -1188,6 +1188,14 @@ public function testOrderBys()\n ->orderByRaw('field(category, ?, ?) asc', ['news', 'opinion']);\n $this->assertSame('(select * from \"posts\" where \"public\" = ?) union all (select * from \"videos\" where \"public\" = ?) order by field(category, ?, ?) asc', $builder->toSql());\n $this->assertEquals([1, 1, 'news', 'opinion'], $builder->getBindings());\n+\n+ $builder = $this->getBuilder();\n+ $builder->select('*')->from('users')->orderBy('name', 'asc');\n+ $builder->orderBy('name', 'desc');\n+ $builder->orderBy('email', 'desc');\n+ $builder->orderBy('email', 'asc');\n+ $builder->orderByRaw('\"age\" ? desc', ['foo']);\n+ $this->assertSame('select * from \"users\" order by \"name\" desc, \"email\" asc, \"age\" ? desc', $builder->toSql());\n }\n \n public function testReorder()", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.45.1\r\n- PHP Version: 8.x\r\n- Database Driver & Version: \r\n- Guzzle version: 7.3.0\r\n\r\n### Description:\r\n\r\nI notice that after to upgrade to 8.45.1 an error is raised when I attempt to perform a request in a cloned PendingRequest instance. I observed that this error is not raised with version 8.44.0.\r\n\r\nThe error raised is:\r\n\r\n`TypeError: Illuminate\\Http\\Client\\Events\\ResponseReceived::__construct(): Argument #1 ($request) must be of type Illuminate\\Http\\Client\\Request, null given, called in /home/vagrant/foobar/code/vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php on line 989`\r\n\r\n\r\nThe error is raised when the method \"dispatchResponseReceivedEvent\" is called and I observed that \"$this->request\" is null.\r\n\r\n### Steps To Reproduce:\r\n\r\n- Upgrade to Laravel 8.45.1\r\n- Run the following code (for example into Tinker):\r\n\r\n```\r\n$client = \\Http::timeout(10);\r\n$newClient = clone $client;\r\n$newClient->get('https://google.com');\r\n```\r\n\r\nI supect that this bug was introduced in https://github.com/laravel/framework/commit/065e130a0437423c3279a4aad9e3d32ea70a16f3\r\n", "comments": [ { "body": "ping @lukeraymonddowning ", "created_at": "2021-06-04T14:42:06Z" }, { "body": "This is caused by the `beforeSendingCallbacks` still viewing `$this` as the old object rather than the cloned object. Looking into a fix for it now.", "created_at": "2021-06-04T15:06:26Z" }, { "body": "Fixed in #37596", "created_at": "2021-06-04T15:12:38Z" } ], "number": 37594, "title": "[8.45.1] Cloned PendingRequest raises a \"($request) must be of type Illuminate\\Http\\Client\\Request, null given\" error" }
{ "body": "Fixes #37594\r\n\r\nThis was caused by the closures registered in the `beforeSendingCallbacks` referencing the original instance in memory. These callbacks now receive the current instance as the third parameter, which allows them to set the provided request and cookies on the correct object instance.", "number": 37596, "review_comments": [], "title": "[8.x] Bugfix for cloning issues with PendingRequest object" }
{ "commits": [ { "message": "BeforeSendingCallbacks receive the instance of the active PendingRequest object, allowing them to work with cloned PendingRequests." }, { "message": "CS fix" } ], "files": [ { "diff": "@@ -137,7 +137,7 @@ class PendingRequest\n *\n * @var \\Illuminate\\Http\\Client\\Request|null\n */\n- protected $request;\n+ protected $request = null;\n \n /**\n * Create a new HTTP Client instance.\n@@ -156,11 +156,11 @@ public function __construct(Factory $factory = null)\n 'http_errors' => false,\n ];\n \n- $this->beforeSendingCallbacks = collect([function (Request $request, array $options) {\n- $this->request = $request;\n- $this->cookies = $options['cookies'];\n+ $this->beforeSendingCallbacks = collect([function (Request $request, array $options, PendingRequest $instance) {\n+ $instance->request = $request;\n+ $instance->cookies = $options['cookies'];\n \n- $this->dispatchRequestSendingEvent();\n+ $instance->dispatchRequestSendingEvent();\n }]);\n }\n \n@@ -913,7 +913,8 @@ public function runBeforeSendingCallbacks($request, array $options)\n return tap($request, function ($request) use ($options) {\n $this->beforeSendingCallbacks->each->__invoke(\n (new Request($request))->withData($options['laravel_data']),\n- $options\n+ $options,\n+ $this\n );\n });\n }\n@@ -985,9 +986,15 @@ protected function dispatchRequestSendingEvent()\n */\n protected function dispatchResponseReceivedEvent(Response $response)\n {\n- if ($dispatcher = optional($this->factory)->getDispatcher()) {\n- $dispatcher->dispatch(new ResponseReceived($this->request, $response));\n+ if (! $dispatcher = optional($this->factory)->getDispatcher()) {\n+ return;\n+ }\n+\n+ if (! $this->request) {\n+ return;\n }\n+\n+ $dispatcher->dispatch(new ResponseReceived($this->request, $response));\n }\n \n /**", "filename": "src/Illuminate/Http/Client/PendingRequest.php", "status": "modified" }, { "diff": "@@ -939,4 +939,20 @@ public function testTheRequestSendingAndResponseReceivedEventsAreFiredWhenAReque\n \n m::close();\n }\n+\n+ public function testClonedClientsWorkSuccessfullyWithTheRequestObject()\n+ {\n+ $events = m::mock(Dispatcher::class);\n+ $events->shouldReceive('dispatch')->once()->with(m::type(RequestSending::class));\n+ $events->shouldReceive('dispatch')->once()->with(m::type(ResponseReceived::class));\n+\n+ $factory = new Factory($events);\n+\n+ $client = $factory->timeout(10);\n+ $clonedClient = clone $client;\n+\n+ $clonedClient->get('https://example.com');\n+\n+ m::close();\n+ }\n }", "filename": "tests/Http/HttpClientTest.php", "status": "modified" } ] }
{ "body": "Hi,\r\n\r\nif you work in a MSSQL database not in the default schema dbo, then faild to delete default constraint via \"php artisan migrate\".\r\nThe problem is in the function compileDropDefaultConstraint in class Illuminate\\Database\\Schema\\Grammars\\SqlServerGrammar . In the function the dbo schema is hard coded. \r\n\r\nin Illuminate\\Database\\Schema\\Grammars\\SqlServerGrammar.php\r\n```\r\n /**\r\n * Compile a drop default constraint command.\r\n *\r\n * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\r\n * @param \\Illuminate\\Support\\Fluent $command\r\n * @return string\r\n */\r\n public function compileDropDefaultConstraint(Blueprint $blueprint, Fluent $command)\r\n {\r\n $columns = \"'\".implode(\"','\", $command->columns).\"'\";\r\n\r\n $tableName = $this->getTablePrefix().$blueprint->getTable();\r\n\r\n $sql = \"DECLARE @sql NVARCHAR(MAX) = '';\";\r\n $sql .= \"SELECT @sql += 'ALTER TABLE [dbo].[{$tableName}] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' \";\r\n $sql .= 'FROM SYS.COLUMNS ';\r\n $sql .= \"WHERE [object_id] = OBJECT_ID('[dbo].[{$tableName}]') AND [name] in ({$columns}) AND [default_object_id] <> 0;\";\r\n $sql .= 'EXEC(@sql)';\r\n\r\n return $sql;\r\n }\r\n```\r\nOn version \"Laravel Framework 8.42.0\"", "comments": [ { "body": "I have no plans to look into this on my end so feel free to send a PR.", "created_at": "2021-05-19T13:07:22Z" }, { "body": "hi,\r\nstep to reproduce:\r\n\r\n1. create an new Mircosoft SQL database \r\n2. create an new schema in the database\r\n3. create an new sql user, set default schema on new schema and get right to create,edit and delte tabelles and data.\r\n4. create new migrate\r\n```php\r\nclass TEST extends Migration {\r\n public function up()\r\n {\r\n Schema::create('testTable', function (Blueprint $table) {\r\n $table->integer('id')->autoIncrement();\r\n $table->date('dateCloumn')->default(DB::raw('GETDATE()'));\r\n $table->timestamps();\r\n });\r\n Schema::table('testTable', function (Blueprint $table) {\r\n $table->date('dateCloumn')->default(null)->change();\r\n });\r\n }\r\n}\r\n```\r\n5. execute migrate\r\n```\r\n Illuminate\\Database\\QueryException \r\n SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]'DF_FDF4D9DA_7A859515' is not a constraint. (SQL: ALTER TABLE testTable DROP CONSTRAINT DF_FDF4D9DA_7A859515)\r\n```\r\nin the database are not constrain with this name", "created_at": "2021-06-01T13:43:39Z" }, { "body": "@MichaelGottschlich that's not a valid use case. It doesn't makes sense to change a column immediately in the same migration. Does this happen in different migrations?", "created_at": "2021-06-01T13:47:14Z" }, { "body": "this also happens when you do it in different migrations. \r\n\r\nI just put it in one migration for better reproduction.\r\n\r\nThe problem also occurs when I do it in the dbo scheme, I have tested that before. ", "created_at": "2021-06-02T06:24:18Z" }, { "body": "Closing this because we only have gotten one report so far for this. We'll not be pursuing a fix for this atm.", "created_at": "2021-06-15T14:04:19Z" }, { "body": "I'm running into this problem when trying to rename two columns (and add a column) in the same migration:\r\n\r\n```php\r\nclass Repro extends Migration\r\n{\r\n public function up()\r\n {\r\n Schema::table('table', function (Blueprint $table) {\r\n $table->renameColumn('foo', 'bar'); // string column\r\n $table->renameColumn('asdf', 'qwerty'); // also a string column\r\n\r\n $table->string('xyz')->default('pdq');\r\n });\r\n }\r\n\r\n // ...\r\n}\r\n```\r\n\r\nError:\r\n\r\n```\r\nIlluminate\\Database\\QueryException \r\n\r\nSQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]'DF_BFB93FBC_503917DA' is not a constraint. (SQL: ALTER TABLE table DROP CONSTRAINT DF_BFB93FBC_503917DA)\r\n```", "created_at": "2021-07-15T14:20:55Z" }, { "body": "I'm having the same issue.\r\nThis also is a valid use-case when adding a new non-null column without default. SQL Server rejects the statement because the new column will contain null as default however it is marked as non-null. However I want all succinct inserts to explicitly insert a value into the column and not use a default value. Since one cannot do that otherwise apart from raw SQL this is a valid use-case.", "created_at": "2022-05-25T07:27:49Z" }, { "body": "After some debugging it seems the issue lies within doctrine. The `SQLServerGrammar` is fine and works, however Doctrine/DBAL is used for the change command, which ultimately uses `generateDefaultContraintName` in `getAlterTableDropDefaultConstraintClause` (SQLServerPlatform.php) which is wrong in this context. It generates a *new* contraint name, instead of getting the existing constraint name. I know too little about doctrine and laravel/illuminate to know where the issue precisely is. But simply using `compileDropDefaultConstraint` from the SQLServer gammar would fix the issue.", "created_at": "2022-05-25T08:37:02Z" }, { "body": "I've also opened an issue with DBAL. Though I don't know if it makes more sense to use the existing `compileDropDefaultConstraint` from SQLServerGrammar.php or wait on Doctrine/DBAL to fix the issue.", "created_at": "2022-05-25T09:00:36Z" } ], "number": 37419, "title": "Migrate failed to drop default constrains in an mssql databases" }
{ "body": "PR to fix #37419 ", "number": 37424, "review_comments": [], "title": "[8.x] Fix SqlServerGrammar::compileDropDefaultConstraint: remove hardcode schema in sql command" }
{ "commits": [ { "message": "fix compileDropDefaultConstraint: remove hardcode schema" }, { "message": "fix phpunit test in tests/Database/DatabaseSqlServerSchemaGrammarTest.php" } ], "files": [ { "diff": "@@ -238,9 +238,9 @@ public function compileDropDefaultConstraint(Blueprint $blueprint, Fluent $comma\n $tableName = $this->getTablePrefix().$blueprint->getTable();\n \n $sql = \"DECLARE @sql NVARCHAR(MAX) = '';\";\n- $sql .= \"SELECT @sql += 'ALTER TABLE [dbo].[{$tableName}] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' \";\n+ $sql .= \"SELECT @sql += 'ALTER TABLE [{$tableName}] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' \";\n $sql .= 'FROM SYS.COLUMNS ';\n- $sql .= \"WHERE [object_id] = OBJECT_ID('[dbo].[{$tableName}]') AND [name] in ({$columns}) AND [default_object_id] <> 0;\";\n+ $sql .= \"WHERE [object_id] = OBJECT_ID('[{$tableName}]') AND [name] in ({$columns}) AND [default_object_id] <> 0;\";\n $sql .= 'EXEC(@sql)';\n \n return $sql;", "filename": "src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -123,7 +123,7 @@ public function testDropColumnDropsCreatesSqlToDropDefaultConstraints()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertCount(1, $statements);\n- $this->assertSame(\"DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE [dbo].[foo] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID('[dbo].[foo]') AND [name] in ('bar') AND [default_object_id] <> 0;EXEC(@sql);alter table \\\"foo\\\" drop column \\\"bar\\\"\", $statements[0]);\n+ $this->assertSame(\"DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE [foo] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID('[foo]') AND [name] in ('bar') AND [default_object_id] <> 0;EXEC(@sql);alter table \\\"foo\\\" drop column \\\"bar\\\"\", $statements[0]);\n }\n \n public function testDropPrimary()\n@@ -184,7 +184,7 @@ public function testDropConstrainedForeignId()\n \n $this->assertCount(2, $statements);\n $this->assertSame('alter table \"users\" drop constraint \"users_foo_foreign\"', $statements[0]);\n- $this->assertSame('DECLARE @sql NVARCHAR(MAX) = \\'\\';SELECT @sql += \\'ALTER TABLE [dbo].[users] DROP CONSTRAINT \\' + OBJECT_NAME([default_object_id]) + \\';\\' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID(\\'[dbo].[users]\\') AND [name] in (\\'foo\\') AND [default_object_id] <> 0;EXEC(@sql);alter table \"users\" drop column \"foo\"', $statements[1]);\n+ $this->assertSame('DECLARE @sql NVARCHAR(MAX) = \\'\\';SELECT @sql += \\'ALTER TABLE [users] DROP CONSTRAINT \\' + OBJECT_NAME([default_object_id]) + \\';\\' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID(\\'[users]\\') AND [name] in (\\'foo\\') AND [default_object_id] <> 0;EXEC(@sql);alter table \"users\" drop column \"foo\"', $statements[1]);\n }\n \n public function testDropTimestamps()", "filename": "tests/Database/DatabaseSqlServerSchemaGrammarTest.php", "status": "modified" } ] }
{ "body": "In case your model using HasOne, HasMany the query building needs additional\ncheck for foreign_key != null\n\nIf don't you will receive any related item having foreign_key = null on a new object.\nExample of wrong behaviour:\n\n$foo = new Foo();\n$foo->save();\n\n$bar = new Bar();\n$this_should_not_holding_any_relation = $bar->getFoos()->getResutls()->toArray()\n\nIn fact currenctly $bar->getFoos() finds any Foo() having foreign_key = null.\nSQL is \"where bar.id = foo.foreign_key\"\nwich is in fact \"null = null\" (any unrelated foo item)\n", "comments": [ { "body": "Is it the same as https://github.com/laravel/framework/issues/5649?\n", "created_at": "2015-03-17T14:20:32Z" }, { "body": "@RomainLanz Yes, seems to be the same issue.\n", "created_at": "2015-03-17T14:28:25Z" }, { "body": "Please fix the tests.\n", "created_at": "2015-03-18T20:32:24Z" }, { "body": "Ping @pumatertion.\n", "created_at": "2015-03-20T20:13:18Z" }, { "body": "I have no idea how to run the tests of vendor/laravel/framework/tests.\nmaybe you can give me some informations how to run them?\n", "created_at": "2015-03-26T12:16:27Z" }, { "body": "> I have no idea how to run the tests of vendor/laravel/framework/tests.\n\nClone laravel/framework. Run composer install. Run phpunit.\n", "created_at": "2015-03-26T12:51:30Z" }, { "body": "Running all tests of laravel in a base distibution created with \"laravel new foo\" needs to require mockable package and also needs directory added to phpunit.xml?\n", "created_at": "2015-03-26T12:59:47Z" }, { "body": "You need to clone this repository (framework), and not the default Laravel repository.\n", "created_at": "2015-03-26T13:05:29Z" }, { "body": "Specifically, you need to clone your fork.\n", "created_at": "2015-03-26T13:07:32Z" }, { "body": "Sorry, have no idea what this mocking stuff has to do. All these magic __call stuff in the query building process also makes me really nuts. Its a black box for me what is happening everywhere. Quitting laravel with much frustration now i think.\n", "created_at": "2015-03-26T13:53:10Z" }, { "body": "Not sure if I did this right, since I don't know anything about Mockery either, but try this: https://github.com/tremby/framework/commit/99b9772c65d54e86a3c78945e5c7f9ea91016ad6 -- tests now pass.\n\nNote that my original failing unit test https://github.com/laravel/framework/pull/5695 still fails (here's the same commit rebased on to current 5.0: https://github.com/tremby/framework/commit/f45444593003b05e15409cbcc1a89abfebefd3b4). See discussion in https://github.com/laravel/framework/issues/5649 about this.\n\nSo either this fix should be implemented at a lower level to make my test pass, or there should be a new passing test for this fix as it stands, as the project maintainers see fit.\n", "created_at": "2015-03-26T20:00:22Z" }, { "body": "@tremby thanks for adjusting the tests. maybe you can investigate further?\n", "created_at": "2015-03-26T22:51:33Z" }, { "body": "Afraid not. As I said over in the bug report #5649 I don't know how to either write a suitable test for your bugfix or to rewrite the bugfix to satisfy the test I did write. Hopefully the maintainers can provide some guidance.\n", "created_at": "2015-03-26T22:57:55Z" }, { "body": "(Would have been nice if you'd used my actual commit, so my credits are in it, but I'll deal.)\n", "created_at": "2015-03-26T22:58:49Z" }, { "body": "Ping @phurni\n", "created_at": "2015-03-27T20:29:31Z" } ], "number": 8033, "title": "[5.0] hasMany or hasOne neets to check for foreign_key != null" }
{ "body": "Reference:\r\nOriginal PR that applied this change: #8033\r\nInquiry from laravel/ideas regarding this fix: https://github.com/laravel/ideas/issues/1341\r\n\r\nChange Notes:\r\nA whereNotNull check was added to the constraints of all HasOne, HasMany, and HasMorph relations queries to avoid a corner-case where new models with auto incremented IDs are created and have not had an ID assigned.\r\n\r\nThis forcibly includes an additional IS NOT NULL clause to all relations queries, where in 99% of cases it is not required.\r\n\r\nThis rectifies that change by only applying that clause in the unlikely case where the parentKey is still null, and reduces the size of relations queries for most usage.\r\n\r\nTo visualize the potential impact of this change, here are the queries as they are now compared to with the change applied\r\n\r\nBefore:\r\n```\r\nselect * from group_members\r\nwhere group_members.group_id = 28\r\n and group_members.group_id is not null\r\n```\r\nAfter:\r\n```\r\nselect * from group_members\r\nwhere group_members.group_id = 28\r\n```\r\n\r\nQuery when parentKey is null (unchanged):\r\n```\r\nselect * from group_members\r\nwhere group_members.group_id is null\r\n and group_members.group_id is not null\r\n```\r\n\r\n\r\nI'm unaware of any real-world situation where the corner-case that encouraged this original bug fix would actually apply, so I struggled writing tests for it. I've updated the existing tests to prevent them from failing by adding an optional parameter to the shared getRelations* methods, and only applying the `whereNotNull` expectation when necessary. However I did not create any actual tests to simulate the actual null id condition. Any suggestions on how those tests should actually be structured would be appreciated.\r\n\r\nImpact: Remove unnecessary where clause for most real-world relations queries usages. This results in reduced bandwidth to database and reduced effort by query parsers where the additional clause is (hopefully) optimized away.\r\n\r\nI've applied this to 6.x as I consider the fix to be valuable to LTS devs (including myself on several projects) due to the positive impact to databases.\r\n", "number": 36905, "review_comments": [], "title": "[6.x] Exclude `whereNotNull` check in relations query" }
{ "commits": [ { "message": "Exclude `whereNotNull` check in relations query\n\nA whereNotNull check was added to the contstraints of all HasOne, HasMany, and HasMorph relations queries to avoid a corner-case where new models with auto incremented IDs are created and have not had an ID assigned.\n\nThis forcibly includes an additional IS NOT NULL clause to all relations queries, where in 99% of cases it is not required.\n\nThis rectifies that change by only applying that clause in the unlikely case where the parentKey is still null, and reduces the size of relations queries for most usage" } ], "files": [ { "diff": "@@ -67,9 +67,14 @@ public function make(array $attributes = [])\n public function addConstraints()\n {\n if (static::$constraints) {\n- $this->query->where($this->foreignKey, '=', $this->getParentKey());\n+ $parentKey = $this->getParentKey();\n+ $this->query->where($this->foreignKey, '=', $parentKey);\n \n- $this->query->whereNotNull($this->foreignKey);\n+ // When $parentKey is null the above line is treated as whereNull($this->foreignKey)\n+ // Avoid loading all models with null foreignKey in that situation\n+ if (is_null($parentKey)) {\n+ $this->query->whereNotNull($this->foreignKey);\n+ }\n }\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php", "status": "modified" }, { "diff": "@@ -252,15 +252,17 @@ public function testCreateManyCreatesARelatedModelForEachRecord()\n $this->assertEquals($colin, $instances[1]);\n }\n \n- protected function getRelation()\n+ protected function getRelation($id = 1)\n {\n $builder = m::mock(Builder::class);\n- $builder->shouldReceive('whereNotNull')->with('table.foreign_key');\n- $builder->shouldReceive('where')->with('table.foreign_key', '=', 1);\n+ if (is_null($id)) {\n+ $builder->shouldReceive('whereNotNull')->once()->with('table.foreign_key');\n+ }\n+ $builder->shouldReceive('where')->once()->with('table.foreign_key', '=', $id);\n $related = m::mock(Model::class);\n $builder->shouldReceive('getModel')->andReturn($related);\n $parent = m::mock(Model::class);\n- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);\n+ $parent->shouldReceive('getAttribute')->with('id')->andReturn($id);\n $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');\n $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');\n ", "filename": "tests/Database/DatabaseEloquentHasManyTest.php", "status": "modified" }, { "diff": "@@ -196,15 +196,17 @@ public function testRelationCountQueryCanBeBuilt()\n $relation->getRelationExistenceCountQuery($builder, $builder);\n }\n \n- protected function getRelation()\n+ protected function getRelation($id = 1)\n {\n $this->builder = m::mock(Builder::class);\n- $this->builder->shouldReceive('whereNotNull')->with('table.foreign_key');\n- $this->builder->shouldReceive('where')->with('table.foreign_key', '=', 1);\n+ if (is_null($id)) {\n+ $this->builder->shouldReceive('whereNotNull')->once()->with('table.foreign_key');\n+ }\n+ $this->builder->shouldReceive('where')->once()->with('table.foreign_key', '=', $id);\n $this->related = m::mock(Model::class);\n $this->builder->shouldReceive('getModel')->andReturn($this->related);\n $this->parent = m::mock(Model::class);\n- $this->parent->shouldReceive('getAttribute')->with('id')->andReturn(1);\n+ $this->parent->shouldReceive('getAttribute')->with('id')->andReturn($id);\n $this->parent->shouldReceive('getAttribute')->with('username')->andReturn('taylor');\n $this->parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');\n $this->parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');", "filename": "tests/Database/DatabaseEloquentHasOneTest.php", "status": "modified" }, { "diff": "@@ -253,37 +253,41 @@ public function testCreateFunctionOnNamespacedMorph()\n $this->assertEquals($created, $relation->create(['name' => 'taylor']));\n }\n \n- protected function getOneRelation()\n+ protected function getOneRelation($id = 1)\n {\n $builder = m::mock(Builder::class);\n- $builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');\n- $builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);\n+ if (is_null($id)) {\n+ $builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');\n+ }\n+ $builder->shouldReceive('where')->once()->with('table.morph_id', '=', $id);\n $related = m::mock(Model::class);\n $builder->shouldReceive('getModel')->andReturn($related);\n $parent = m::mock(Model::class);\n- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);\n+ $parent->shouldReceive('getAttribute')->with('id')->andReturn($id);\n $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));\n $builder->shouldReceive('where')->once()->with('table.morph_type', get_class($parent));\n \n return new MorphOne($builder, $parent, 'table.morph_type', 'table.morph_id', 'id');\n }\n \n- protected function getManyRelation()\n+ protected function getManyRelation($id = 1)\n {\n $builder = m::mock(Builder::class);\n- $builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');\n- $builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);\n+ if (is_null($id)) {\n+ $builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');\n+ }\n+ $builder->shouldReceive('where')->once()->with('table.morph_id', '=', $id);\n $related = m::mock(Model::class);\n $builder->shouldReceive('getModel')->andReturn($related);\n $parent = m::mock(Model::class);\n- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);\n+ $parent->shouldReceive('getAttribute')->with('id')->andReturn($id);\n $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));\n $builder->shouldReceive('where')->once()->with('table.morph_type', get_class($parent));\n \n return new MorphMany($builder, $parent, 'table.morph_type', 'table.morph_id', 'id');\n }\n \n- protected function getNamespacedRelation($alias)\n+ protected function getNamespacedRelation($alias, $id = 1)\n {\n require_once __DIR__.'/stubs/EloquentModelNamespacedStub.php';\n \n@@ -292,12 +296,14 @@ protected function getNamespacedRelation($alias)\n ]);\n \n $builder = m::mock(Builder::class);\n- $builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');\n- $builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);\n+ if (is_null($id)) {\n+ $builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');\n+ }\n+ $builder->shouldReceive('where')->once()->with('table.morph_id', '=', $id);\n $related = m::mock(Model::class);\n $builder->shouldReceive('getModel')->andReturn($related);\n $parent = m::mock(EloquentModelNamespacedStub::class);\n- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);\n+ $parent->shouldReceive('getAttribute')->with('id')->andReturn($id);\n $parent->shouldReceive('getMorphClass')->andReturn($alias);\n $builder->shouldReceive('where')->once()->with('table.morph_type', $alias);\n ", "filename": "tests/Database/DatabaseEloquentMorphTest.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": "Fixes an issue where missing fields in the data being validated will cause a deprecation warning when formatting the message, because `str_replace()` expects a string but gets `null`:\r\nhttps://github.com/laravel/framework/blob/a7ec58e55daa54568c45bd6b83754179dee950f6/src/Illuminate/Validation/Concerns/FormatsMessages.php#L309-L311\r\n\r\n---\r\n\r\nThis is already covered but requires PHP > 8.0 to trigger:\r\nhttps://github.com/laravel/framework/blob/354c57b8cb457549114074c500944455a288d6cc/tests/Validation/ValidationValidatorTest.php#L110-L118\r\nhttps://github.com/laravel/framework/blob/354c57b8cb457549114074c500944455a288d6cc/tests/Validation/ValidationValidatorTest.php#L881-L885\r\n\r\n#### Full Stacktrace\r\n```\r\n [2021-03-06 15:20:07] testing.ERROR: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated {\"userId\":35,\"exception\":\"[object] (ErrorException(code: 0): str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated at ./vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php:310)\r\n[stacktrace]\r\n#0 [internal function]: Illuminate\\\\Foundation\\\\Bootstrap\\\\HandleExceptions->handleError()\r\n#1 ./vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php(310): str_replace()\r\n#2 ./vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php(219): Illuminate\\\\Validation\\\\Validator->replaceInputPlaceholder()\r\n#3 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(814): Illuminate\\\\Validation\\\\Validator->makeReplacements()\r\n#4 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(566): Illuminate\\\\Validation\\\\Validator->addFailure()\r\n#5 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(388): Illuminate\\\\Validation\\\\Validator->validateAttribute()\r\n#6 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(419): Illuminate\\\\Validation\\\\Validator->passes()\r\n#7 ./vendor/laravel/framework/src/Illuminate/Validation/ValidatesWhenResolvedTrait.php(25): Illuminate\\\\Validation\\\\Validator->fails()\r\n#8 ./vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php(30): Illuminate\\\\Foundation\\\\Http\\\\FormRequest->validateResolved()\r\n#9 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(1219): Illuminate\\\\Foundation\\\\Providers\\\\FormRequestServiceProvider->Illuminate\\\\Foundation\\\\Providers\\\\{closure}()\r\n#10 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(1183): Illuminate\\\\Container\\\\Container->fireCallbackArray()\r\n#11 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(1168): Illuminate\\\\Container\\\\Container->fireAfterResolvingCallbacks()\r\n#12 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(732): Illuminate\\\\Container\\\\Container->fireResolvingCallbacks()\r\n#13 ./vendor/laravel/framework/src/Illuminate/Foundation/Application.php(841): Illuminate\\\\Container\\\\Container->resolve()\r\n#14 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(651): Illuminate\\\\Foundation\\\\Application->resolve()\r\n#15 ./vendor/laravel/framework/src/Illuminate/Foundation/Application.php(826): Illuminate\\\\Container\\\\Container->make()\r\n#16 ./vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php(79): Illuminate\\\\Foundation\\\\Application->make()\r\n#17 ./vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php(48): Illuminate\\\\Routing\\\\ControllerDispatcher->transformDependency()\r\n#18 ./vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php(28): Illuminate\\\\Routing\\\\ControllerDispatcher->resolveMethodDependencies()\r\n#19 ./vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(41): Illuminate\\\\Routing\\\\ControllerDispatcher->resolveClassMethodDependencies()\r\n#20 ./vendor/laravel/framework/src/Illuminate/Routing/Route.php(254): Illuminate\\\\Routing\\\\ControllerDispatcher->dispatch()\r\n#21 ./vendor/laravel/framework/src/Illuminate/Routing/Route.php(197): Illuminate\\\\Routing\\\\Route->runController()\r\n#22 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(693): Illuminate\\\\Routing\\\\Route->run()\r\n#23 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\\\Routing\\\\Router->Illuminate\\\\Routing\\\\{closure}()\r\n#24 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#25 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Routing\\\\Middleware\\\\SubstituteBindings->handle()\r\n#26 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(127): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#27 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(103): Illuminate\\\\Routing\\\\Middleware\\\\ThrottleRequests->handleRequest()\r\n#28 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(55): Illuminate\\\\Routing\\\\Middleware\\\\ThrottleRequests->handleRequestUsingNamedLimiter()\r\n#29 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Routing\\\\Middleware\\\\ThrottleRequests->handle()\r\n#30 ./vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#31 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Auth\\\\Middleware\\\\Authenticate->handle()\r\n#32 ./vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php(33): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#33 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Laravel\\\\Sanctum\\\\Http\\\\Middleware\\\\EnsureFrontendRequestsAreStateful->Laravel\\\\Sanctum\\\\Http\\\\Middleware\\\\{closure}()\r\n#34 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#35 ./vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php(34): Illuminate\\\\Pipeline\\\\Pipeline->then()\r\n#36 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Laravel\\\\Sanctum\\\\Http\\\\Middleware\\\\EnsureFrontendRequestsAreStateful->handle()\r\n#37 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#38 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(695): Illuminate\\\\Pipeline\\\\Pipeline->then()\r\n#39 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(670): Illuminate\\\\Routing\\\\Router->runRouteWithinStack()\r\n#40 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(636): Illuminate\\\\Routing\\\\Router->runRoute()\r\n#41 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(625): Illuminate\\\\Routing\\\\Router->dispatchToRoute()\r\n#42 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(166): Illuminate\\\\Routing\\\\Router->dispatch()\r\n#43 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\\\Foundation\\\\Http\\\\Kernel->Illuminate\\\\Foundation\\\\Http\\\\{closure}()\r\n#44 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#45 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\TransformsRequest->handle()\r\n#46 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#47 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\TransformsRequest->handle()\r\n#48 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#49 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\ValidatePostSize->handle()\r\n#50 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#51 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\PreventRequestsDuringMaintenance->handle()\r\n#52 ./vendor/fruitcake/laravel-cors/src/HandleCors.php(57): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#53 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\\\\Cors\\\\HandleCors->handle()\r\n#54 ./vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#55 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\\\\Proxy\\\\TrustProxies->handle()\r\n#56 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#57 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(141): Illuminate\\\\Pipeline\\\\Pipeline->then()\r\n#58 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(110): Illuminate\\\\Foundation\\\\Http\\\\Kernel->sendRequestThroughRouter()\r\n#59 ./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(508): Illuminate\\\\Foundation\\\\Http\\\\Kernel->handle()\r\n#60 ./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(474): Illuminate\\\\Foundation\\\\Testing\\\\TestCase->call()\r\n#61 ./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(333): Illuminate\\\\Foundation\\\\Testing\\\\TestCase->json()\r\n#62 ./tests/Feature/Api/Projects/CreateProjectTest.php(119): Illuminate\\\\Foundation\\\\Testing\\\\TestCase->postJson()\r\n#63 ./vendor/phpunit/phpunit/src/Framework/TestCase.php(1526): Tests\\\\Feature\\\\Api\\\\Projects\\\\CreateProjectTest->cannot_create_project_without_name()\r\n#64 ./vendor/phpunit/phpunit/src/Framework/TestCase.php(1132): PHPUnit\\\\Framework\\\\TestCase->runTest()\r\n#65 ./vendor/phpunit/phpunit/src/Framework/TestResult.php(722): PHPUnit\\\\Framework\\\\TestCase->runBare()\r\n#66 ./vendor/phpunit/phpunit/src/Framework/TestCase.php(884): PHPUnit\\\\Framework\\\\TestResult->run()\r\n#67 ./vendor/phpunit/phpunit/src/Framework/TestSuite.php(677): PHPUnit\\\\Framework\\\\TestCase->run()\r\n#68 ./vendor/phpunit/phpunit/src/Framework/TestSuite.php(677): PHPUnit\\\\Framework\\\\TestSuite->run()\r\n#69 ./vendor/phpunit/phpunit/src/Framework/TestSuite.php(677): PHPUnit\\\\Framework\\\\TestSuite->run()\r\n#70 ./vendor/phpunit/phpunit/src/TextUI/TestRunner.php(667): PHPUnit\\\\Framework\\\\TestSuite->run()\r\n#71 ./vendor/phpunit/phpunit/src/TextUI/Command.php(142): PHPUnit\\\\TextUI\\\\TestRunner->run()\r\n#72 ./vendor/phpunit/phpunit/src/TextUI/Command.php(95): PHPUnit\\\\TextUI\\\\Command->run()\r\n#73 ./vendor/phpunit/phpunit/phpunit(61): PHPUnit\\\\TextUI\\\\Command::main()\r\n#74 {main}\r\n\"} \r\n```", "number": 36622, "review_comments": [], "title": "[8.x] Fix replacing required :input with null on PHP 8.1" }
{ "commits": [ { "message": "Fix replacing required :input with null on PHP 8.1\n\nFixes an issue where data lacking one or more of the fields under\nvalidation will cause tests to fail with an `ErrorException`.\n\nThat exception is a PHP deprecation warning triggered by the call to\n`str_replace()` inside `replaceInputPlaceholder()`, which assumes the\nvalue returned from `getDisplayableValue()` will always be a string." } ], "files": [ { "diff": "@@ -336,7 +336,7 @@ public function getDisplayableValue($attribute, $value)\n return $value ? 'true' : 'false';\n }\n \n- return $value;\n+ return (string) $value;\n }\n \n /**", "filename": "src/Illuminate/Validation/Concerns/FormatsMessages.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": "Fixes an issue where missing fields in the data being validated will cause a deprecation warning when formatting the message, because `str_replace()` expects a string but gets `null`:\r\nhttps://github.com/laravel/framework/blob/a7ec58e55daa54568c45bd6b83754179dee950f6/src/Illuminate/Validation/Concerns/FormatsMessages.php#L309-L311\r\n\r\n---\r\n\r\nThis is already covered but requires PHP > 8.0 to trigger:\r\nhttps://github.com/laravel/framework/blob/354c57b8cb457549114074c500944455a288d6cc/tests/Validation/ValidationValidatorTest.php#L110-L118\r\nhttps://github.com/laravel/framework/blob/354c57b8cb457549114074c500944455a288d6cc/tests/Validation/ValidationValidatorTest.php#L881-L885\r\n\r\n#### Full Stacktrace\r\n```\r\n [2021-03-06 15:20:07] testing.ERROR: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated {\"userId\":35,\"exception\":\"[object] (ErrorException(code: 0): str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated at ./vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php:310)\r\n[stacktrace]\r\n#0 [internal function]: Illuminate\\\\Foundation\\\\Bootstrap\\\\HandleExceptions->handleError()\r\n#1 ./vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php(310): str_replace()\r\n#2 ./vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php(219): Illuminate\\\\Validation\\\\Validator->replaceInputPlaceholder()\r\n#3 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(814): Illuminate\\\\Validation\\\\Validator->makeReplacements()\r\n#4 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(566): Illuminate\\\\Validation\\\\Validator->addFailure()\r\n#5 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(388): Illuminate\\\\Validation\\\\Validator->validateAttribute()\r\n#6 ./vendor/laravel/framework/src/Illuminate/Validation/Validator.php(419): Illuminate\\\\Validation\\\\Validator->passes()\r\n#7 ./vendor/laravel/framework/src/Illuminate/Validation/ValidatesWhenResolvedTrait.php(25): Illuminate\\\\Validation\\\\Validator->fails()\r\n#8 ./vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php(30): Illuminate\\\\Foundation\\\\Http\\\\FormRequest->validateResolved()\r\n#9 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(1219): Illuminate\\\\Foundation\\\\Providers\\\\FormRequestServiceProvider->Illuminate\\\\Foundation\\\\Providers\\\\{closure}()\r\n#10 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(1183): Illuminate\\\\Container\\\\Container->fireCallbackArray()\r\n#11 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(1168): Illuminate\\\\Container\\\\Container->fireAfterResolvingCallbacks()\r\n#12 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(732): Illuminate\\\\Container\\\\Container->fireResolvingCallbacks()\r\n#13 ./vendor/laravel/framework/src/Illuminate/Foundation/Application.php(841): Illuminate\\\\Container\\\\Container->resolve()\r\n#14 ./vendor/laravel/framework/src/Illuminate/Container/Container.php(651): Illuminate\\\\Foundation\\\\Application->resolve()\r\n#15 ./vendor/laravel/framework/src/Illuminate/Foundation/Application.php(826): Illuminate\\\\Container\\\\Container->make()\r\n#16 ./vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php(79): Illuminate\\\\Foundation\\\\Application->make()\r\n#17 ./vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php(48): Illuminate\\\\Routing\\\\ControllerDispatcher->transformDependency()\r\n#18 ./vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php(28): Illuminate\\\\Routing\\\\ControllerDispatcher->resolveMethodDependencies()\r\n#19 ./vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(41): Illuminate\\\\Routing\\\\ControllerDispatcher->resolveClassMethodDependencies()\r\n#20 ./vendor/laravel/framework/src/Illuminate/Routing/Route.php(254): Illuminate\\\\Routing\\\\ControllerDispatcher->dispatch()\r\n#21 ./vendor/laravel/framework/src/Illuminate/Routing/Route.php(197): Illuminate\\\\Routing\\\\Route->runController()\r\n#22 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(693): Illuminate\\\\Routing\\\\Route->run()\r\n#23 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\\\Routing\\\\Router->Illuminate\\\\Routing\\\\{closure}()\r\n#24 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#25 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Routing\\\\Middleware\\\\SubstituteBindings->handle()\r\n#26 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(127): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#27 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(103): Illuminate\\\\Routing\\\\Middleware\\\\ThrottleRequests->handleRequest()\r\n#28 ./vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(55): Illuminate\\\\Routing\\\\Middleware\\\\ThrottleRequests->handleRequestUsingNamedLimiter()\r\n#29 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Routing\\\\Middleware\\\\ThrottleRequests->handle()\r\n#30 ./vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#31 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Auth\\\\Middleware\\\\Authenticate->handle()\r\n#32 ./vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php(33): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#33 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Laravel\\\\Sanctum\\\\Http\\\\Middleware\\\\EnsureFrontendRequestsAreStateful->Laravel\\\\Sanctum\\\\Http\\\\Middleware\\\\{closure}()\r\n#34 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#35 ./vendor/laravel/sanctum/src/Http/Middleware/EnsureFrontendRequestsAreStateful.php(34): Illuminate\\\\Pipeline\\\\Pipeline->then()\r\n#36 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Laravel\\\\Sanctum\\\\Http\\\\Middleware\\\\EnsureFrontendRequestsAreStateful->handle()\r\n#37 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#38 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(695): Illuminate\\\\Pipeline\\\\Pipeline->then()\r\n#39 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(670): Illuminate\\\\Routing\\\\Router->runRouteWithinStack()\r\n#40 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(636): Illuminate\\\\Routing\\\\Router->runRoute()\r\n#41 ./vendor/laravel/framework/src/Illuminate/Routing/Router.php(625): Illuminate\\\\Routing\\\\Router->dispatchToRoute()\r\n#42 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(166): Illuminate\\\\Routing\\\\Router->dispatch()\r\n#43 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\\\Foundation\\\\Http\\\\Kernel->Illuminate\\\\Foundation\\\\Http\\\\{closure}()\r\n#44 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#45 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\TransformsRequest->handle()\r\n#46 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#47 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\TransformsRequest->handle()\r\n#48 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#49 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\ValidatePostSize->handle()\r\n#50 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#51 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\\\Foundation\\\\Http\\\\Middleware\\\\PreventRequestsDuringMaintenance->handle()\r\n#52 ./vendor/fruitcake/laravel-cors/src/HandleCors.php(57): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#53 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\\\\Cors\\\\HandleCors->handle()\r\n#54 ./vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#55 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\\\\Proxy\\\\TrustProxies->handle()\r\n#56 ./vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}()\r\n#57 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(141): Illuminate\\\\Pipeline\\\\Pipeline->then()\r\n#58 ./vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(110): Illuminate\\\\Foundation\\\\Http\\\\Kernel->sendRequestThroughRouter()\r\n#59 ./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(508): Illuminate\\\\Foundation\\\\Http\\\\Kernel->handle()\r\n#60 ./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(474): Illuminate\\\\Foundation\\\\Testing\\\\TestCase->call()\r\n#61 ./vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php(333): Illuminate\\\\Foundation\\\\Testing\\\\TestCase->json()\r\n#62 ./tests/Feature/Api/Projects/CreateProjectTest.php(119): Illuminate\\\\Foundation\\\\Testing\\\\TestCase->postJson()\r\n#63 ./vendor/phpunit/phpunit/src/Framework/TestCase.php(1526): Tests\\\\Feature\\\\Api\\\\Projects\\\\CreateProjectTest->cannot_create_project_without_name()\r\n#64 ./vendor/phpunit/phpunit/src/Framework/TestCase.php(1132): PHPUnit\\\\Framework\\\\TestCase->runTest()\r\n#65 ./vendor/phpunit/phpunit/src/Framework/TestResult.php(722): PHPUnit\\\\Framework\\\\TestCase->runBare()\r\n#66 ./vendor/phpunit/phpunit/src/Framework/TestCase.php(884): PHPUnit\\\\Framework\\\\TestResult->run()\r\n#67 ./vendor/phpunit/phpunit/src/Framework/TestSuite.php(677): PHPUnit\\\\Framework\\\\TestCase->run()\r\n#68 ./vendor/phpunit/phpunit/src/Framework/TestSuite.php(677): PHPUnit\\\\Framework\\\\TestSuite->run()\r\n#69 ./vendor/phpunit/phpunit/src/Framework/TestSuite.php(677): PHPUnit\\\\Framework\\\\TestSuite->run()\r\n#70 ./vendor/phpunit/phpunit/src/TextUI/TestRunner.php(667): PHPUnit\\\\Framework\\\\TestSuite->run()\r\n#71 ./vendor/phpunit/phpunit/src/TextUI/Command.php(142): PHPUnit\\\\TextUI\\\\TestRunner->run()\r\n#72 ./vendor/phpunit/phpunit/src/TextUI/Command.php(95): PHPUnit\\\\TextUI\\\\Command->run()\r\n#73 ./vendor/phpunit/phpunit/phpunit(61): PHPUnit\\\\TextUI\\\\Command::main()\r\n#74 {main}\r\n\"} \r\n```", "number": 36622, "review_comments": [], "title": "[8.x] Fix replacing required :input with null on PHP 8.1" }
{ "commits": [ { "message": "Fix replacing required :input with null on PHP 8.1\n\nFixes an issue where data lacking one or more of the fields under\nvalidation will cause tests to fail with an `ErrorException`.\n\nThat exception is a PHP deprecation warning triggered by the call to\n`str_replace()` inside `replaceInputPlaceholder()`, which assumes the\nvalue returned from `getDisplayableValue()` will always be a string." } ], "files": [ { "diff": "@@ -336,7 +336,7 @@ public function getDisplayableValue($attribute, $value)\n return $value ? 'true' : 'false';\n }\n \n- return $value;\n+ return (string) $value;\n }\n \n /**", "filename": "src/Illuminate/Validation/Concerns/FormatsMessages.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.31.0\r\n- PHP Version: 7.4.16\r\n- Database Driver & Version: MySQL 5.7\r\n\r\n### Description:\r\nWhen defining a new schedule command, the `between` method doesn't appear to be applying to the cron expression.\r\n\r\n```php\r\n// app/Console/Kernel\r\n\r\nprotected function schedule(Schedule $schedule)\r\n {\r\n $schedule->command('foo')\r\n ->hourly()\r\n ->between('4:00', '5:00');\r\n }\r\n```\r\nRunning `php artisan schedule:list` shows the wrong intervals and next due to be after `5:00`\r\n\r\n![image](https://user-images.githubusercontent.com/8125119/110958434-4ed27f00-8312-11eb-8729-ccd679b19be5.png)\r\n\r\n\r\n### Steps To Reproduce:\r\n1. Add the above task to `app/Console/Kernel.php@schedule` \r\n2. Open terminal and run `php artisan schedule:list`\r\n3. Should see Interval set to `0 * * * *` and Next Run will be set to time after end time ", "comments": [ { "body": "Yeah I see the same. But this is more of a feature request than a bug. We'd appreciate a PR if anyone can help us out with this one. Thanks", "created_at": "2021-03-15T11:19:47Z" }, { "body": "@driesvints Thank you for looking at this.\r\n\r\nCan I ask why this is a feature request and not a bug? \r\n\r\nThe documentation says that using `schedule:list` will show you when the task is scheduled to run again, but it's clearly not doing that for schedules using the `between` method.", "created_at": "2021-03-15T20:31:09Z" }, { "body": "Okay, I'll re-open this. Appreciating a PR regardlessly. ", "created_at": "2021-03-15T20:59:33Z" }, { "body": "I'll take a crack at it", "created_at": "2021-03-15T21:19:06Z" }, { "body": "Looking at the code it is because the `between` method really just registers a `when` callback that is evaluated at runtime. The cron expression itself is not modified. So, the definition will still be respected and the command will only run at the specified times - but just the `schedule:list` doesn't reflect that.", "created_at": "2021-03-16T14:18:21Z" }, { "body": "@taylorotwell I see. I have a PR coming soon that I think will fix the issue with `schedule:list`, but I am not sure if the implementation is correct.", "created_at": "2021-03-16T14:23:10Z" }, { "body": "After many attempts to fix this for all scenarios (I could think of), I am throwing in the towel.\r\n\r\nI am going to close this out as it seems like many people are not concerned about it.\r\n\r\nThanks for your time and for the great framework!", "created_at": "2021-03-19T19:19:44Z" } ], "number": 36581, "title": "[8.x] Between method doesn't change cron expression in Scheduler" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\nThis PR resolves #36581 \r\nCurrently, when you use `between` or `unlessBetween` in a schedule task, the resulting cron expression and next due date is not effected in the output of `schedule:list`. The scheduler itself still only runs during the specified times, it is just not reflected in the output of `schedule:list`\r\n\r\n```php\r\npublic function between($startTime, $endTime)\r\n {\r\n $startingHour = Carbon::parse($startTime, $this->timezone)->format('G');\r\n $endingHour = Carbon::parse($endTime, $this->timezone)->format('G');\r\n\r\n return $this->when($this->inTimeInterval($startTime, $endTime))\r\n ->spliceIntoPosition(2, $startingHour . '-' . $endingHour);\r\n }\r\n```\r\n\r\n```php\r\npublic function unlessBetween($startTime, $endTime)\r\n {\r\n $startingHour = Carbon::parse($startTime, $this->timezone)->format('G');\r\n $endingHour = Carbon::parse($endTime, $this->timezone)->format('G');\r\n\r\n $firstInterval = $startingHour == \"0\" ? $startingHour : \"0-$startingHour\";\r\n $secondInterval = $endingHour == \"23\" ? $endingHour : \"$endingHour-23\";\r\n\r\n return $this->skip($this->inTimeInterval($startTime, $endTime))\r\n ->spliceIntoPosition(2, $firstInterval . ',' . $secondInterval);\r\n }\r\n```\r\n\r\nTo test: \r\n1. Go to `app/Console/Kernel` and add a new command that is scheduled to run between X and Y. \r\n2. Then run `php artisan schedule:list`\r\n\r\nYou should see the cron expression at position 2 change to `X-Y` and if the time is between those time then Next Due Date should reflect that. If the time falls outside of the times, then Next Due Date should be the next day at the start time(X).\r\n\r\nThis is my first PR into Laravel and I am looking for any and all input on this one. Thanks!", "number": 36616, "review_comments": [], "title": "[8.x] Adding methods to modify cron expression in between and unlessBetween" }
{ "commits": [ { "message": "Adding methods to modify cron expression in between and unlessBetween methods" } ], "files": [ { "diff": "@@ -28,7 +28,11 @@ public function cron($expression)\n */\n public function between($startTime, $endTime)\n {\n- return $this->when($this->inTimeInterval($startTime, $endTime));\n+ $startingHour = Carbon::parse($startTime, $this->timezone)->format('G');\n+ $endingHour = Carbon::parse($endTime, $this->timezone)->format('G');\n+\n+ return $this->when($this->inTimeInterval($startTime, $endTime))\n+ ->spliceIntoPosition(2, $startingHour . '-' . $endingHour);\n }\n \n /**\n@@ -40,9 +44,17 @@ public function between($startTime, $endTime)\n */\n public function unlessBetween($startTime, $endTime)\n {\n- return $this->skip($this->inTimeInterval($startTime, $endTime));\n+ $startingHour = Carbon::parse($startTime, $this->timezone)->format('G');\n+ $endingHour = Carbon::parse($endTime, $this->timezone)->format('G');\n+\n+ $firstInterval = $startingHour == \"0\" ? $startingHour : \"0-$startingHour\";\n+ $secondInterval = $endingHour == \"23\" ? $endingHour : \"$endingHour-23\";\n+\n+ return $this->skip($this->inTimeInterval($startTime, $endTime))\n+ ->spliceIntoPosition(2, $firstInterval . ',' . $secondInterval);\n }\n \n+\n /**\n * Schedule the event to run between start and end time.\n *", "filename": "src/Illuminate/Console/Scheduling/ManagesFrequencies.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": "On Google Cloud SQL instances it may happen that the connection to the DB is lost with horizon.\r\n\r\nThis occasionally happens when there are no jobs for a few hours but the connection is still alive.\r\n\r\n<details><summary>Log</summary>\r\n<p>\r\n\r\n```\r\nErrorException: PDO::prepare(): SSL: Broken pipe\r\n#40 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(338): Illuminate\\Foundation\\Bootstrap\\HandleExceptions::handleError\r\n#39 [internal](0): PDO::prepare\r\n#38 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(338): Illuminate\\Database\\Connection::Illuminate\\Database\\{closure}\r\n#37 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(671): Illuminate\\Database\\Connection::runQueryCallback\r\n#36 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(638): Illuminate\\Database\\Connection::run\r\n#35 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(346): Illuminate\\Database\\Connection::select\r\n#34 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2313): Illuminate\\Database\\Query\\Builder::runSelect\r\n#33 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2301): Illuminate\\Database\\Query\\Builder::Illuminate\\Database\\Query\\{closure}\r\n#32 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2796): Illuminate\\Database\\Query\\Builder::onceWithColumns\r\n#31 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2302): Illuminate\\Database\\Query\\Builder::get\r\n#30 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(588): Illuminate\\Database\\Eloquent\\Builder::getModels\r\n#29 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(572): Illuminate\\Database\\Eloquent\\Builder::get\r\n#28 /vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php(170): Illuminate\\Database\\Eloquent\\Builder::first\r\n#27 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(499): Illuminate\\Database\\Eloquent\\Builder::firstOrFail\r\n#26 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(102): App\\Events\\Updated::restoreModel\r\n#25 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(57): App\\Events\\Updated::getRestoredPropertyValue\r\n#24 /vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(122): App\\Events\\Updated::__unserialize\r\n#23 [internal](0): unserialize\r\n#22 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(95): Illuminate\\Queue\\CallQueuedHandler::getCommand\r\n#21 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(60): Illuminate\\Queue\\CallQueuedHandler::call\r\n#20 /vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\\Queue\\Jobs\\Job::fire\r\n#19 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(406): Illuminate\\Queue\\Worker::process\r\n#18 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(356): Illuminate\\Queue\\Worker::runJob\r\n#17 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(158): Illuminate\\Queue\\Worker::daemon\r\n#16 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(116): Illuminate\\Queue\\Console\\WorkCommand::runWorker\r\n#15 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(100): Illuminate\\Queue\\Console\\WorkCommand::handle\r\n#14 /vendor/laravel/horizon/src/Console/WorkCommand.php(50): Laravel\\Horizon\\Console\\WorkCommand::handle\r\n#13 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}\r\n#12 /vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\\Container\\Util::unwrapIfClosure\r\n#11 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\BoundMethod::callBoundMethod\r\n#10 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::call\r\n#9 /vendor/laravel/framework/src/Illuminate/Container/Container.php(610): Illuminate\\Container\\Container::call\r\n#8 /vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Console\\Command::execute\r\n#7 /vendor/symfony/console/Command/Command.php(256): Symfony\\Component\\Console\\Command\\Command::run\r\n#6 /vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Illuminate\\Console\\Command::run\r\n#5 /vendor/symfony/console/Application.php(971): Symfony\\Component\\Console\\Application::doRunCommand\r\n#4 /vendor/symfony/console/Application.php(290): Symfony\\Component\\Console\\Application::doRun\r\n#3 /vendor/symfony/console/Application.php(166): Symfony\\Component\\Console\\Application::run\r\n#2 /vendor/laravel/framework/src/Illuminate/Console/Application.php(92): Illuminate\\Console\\Application::run\r\n#1 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Foundation\\Console\\Kernel::handle\r\n#0 /artisan(37): null\r\n\r\nIlluminate\\Database\\QueryException: PDO::prepare(): SSL: Broken pipe (SQL: select * from ?????????? limit 1)\r\n#37 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(678): Illuminate\\Database\\Connection::runQueryCallback\r\n#36 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(638): Illuminate\\Database\\Connection::run\r\n#35 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(346): Illuminate\\Database\\Connection::select\r\n#34 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2313): Illuminate\\Database\\Query\\Builder::runSelect\r\n#33 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2301): Illuminate\\Database\\Query\\Builder::Illuminate\\Database\\Query\\{closure}\r\n#32 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2796): Illuminate\\Database\\Query\\Builder::onceWithColumns\r\n#31 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2302): Illuminate\\Database\\Query\\Builder::get\r\n#30 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(588): Illuminate\\Database\\Eloquent\\Builder::getModels\r\n#29 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(572): Illuminate\\Database\\Eloquent\\Builder::get\r\n#28 /vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php(170): Illuminate\\Database\\Eloquent\\Builder::first\r\n#27 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(499): Illuminate\\Database\\Eloquent\\Builder::firstOrFail\r\n#26 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(102): App\\Events\\Updated::restoreModel\r\n#25 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(57): App\\Events\\Updated::getRestoredPropertyValue\r\n#24 /vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(122): App\\Events\\Updated::__unserialize\r\n#23 [internal](0): unserialize\r\n#22 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(95): Illuminate\\Queue\\CallQueuedHandler::getCommand\r\n#21 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(60): Illuminate\\Queue\\CallQueuedHandler::call\r\n#20 /vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\\Queue\\Jobs\\Job::fire\r\n#19 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(406): Illuminate\\Queue\\Worker::process\r\n#18 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(356): Illuminate\\Queue\\Worker::runJob\r\n#17 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(158): Illuminate\\Queue\\Worker::daemon\r\n#16 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(116): Illuminate\\Queue\\Console\\WorkCommand::runWorker\r\n#15 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(100): Illuminate\\Queue\\Console\\WorkCommand::handle\r\n#14 /vendor/laravel/horizon/src/Console/WorkCommand.php(50): Laravel\\Horizon\\Console\\WorkCommand::handle\r\n#13 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}\r\n#12 /vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\\Container\\Util::unwrapIfClosure\r\n#11 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\BoundMethod::callBoundMethod\r\n#10 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::call\r\n#9 /vendor/laravel/framework/src/Illuminate/Container/Container.php(610): Illuminate\\Container\\Container::call\r\n#8 /vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Console\\Command::execute\r\n#7 /vendor/symfony/console/Command/Command.php(256): Symfony\\Component\\Console\\Command\\Command::run\r\n#6 /vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Illuminate\\Console\\Command::run\r\n#5 /vendor/symfony/console/Application.php(971): Symfony\\Component\\Console\\Application::doRunCommand\r\n#4 /vendor/symfony/console/Application.php(290): Symfony\\Component\\Console\\Application::doRun\r\n#3 /vendor/symfony/console/Application.php(166): Symfony\\Component\\Console\\Application::run\r\n#2 /vendor/laravel/framework/src/Illuminate/Console/Application.php(92): Illuminate\\Console\\Application::run\r\n#1 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Foundation\\Console\\Kernel::handle\r\n#0 /artisan(37): null\r\n```\r\n\r\n</p>\r\n</details>", "number": 36601, "review_comments": [], "title": "[6.x] Add broken pipe exception as lost connection error" }
{ "commits": [ { "message": "Add ssl broken pipe as lost connection error" } ], "files": [ { "diff": "@@ -50,6 +50,7 @@ protected function causedByLostConnection(Throwable $e)\n 'SSL: Connection timed out',\n 'SQLSTATE[HY000]: General error: 1105 The last transaction was aborted due to Seamless Scaling. Please retry.',\n 'Temporary failure in name resolution',\n+ 'SSL: Broken pipe',\n ]);\n }\n }", "filename": "src/Illuminate/Database/DetectsLostConnections.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 Google Cloud SQL instances it may happen that the connection to the DB is lost with horizon.\r\n\r\nThis occasionally happens when there are no jobs for a few hours but the connection is still alive.\r\n\r\n<details><summary>Log</summary>\r\n<p>\r\n\r\n```\r\nErrorException: PDO::prepare(): SSL: Broken pipe\r\n#40 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(338): Illuminate\\Foundation\\Bootstrap\\HandleExceptions::handleError\r\n#39 [internal](0): PDO::prepare\r\n#38 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(338): Illuminate\\Database\\Connection::Illuminate\\Database\\{closure}\r\n#37 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(671): Illuminate\\Database\\Connection::runQueryCallback\r\n#36 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(638): Illuminate\\Database\\Connection::run\r\n#35 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(346): Illuminate\\Database\\Connection::select\r\n#34 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2313): Illuminate\\Database\\Query\\Builder::runSelect\r\n#33 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2301): Illuminate\\Database\\Query\\Builder::Illuminate\\Database\\Query\\{closure}\r\n#32 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2796): Illuminate\\Database\\Query\\Builder::onceWithColumns\r\n#31 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2302): Illuminate\\Database\\Query\\Builder::get\r\n#30 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(588): Illuminate\\Database\\Eloquent\\Builder::getModels\r\n#29 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(572): Illuminate\\Database\\Eloquent\\Builder::get\r\n#28 /vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php(170): Illuminate\\Database\\Eloquent\\Builder::first\r\n#27 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(499): Illuminate\\Database\\Eloquent\\Builder::firstOrFail\r\n#26 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(102): App\\Events\\Updated::restoreModel\r\n#25 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(57): App\\Events\\Updated::getRestoredPropertyValue\r\n#24 /vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(122): App\\Events\\Updated::__unserialize\r\n#23 [internal](0): unserialize\r\n#22 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(95): Illuminate\\Queue\\CallQueuedHandler::getCommand\r\n#21 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(60): Illuminate\\Queue\\CallQueuedHandler::call\r\n#20 /vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\\Queue\\Jobs\\Job::fire\r\n#19 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(406): Illuminate\\Queue\\Worker::process\r\n#18 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(356): Illuminate\\Queue\\Worker::runJob\r\n#17 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(158): Illuminate\\Queue\\Worker::daemon\r\n#16 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(116): Illuminate\\Queue\\Console\\WorkCommand::runWorker\r\n#15 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(100): Illuminate\\Queue\\Console\\WorkCommand::handle\r\n#14 /vendor/laravel/horizon/src/Console/WorkCommand.php(50): Laravel\\Horizon\\Console\\WorkCommand::handle\r\n#13 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}\r\n#12 /vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\\Container\\Util::unwrapIfClosure\r\n#11 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\BoundMethod::callBoundMethod\r\n#10 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::call\r\n#9 /vendor/laravel/framework/src/Illuminate/Container/Container.php(610): Illuminate\\Container\\Container::call\r\n#8 /vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Console\\Command::execute\r\n#7 /vendor/symfony/console/Command/Command.php(256): Symfony\\Component\\Console\\Command\\Command::run\r\n#6 /vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Illuminate\\Console\\Command::run\r\n#5 /vendor/symfony/console/Application.php(971): Symfony\\Component\\Console\\Application::doRunCommand\r\n#4 /vendor/symfony/console/Application.php(290): Symfony\\Component\\Console\\Application::doRun\r\n#3 /vendor/symfony/console/Application.php(166): Symfony\\Component\\Console\\Application::run\r\n#2 /vendor/laravel/framework/src/Illuminate/Console/Application.php(92): Illuminate\\Console\\Application::run\r\n#1 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Foundation\\Console\\Kernel::handle\r\n#0 /artisan(37): null\r\n\r\nIlluminate\\Database\\QueryException: PDO::prepare(): SSL: Broken pipe (SQL: select * from ?????????? limit 1)\r\n#37 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(678): Illuminate\\Database\\Connection::runQueryCallback\r\n#36 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(638): Illuminate\\Database\\Connection::run\r\n#35 /vendor/laravel/framework/src/Illuminate/Database/Connection.php(346): Illuminate\\Database\\Connection::select\r\n#34 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2313): Illuminate\\Database\\Query\\Builder::runSelect\r\n#33 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2301): Illuminate\\Database\\Query\\Builder::Illuminate\\Database\\Query\\{closure}\r\n#32 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2796): Illuminate\\Database\\Query\\Builder::onceWithColumns\r\n#31 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2302): Illuminate\\Database\\Query\\Builder::get\r\n#30 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(588): Illuminate\\Database\\Eloquent\\Builder::getModels\r\n#29 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(572): Illuminate\\Database\\Eloquent\\Builder::get\r\n#28 /vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php(170): Illuminate\\Database\\Eloquent\\Builder::first\r\n#27 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(499): Illuminate\\Database\\Eloquent\\Builder::firstOrFail\r\n#26 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(102): App\\Events\\Updated::restoreModel\r\n#25 /vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(57): App\\Events\\Updated::getRestoredPropertyValue\r\n#24 /vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(122): App\\Events\\Updated::__unserialize\r\n#23 [internal](0): unserialize\r\n#22 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(95): Illuminate\\Queue\\CallQueuedHandler::getCommand\r\n#21 /vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(60): Illuminate\\Queue\\CallQueuedHandler::call\r\n#20 /vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\\Queue\\Jobs\\Job::fire\r\n#19 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(406): Illuminate\\Queue\\Worker::process\r\n#18 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(356): Illuminate\\Queue\\Worker::runJob\r\n#17 /vendor/laravel/framework/src/Illuminate/Queue/Worker.php(158): Illuminate\\Queue\\Worker::daemon\r\n#16 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(116): Illuminate\\Queue\\Console\\WorkCommand::runWorker\r\n#15 /vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(100): Illuminate\\Queue\\Console\\WorkCommand::handle\r\n#14 /vendor/laravel/horizon/src/Console/WorkCommand.php(50): Laravel\\Horizon\\Console\\WorkCommand::handle\r\n#13 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(36): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}\r\n#12 /vendor/laravel/framework/src/Illuminate/Container/Util.php(40): Illuminate\\Container\\Util::unwrapIfClosure\r\n#11 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(93): Illuminate\\Container\\BoundMethod::callBoundMethod\r\n#10 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(37): Illuminate\\Container\\BoundMethod::call\r\n#9 /vendor/laravel/framework/src/Illuminate/Container/Container.php(610): Illuminate\\Container\\Container::call\r\n#8 /vendor/laravel/framework/src/Illuminate/Console/Command.php(136): Illuminate\\Console\\Command::execute\r\n#7 /vendor/symfony/console/Command/Command.php(256): Symfony\\Component\\Console\\Command\\Command::run\r\n#6 /vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Illuminate\\Console\\Command::run\r\n#5 /vendor/symfony/console/Application.php(971): Symfony\\Component\\Console\\Application::doRunCommand\r\n#4 /vendor/symfony/console/Application.php(290): Symfony\\Component\\Console\\Application::doRun\r\n#3 /vendor/symfony/console/Application.php(166): Symfony\\Component\\Console\\Application::run\r\n#2 /vendor/laravel/framework/src/Illuminate/Console/Application.php(92): Illuminate\\Console\\Application::run\r\n#1 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\\Foundation\\Console\\Kernel::handle\r\n#0 /artisan(37): null\r\n```\r\n\r\n</p>\r\n</details>", "number": 36601, "review_comments": [], "title": "[6.x] Add broken pipe exception as lost connection error" }
{ "commits": [ { "message": "Add ssl broken pipe as lost connection error" } ], "files": [ { "diff": "@@ -50,6 +50,7 @@ protected function causedByLostConnection(Throwable $e)\n 'SSL: Connection timed out',\n 'SQLSTATE[HY000]: General error: 1105 The last transaction was aborted due to Seamless Scaling. Please retry.',\n 'Temporary failure in name resolution',\n+ 'SSL: Broken pipe',\n ]);\n }\n }", "filename": "src/Illuminate/Database/DetectsLostConnections.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.28.1\r\n- PHP Version: 8.0.2\r\n- Database Driver & Version: phpredis 5.3.3\r\n\r\n### Description:\r\n\r\nThe eval call is missing proper argument serialization and compression if php-redis extension is configured to do so.\r\n\r\nhttps://github.com/laravel/framework/blob/8.x/src/Illuminate/Cache/RedisLock.php#L51\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\nInstall igbinary, install phpredis, configure laravel to use redis as cache driver. Use the lock functionality as described here: https://laravel.com/docs/8.x/cache#atomic-locks\r\n\r\n\r\nIn the following section you can see the code example, the console and the redis monitor output.\r\n\r\n#### No serializer enabled\r\n\r\n![lock_serializer_none_code](https://user-images.githubusercontent.com/7612582/108636991-01888d80-7489-11eb-994d-03127cdb8f42.png)\r\n\r\n![lock_serializer_none_output](https://user-images.githubusercontent.com/7612582/108636996-08170500-7489-11eb-80e4-8b69246672d8.png)\r\n\r\n![lock_serializer_none_monitor](https://user-images.githubusercontent.com/7612582/108636998-0c432280-7489-11eb-9ba7-03ea65e1c6fe.png)\r\n\r\n#### Igbinary serializer enabled\r\n\r\n![lock_serializer_igbinary_code](https://user-images.githubusercontent.com/7612582/108637008-16fdb780-7489-11eb-9d56-a01518970450.png)\r\n\r\n![lock_serializer_igbinary_output](https://user-images.githubusercontent.com/7612582/108637015-1bc26b80-7489-11eb-8846-3e6c0b362b21.png)\r\n\r\n![lock_serializer_igbinary_monitor](https://user-images.githubusercontent.com/7612582/108637031-21b84c80-7489-11eb-8169-9e3520771e14.png)\r\n\r\nAs you can see in the second example the final lock release is not happening and the lock stays in redis until it times out or if no timeout set, will stay there forever. The reason for this is that the phpredis extension can not know which arguments are keys and which are values that need to be serialized and thus the responsibility to do so is in the hands of the extension user to serialize the values in the same way as the extension is currently configured. I have fixed another lock library already, but unfortunately I am not aware how to contribute in the laravel framework.\r\n\r\nThe solution would be in https://github.com/laravel/framework/blob/8.x/src/Illuminate/Cache/RedisLock.php#L51\r\n\r\n```php\r\n/**\r\n * Release the lock.\r\n *\r\n * @return bool\r\n */\r\npublic function release()\r\n{\r\n /* If a serialization mode such as \"php\" or \"igbinary\" is enabled, the arguments must be\r\n * serialized by us, because phpredis does not do this for the eval command.\r\n *\r\n * The keys must not be serialized.\r\n */\r\n $owner = $this->owner;\r\n $client = $this->redis->client();\r\n $clientClass = get_class($client);\r\n if ($clientClass === 'Redis' || $clientClass === 'RedisCluster') {\r\n $owner = $client->_serialize($owner);\r\n }\r\n\r\n return (bool) $this->redis->eval(LuaScripts::releaseLock(), 1, $this->name, $owner);\r\n}\r\n```\r\n\r\nI have tested this code and it works.\r\n\r\n**IMPORTANT**\r\n\r\nA similar change needs to be done for the compression options. There, we have no access to an internal function like with the serializer (`_serialize($x)`), but rather have to check the options that are set (`$redis->getOption(Redis::OPT_COMPRESSION);`).\r\n\r\nThis fix would be also a pre condition to introduce those phpredis options to the general redis config.", "comments": [ { "body": "Thanks. I don't have experience with Redis clusters myself but your fix seems straight forward to me. Can you send in a PR for that?", "created_at": "2021-02-22T15:41:59Z" }, { "body": "Sure, will prepare a pull request these days.", "created_at": "2021-02-23T22:04:23Z" }, { "body": "> Thanks. I don't have experience with Redis clusters myself but your fix seems straight forward to me. Can you send in a PR for that?\r\n\r\nPull reques submitted (https://github.com/laravel/framework/pull/36412). As a result I also submitted two phpredis issues where one needs investigation/fix (https://github.com/phpredis/phpredis/issues/1939) and one would be a good to have (https://github.com/phpredis/phpredis/issues/1938).", "created_at": "2021-02-27T16:17:49Z" }, { "body": "Thanks @TheLevti!", "created_at": "2021-03-01T09:27:34Z" } ], "number": 36337, "title": "Redis & RedisCluster eval with serializer & compression" }
{ "body": "laravel/framework#36337: Respect serialization and compression settings of the phpredis extension when using it for locking via the cache service.\r\n\r\n- Support phpredis serialization when locking (none, php, json, igbinary, msgpack).\r\n- Support phpredis compression when locking (none, lzf, zstd, lz4).\r\n\r\nThis is a bug that will cause locking to not release the lock if the redis connection is configured to use serialization and/or compression of data. LZ4 code support was added, but is not working yet as phpredis implemented it not consistent to the lz4 php extension. Waiting for this issue on phpredis to be resolved: https://github.com/phpredis/phpredis/issues/1939. All other compression options resolve this bug.\r\n\r\nAlso once the phpredis issue https://github.com/phpredis/phpredis/issues/1938 is resolved, we might have a consistent way to call the same compression logic that the extension is using without the need to check for each implementation.\r\n\r\nTested locally with all extensions enabled/configured (lzf, zstd, lz4, igbinary, msgpack).\r\n\r\nSolves #36337 ", "number": 36412, "review_comments": [ { "body": "This `release()` method can be kept simple by moving the \"phpredis\" extension-specific code into another method:\r\n\r\n```php\r\npublic function release()\r\n{\r\n return (bool) $this->redis->eval(LuaScripts::releaseLock(), 1, $this->name, $this->phpRedisOwner() ?? $owner);\r\n}\r\n\r\nprotected function phpRedisOwner()\r\n{\r\n if (! $this->isPhpRedisCompressionEnabled()) {\r\n return;\r\n }\r\n\r\n $owner = $this->redis->client()->_serialize($this->owner);\r\n\r\n // etc.\r\n}\r\n```\r\n\r\nHere's a Gist with an updated `RedisLock.php` class: https://gist.github.com/derekmd/039d1b7b83326fc69790552fb30c9cc8 Then a 220 line class is shortened to 181 lines.\r\n\r\nAnother option is to move these additions into a completely new class with a constructor that accepts dependencies `$this->owner` and `$this->redis->client()`.", "created_at": "2021-02-27T23:49:15Z" }, { "body": "Can the calls to `constant()` be avoided since you don't need to worry about classes `\\Redis` and `\\RedisCluster` not existing? Updating `isPhpRedis()` to use `instanceof`:\r\n\r\n```php\r\nuse Redis;\r\nuse RedisCluster;\r\n\r\n// ...\r\n\r\nprotected function isPhpRedis()\r\n{\r\n $client = $this->redis->client();\r\n\r\n return $client instanceof Redis || $client instanceof RedisCluster;\r\n}\r\n```\r\n\r\nThis short-circuits the other `is*()` methods from being called. The `instanceof` keyword can accept any symbol, even for classes that don't exist. e.g., `$client instanceof ThisClassDoesNotExist` won't throw an exception - it just returns `false`.\r\n\r\nThen the other predicate methods can be simplified to a single expression. e.g.,\r\n\r\n```php\r\nprotected function isPhpRedisLz4Enabled()\r\n{\r\n return defined('Redis::COMPRESSION_LZ4') &&\r\n $this->redis->client()->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_LZ4;\r\n}\r\n```", "created_at": "2021-02-27T23:50:26Z" }, { "body": "Sure, I was just not sure how static analyzers will react if classes/constants do not exist as they are added bases on compile config on phpredis", "created_at": "2021-02-28T08:27:52Z" }, { "body": "I have moved this whole code into a different class.", "created_at": "2021-02-28T11:20:21Z" }, { "body": "Also I added a new test class for this new one. Seems to be a lot cleaner now as this code is very specific to the extension and should not be mixed with the general redis code.", "created_at": "2021-02-28T11:22:09Z" }, { "body": "@TheLevti - So adding this call will not break any existing locks that were created before this change? I could imagine a scenario where locks exist - application is deployed with this changed - will those locks still be able to be regathered and released?", "created_at": "2021-03-03T22:42:01Z" }, { "body": "Yes, existing locks will work on deployment (if the lock owner is restored of course). If phpredis has serialization disabled, this will return the same value as passed down (See: https://github.com/phpredis/phpredis/blob/develop/library.c#L3029). I wrote a test for this case, which passes. (See: https://github.com/laravel/framework/pull/36412/files#diff-07d7fee8b1e505b0e2816e7b5dd26b90abc81614820689b5a070912f495c8279R31)", "created_at": "2021-03-04T20:32:26Z" }, { "body": "Nothing changes in regards of the redlock algorithm. The way the lock is created has not changed here. The same eval call is done with the same lua script executed on release as before. This change is all about modifying the passed arguments to the eval call when releasing the lock.", "created_at": "2021-03-04T20:34:22Z" } ], "title": "[8.x] phpredis lock serialization and compression support" }
{ "commits": [ { "message": "laravel/framework#36337: Respect serialization and compression of phpredis during locking\n\n- Support phpredis serialization when locking (none, php, json, igbinary, msgpack).\n- Support phpredis compression when locking (none, lzf, zstd, lz4)." } ], "files": [ { "diff": "@@ -0,0 +1,89 @@\n+<?php\n+\n+namespace Illuminate\\Cache;\n+\n+use Illuminate\\Redis\\Connections\\PhpRedisConnection;\n+use Redis;\n+use UnexpectedValueException;\n+\n+class PhpRedisLock extends RedisLock\n+{\n+ public function __construct(PhpRedisConnection $redis, string $name, int $seconds, ?string $owner = null)\n+ {\n+ parent::__construct($redis, $name, $seconds, $owner);\n+ }\n+\n+ /**\n+ * {@inheritDoc}\n+ */\n+ public function release()\n+ {\n+ return (bool) $this->redis->eval(\n+ LuaScripts::releaseLock(),\n+ 1,\n+ $this->name,\n+ $this->serializedAndCompressedOwner()\n+ );\n+ }\n+\n+ protected function serializedAndCompressedOwner(): string\n+ {\n+ $client = $this->redis->client();\n+\n+ /* If a serialization mode such as \"php\" or \"igbinary\" and/or a\n+ * compression mode such as \"lzf\" or \"zstd\" is enabled, the owner\n+ * must be serialized and/or compressed by us, because phpredis does\n+ * not do this for the eval command.\n+ *\n+ * Name must not be modified!\n+ */\n+ $owner = $client->_serialize($this->owner);\n+\n+ /* Once the phpredis extension exposes a compress function like the\n+ * above `_serialize()` function, we should switch to it to guarantee\n+ * consistency in the way the extension serializes and compresses to\n+ * avoid the need to check each compression option ourselves.\n+ *\n+ * @see https://github.com/phpredis/phpredis/issues/1938\n+ */\n+ if ($this->compressed()) {\n+ if ($this->lzfCompressed()) {\n+ $owner = \\lzf_compress($owner);\n+ } elseif ($this->zstdCompressed()) {\n+ $owner = \\zstd_compress($owner, $client->getOption(Redis::OPT_COMPRESSION_LEVEL));\n+ } elseif ($this->lz4Compressed()) {\n+ $owner = \\lz4_compress($owner, $client->getOption(Redis::OPT_COMPRESSION_LEVEL));\n+ } else {\n+ throw new UnexpectedValueException(sprintf(\n+ 'Unknown phpredis compression in use (%d). Unable to release lock.',\n+ $client->getOption(Redis::OPT_COMPRESSION)\n+ ));\n+ }\n+ }\n+\n+ return $owner;\n+ }\n+\n+ protected function compressed(): bool\n+ {\n+ return $this->redis->client()->getOption(Redis::OPT_COMPRESSION) !== Redis::COMPRESSION_NONE;\n+ }\n+\n+ protected function lzfCompressed(): bool\n+ {\n+ return defined('Redis::COMPRESSION_LZF') &&\n+ $this->redis->client()->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_LZF;\n+ }\n+\n+ protected function zstdCompressed(): bool\n+ {\n+ return defined('Redis::COMPRESSION_ZSTD') &&\n+ $this->redis->client()->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_ZSTD;\n+ }\n+\n+ protected function lz4Compressed(): bool\n+ {\n+ return defined('Redis::COMPRESSION_LZ4') &&\n+ $this->redis->client()->getOption(Redis::OPT_COMPRESSION) === Redis::COMPRESSION_LZ4;\n+ }\n+}", "filename": "src/Illuminate/Cache/PhpRedisLock.php", "status": "added" }, { "diff": "@@ -4,6 +4,7 @@\n \n use Illuminate\\Contracts\\Cache\\LockProvider;\n use Illuminate\\Contracts\\Redis\\Factory as Redis;\n+use Illuminate\\Redis\\Connections\\PhpRedisConnection;\n \n class RedisStore extends TaggableStore implements LockProvider\n {\n@@ -188,7 +189,14 @@ public function forever($key, $value)\n */\n public function lock($name, $seconds = 0, $owner = null)\n {\n- return new RedisLock($this->lockConnection(), $this->prefix.$name, $seconds, $owner);\n+ $lockName = $this->prefix.$name;\n+ $lockConnection = $this->lockConnection();\n+\n+ if ($lockConnection instanceof PhpRedisConnection) {\n+ return new PhpRedisLock($lockConnection, $lockName, $seconds, $owner);\n+ }\n+\n+ return new RedisLock($lockConnection, $lockName, $seconds, $owner);\n }\n \n /**", "filename": "src/Illuminate/Cache/RedisStore.php", "status": "modified" }, { "diff": "@@ -0,0 +1,306 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Cache;\n+\n+use Illuminate\\Foundation\\Testing\\Concerns\\InteractsWithRedis;\n+use Illuminate\\Support\\Facades\\Cache;\n+use Orchestra\\Testbench\\TestCase;\n+use Redis;\n+\n+/**\n+ * @group integration\n+ */\n+class PhpRedisCacheLockTest extends TestCase\n+{\n+ use InteractsWithRedis;\n+\n+ protected function setUp(): void\n+ {\n+ parent::setUp();\n+\n+ $this->setUpRedis();\n+ }\n+\n+ protected function tearDown(): void\n+ {\n+ parent::tearDown();\n+\n+ $this->tearDownRedis();\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithoutSerializationAndCompression()\n+ {\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithPhpSerialization()\n+ {\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithJsonSerialization()\n+ {\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_JSON);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithIgbinarySerialization()\n+ {\n+ if (! defined('Redis::SERIALIZER_IGBINARY')) {\n+ $this->markTestSkipped('Redis extension is not configured to support the igbinary serializer.');\n+ }\n+\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithMsgpackSerialization()\n+ {\n+ if (! defined('Redis::SERIALIZER_MSGPACK')) {\n+ $this->markTestSkipped('Redis extension is not configured to support the msgpack serializer.');\n+ }\n+\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_MSGPACK);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithLzfCompression()\n+ {\n+ if (! defined('Redis::COMPRESSION_LZF')) {\n+ $this->markTestSkipped('Redis extension is not configured to support the lzf compression.');\n+ }\n+\n+ if (! extension_loaded('lzf')) {\n+ $this->markTestSkipped('Lzf extension is not installed.');\n+ }\n+\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);\n+ $client->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithZstdCompression()\n+ {\n+ if (! defined('Redis::COMPRESSION_ZSTD')) {\n+ $this->markTestSkipped('Redis extension is not configured to support the zstd compression.');\n+ }\n+\n+ if (! extension_loaded('zstd')) {\n+ $this->markTestSkipped('Zstd extension is not installed.');\n+ }\n+\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);\n+ $client->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_ZSTD);\n+ $client->setOption(Redis::OPT_COMPRESSION_LEVEL, Redis::COMPRESSION_ZSTD_DEFAULT);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+\n+ $client->setOption(Redis::OPT_COMPRESSION_LEVEL, Redis::COMPRESSION_ZSTD_MIN);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+\n+ $client->setOption(Redis::OPT_COMPRESSION_LEVEL, Redis::COMPRESSION_ZSTD_MAX);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithLz4Compression()\n+ {\n+ if (! defined('Redis::COMPRESSION_LZ4')) {\n+ $this->markTestSkipped('Redis extension is not configured to support the lz4 compression.');\n+ }\n+\n+ if (! extension_loaded('lz4')) {\n+ $this->markTestSkipped('Lz4 extension is not installed.');\n+ }\n+\n+ $this->markTestIncomplete(\n+ 'phpredis extension does not compress consistently with the php '.\n+ 'extension lz4. See: https://github.com/phpredis/phpredis/issues/1939'\n+ );\n+\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);\n+ $client->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZ4);\n+ $client->setOption(Redis::OPT_COMPRESSION_LEVEL, 1);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+\n+ $client->setOption(Redis::OPT_COMPRESSION_LEVEL, 3);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+\n+ $client->setOption(Redis::OPT_COMPRESSION_LEVEL, 12);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+\n+ public function testRedisLockCanBeAcquiredAndReleasedWithSerializationAndCompression()\n+ {\n+ if (! defined('Redis::COMPRESSION_LZF')) {\n+ $this->markTestSkipped('Redis extension is not configured to support the lzf compression.');\n+ }\n+\n+ if (! extension_loaded('lzf')) {\n+ $this->markTestSkipped('Lzf extension is not installed.');\n+ }\n+\n+ $this->app['config']->set('database.redis.client', 'phpredis');\n+ $this->app['config']->set('cache.stores.redis.connection', 'default');\n+ $this->app['config']->set('cache.stores.redis.lock_connection', 'default');\n+\n+ /** @var \\Illuminate\\Cache\\RedisStore $store */\n+ $store = Cache::store('redis');\n+ /** @var \\Redis $client */\n+ $client = $store->lockConnection()->client();\n+\n+ $client->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);\n+ $client->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF);\n+ $store->lock('foo')->forceRelease();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ $lock = $store->lock('foo', 10);\n+ $this->assertTrue($lock->get());\n+ $this->assertFalse($store->lock('foo', 10)->get());\n+ $lock->release();\n+ $this->assertNull($store->lockConnection()->get($store->getPrefix().'foo'));\n+ }\n+}", "filename": "tests/Integration/Cache/PhpRedisCacheLockTest.php", "status": "added" } ] }
{ "body": "- Laravel Version: 8.20.1\r\n- PHP Version: 8.0.1\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n`@props` removes `disabled` from `$attributes`, but does not set `$disabled` value to true.\r\n\r\n### Steps To Reproduce:\r\n\r\nFile: `resources/views/home.blade.php` \r\n```\r\n<x-form-input type=\"text\" :disabled=\"true\" />\r\n```\r\n\r\nFile: `resources/views/components/form-input.blade.php` \r\n```\r\n<x-input :attributes=\"$attributes\" />\r\n```\r\n\r\nFile: `resources/views/components/input.blade.php`\r\n```\r\n@props(['disabled' => false])\r\n\r\n@php\r\ndd([\r\n 'disabled' => $disabled,\r\n 'attributes' => $attributes,\r\n]);\r\n\r\n$class = 'border-gray-300';\r\n$classDisabled = 'border-gray-300 bg-gray-50 text-gray-500';\r\n\r\nif ($disabled) {\r\n $class = $classDisabled;\r\n}\r\n@endphp\r\n\r\n<input {{ $attributes->merge(['class' => $class]) }} {{ $disabled ? 'disabled' : '' }}/>\r\n```\r\n\r\nOutput:\r\n```\r\narray:2 [▼\r\n \"disabled\" => false\r\n \"attributes\" => Illuminate\\View\\ComponentAttributeBag {#1501 ▼\r\n #attributes: array:1 [▼\r\n \"type\" => \"text\"\r\n ]\r\n }\r\n]\r\n```\r\n\r\n", "comments": [ { "body": "I've been breaking my head over this one for a few but cannot figure it out. Gonna see if @taylorotwell knows what's going on here.", "created_at": "2021-02-12T13:46:02Z" }, { "body": "Fix here: https://github.com/laravel/framework/issues/36236", "created_at": "2021-02-12T14:45:51Z" } ], "number": 36236, "title": "Laravel 8 component @props not setting prop value" }
{ "body": "Fixes #36236 ", "number": 36240, "review_comments": [], "title": "[8.x] Fix attribute nesting on anonymous components" }
{ "commits": [ { "message": "fix attribute nesting" }, { "message": "Apply fixes from StyleCI (#36239)" }, { "message": "add test" }, { "message": "adjust order" } ], "files": [ { "diff": "@@ -50,6 +50,11 @@ public function data()\n {\n $this->attributes = $this->attributes ?: $this->newAttributeBag();\n \n- return $this->data + ['attributes' => $this->attributes];\n+ return array_merge(\n+ optional($this->data['attributes'] ?? null)->getAttributes() ?: [],\n+ $this->attributes->getAttributes(),\n+ $this->data,\n+ ['attributes' => $this->attributes]\n+ );\n }\n }", "filename": "src/Illuminate/View/AnonymousComponent.php", "status": "modified" }, { "diff": "@@ -69,6 +69,13 @@ public function test_appendable_attributes()\n </div>', trim($view));\n }\n \n+ public function tested_nested_anonymous_attribute_proxying_works_correctly()\n+ {\n+ $view = View::make('uses-child-input')->render();\n+\n+ $this->assertSame('<input class=\"disabled-class\" foo=\"bar\" type=\"text\" disabled />', trim($view));\n+ }\n+\n protected function getEnvironmentSetUp($app)\n {\n $app['config']->set('view.paths', [__DIR__.'/templates']);", "filename": "tests/Integration/View/BladeTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,11 @@\n+@props(['disabled' => false])\n+\n+@php\n+if ($disabled) {\n+ $class = 'disabled-class';\n+} else {\n+ $class = 'not-disabled-class';\n+}\n+@endphp\n+\n+<input {{ $attributes->merge(['class' => $class]) }} {{ $disabled ? 'disabled' : '' }} />\n\\ No newline at end of file", "filename": "tests/Integration/View/templates/components/base-input.blade.php", "status": "added" }, { "diff": "@@ -0,0 +1 @@\n+<x-base-input foo=\"bar\" :attributes=\"$attributes\" />\n\\ No newline at end of file", "filename": "tests/Integration/View/templates/components/child-input.blade.php", "status": "added" }, { "diff": "@@ -0,0 +1 @@\n+<x-child-input type=\"text\" :disabled=\"true\" />\n\\ No newline at end of file", "filename": "tests/Integration/View/templates/uses-child-input.blade.php", "status": "added" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.x-dev\r\n- PHP Version: 7.4.8\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\nRight now it appears that using Closure factory states alongside Faker does not work, this is because the Closure is created in another instance of the factory then where it is eventually invoked, so when it is invoked `$this->faker` still references the old instance's faker (which, depending on the situation, may or may not be null). So instead attributes created via faker this way will be null.\r\n\r\n### Steps To Reproduce:\r\n- Create a fresh Laravel 8.x-dev application `composer create-project laravel/laravel:dev-develop`\r\n- Paste the following snippet in the UserFactory:\r\n```\r\n public function foo()\r\n {\r\n return $this->state(fn () => [\r\n 'name' => $this->faker->name,\r\n ]);\r\n }\r\n```\r\n- Open Tinker\r\n- Paste the following line `User::factory()->foo()->make()`\r\n\r\n### Potential fix:\r\nI was able to get it working by adding `$state = $state->bindTo($this);` within the reduce callback in `Factory::getRawAttributes()`, this works because `$this->faker = $this->withFaker()` is called right before the states are resolved, but I don't know what further implications this has.", "comments": [ { "body": "Thanks! We've fixed this.", "created_at": "2020-08-31T16:46:41Z" }, { "body": "Is it just me or is this still broken?\r\n\r\n- `laravel new testProject` (Laravel 8.0.0)\r\n- Paste the following snippet in the `UserFactory.php`\r\n```php\r\npublic function foo()\r\n {\r\n return $this->state([\r\n 'name' => $this->faker->name,\r\n ]);\r\n }\r\n```\r\n- Open Tinker\r\n- Paste the following line: `User::factory()->foo()->make()`\r\n- returns `PHP Notice: Trying to get property 'name' of non-object`\r\n- `dd($this->faker);` returns `null`\r\n\r\n@axlon @driesvints \r\n\r\n(note the example method here is not returning a closure, but an array as demonstrated in the docs)", "created_at": "2020-09-08T20:46:17Z" }, { "body": "@drbyte could it be that you're using a unit test where the framework isn't booted?", "created_at": "2020-09-09T16:47:19Z" }, { "body": "@driesvints no, it's a proper FeatureTest which properly extends TestCase\r\n\r\nHere's a blank repo with a commit showing how to reproduce it:\r\nhttps://github.com/drbyte/withFaker-bug/commit/45442006ed35c394a23f2372cc5b8012f5463f6d", "created_at": "2020-09-09T18:01:44Z" }, { "body": "@drbyte its because your state is not within a closure, when you use it like this the state will be resolved as soon as you call the method, before faker is initialised\r\n\r\nChanging it to the snippet below should fix it:\r\n\r\n```\r\n public function male()\r\n {\r\n return $this->state(fn () => [\r\n 'name' => $this->faker->firstNameMale,\r\n ]);\r\n }\r\n```\r\n\r\nEdit (as I didn't read your first comment initially) : I haven't checked the docs yet, so I don't know if it shows an example without a Closure but AFAIK it won't work without a closure unless you manually instantiate faker on the factory instance (which I wouldn't recommend because of the way factories work internally)", "created_at": "2020-09-09T18:12:25Z" }, { "body": "Thanks. My brain was treating it as a regular class, but of course it's not. 😄 \r\n\r\nThe docs don't mention it, but I've submitted a PR. https://github.com/laravel/docs/pull/6329/files", "created_at": "2020-09-09T18:24:14Z" } ], "number": 34069, "title": "[8.x] Faker doesn't work within model factory states" }
{ "body": "It is currently possible to access `$faker` from factory state defined in the factory class itself. This was discussed in #34069 and implemented in #34074.\r\n\r\nHowever, Eloquent Factories also support passing inline state when using the factory:\r\n```php\r\n$user = User::factory()->state([\r\n 'name' => 'Abigail Otwell',\r\n])->make();\r\n```\r\n\r\nThe current implementation does not allow accessing `$faker` from this inline state closure:\r\n```php\r\n$user = User::factory()->state(fn () => [\r\n // The following line throws the error \"Cannot access protected property UserFactory::$faker\"\r\n 'name' => $this->faker,\r\n])->make();\r\n```\r\nI demonstrate this with a failing test in the first commit in this PR.\r\n\r\nI understand from the documentation that using inline state should be as similar as possible to using a state defined on the factory itself. To fix it, we simply need to also pass `$this` as the second argument to `bindTo`, in order to also re-bind the scope of the closure. This is implemented in the second commit.", "number": 36211, "review_comments": [], "title": "[8.x] Eloquent Factories: Allow access to $faker from inline state" }
{ "commits": [ { "message": "Add test for accessing faker in inline factory state closures" }, { "message": "Fix accessing ->faker in inline state closures" } ], "files": [ { "diff": "@@ -375,7 +375,7 @@ protected function getRawAttributes(?Model $parent)\n }], $states->all()));\n })->reduce(function ($carry, $state) use ($parent) {\n if ($state instanceof Closure) {\n- $state = $state->bindTo($this);\n+ $state = $state->bindTo($this, $this);\n }\n \n return array_merge($carry, $state($carry, $parent));", "filename": "src/Illuminate/Database/Eloquent/Factories/Factory.php", "status": "modified" }, { "diff": "@@ -211,6 +211,7 @@ public function test_has_many_relationship()\n ->state(function ($attributes, $user) {\n // Test parent is passed to child state mutations...\n $_SERVER['__test.post.state-user'] = $user;\n+ $_SERVER['__test.post.state-faker'] = $this->faker;\n \n return [];\n })\n@@ -230,10 +231,12 @@ public function test_has_many_relationship()\n $this->assertInstanceOf(Eloquent::class, $_SERVER['__test.post.creating-post']);\n $this->assertInstanceOf(Eloquent::class, $_SERVER['__test.post.creating-user']);\n $this->assertInstanceOf(Eloquent::class, $_SERVER['__test.post.state-user']);\n+ $this->assertInstanceOf(\\Faker\\Generator::class, $_SERVER['__test.post.state-faker']);\n \n unset($_SERVER['__test.post.creating-post']);\n unset($_SERVER['__test.post.creating-user']);\n unset($_SERVER['__test.post.state-user']);\n+ unset($_SERVER['__test.post.state-faker']);\n }\n \n public function test_belongs_to_relationship()", "filename": "tests/Database/DatabaseEloquentFactoryTest.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.23.1\r\n- PHP Version: 7.4.10\r\n- Database Driver & Version: Postgres 9.6+\r\n\r\n### Description:\r\n\r\nWhen performing a dump as follows:\r\n\r\n```shell\r\nphp artisan schema:dump\r\n```\r\n\r\nIt generates a dump file containing all data from the database.\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Create a new Postgresql database and rename it's default schema:\r\n\r\n```shell\r\ncreatedb testdb\r\npsql -c 'ALTER SCHEMA public RENAME TO alternative' testdb\r\n```\r\n\r\n2. Properly setup the database connection on `.env`\r\n\r\n3. In the project change `config/database.php` line `'schema' => 'public',` to `'schema' => 'alternative',` in the pgsql driver.\r\n\r\n4. Execute `migrate:install`\r\n\r\n5. Add some data to the database on any table other then `migrations` using any method.\r\n\r\n6. Execute the command `schema:dump`", "comments": [], "number": 35965, "title": "Dumping a schemefrom a postgresql database with a non default schema (i.e. other than public) results in a full dump including data." }
{ "body": "This PR solves the issue #35965 by adding the schema of the table to be ignored in the `--exclude-table-data` option when performing a dump.\r\n\r\nWhen loading generated dump it outputs some warnings saying that it cannot create the schema because it already exists, either way the rest of the load works successfully. Looking into the [Postgresql documentation](https://www.postgresql.org/docs/9.6/app-pgrestore.html) it is possible tho suppress such warnings ugins the option `--clean` and `--if-exists` when executing a `pg_restore`. As the load will only occur when the database is empty anyway the addition of those options seems harmless.\r\n\r\nFixes #35965", "number": 35966, "review_comments": [], "title": "[8.x] Fix issue with dumping schema from a postgres database using no default schema" }
{ "commits": [ { "message": "Add proper handling for non-default postgresql schema when performing a dump" }, { "message": "Suppress harmless errors messages when restoring a db dump with non default schema" }, { "message": "Use provided $connection to get schema" } ], "files": [ { "diff": "@@ -16,12 +16,13 @@ class PostgresSchemaState extends SchemaState\n */\n public function dump(Connection $connection, $path)\n {\n+ $schema = $connection->getConfig('schema');\n $excludedTables = collect($connection->getSchemaBuilder()->getAllTables())\n ->map->tablename\n ->reject(function ($table) {\n return $table === $this->migrationTable;\n- })->map(function ($table) {\n- return '--exclude-table-data='.$table;\n+ })->map(function ($table) use ($schema) {\n+ return '--exclude-table-data='.$schema.'.'.$table;\n })->implode(' ');\n \n $this->makeProcess(\n@@ -39,7 +40,7 @@ public function dump(Connection $connection, $path)\n */\n public function load($path)\n {\n- $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD pg_restore --no-owner --no-acl --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE $LARAVEL_LOAD_PATH';\n+ $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD pg_restore --no-owner --no-acl --clean --if-exists --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE $LARAVEL_LOAD_PATH';\n \n if (Str::endsWith($path, '.sql')) {\n $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD psql --file=$LARAVEL_LOAD_PATH --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE';", "filename": "src/Illuminate/Database/Schema/PostgresSchemaState.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": "MySQL persistent connections:\r\n\r\n- PHP-FPM 7.4\r\n- MySQL 8.0 (SSL)\r\n\r\nDue to short network unavailabilities, we sometimes lose connection and a reconnection should be attempted.\r\n\r\n**SQLSTATE[HY000] [2002] Connection timed out**\r\n\r\n`````\r\n[2020-11-15 11:00:19] production.ERROR: SQLSTATE[HY000] [2002] Connection timed out (SQL: select ...))) {\"exception\":\"[object] (Illuminate\\\\Database\\\\QueryException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out (SQL: select ...))) at /var/www/html/vendor/illuminate/database/Connection.php:671)\r\n[stacktrace]\r\n#0 /var/www/html/vendor/illuminate/database/Connection.php(631): Illuminate\\\\Database\\\\Connection->runQueryCallback('select count(*)...', Array, Object(Closure))\r\n#1 /var/www/html/vendor/illuminate/database/Connection.php(339): Illuminate\\\\Database\\\\Connection->run('select count(*)...', Array, Object(Closure))\r\n#2 /var/www/html/vendor/illuminate/database/Query/Builder.php(2303): Illuminate\\\\Database\\\\Connection->select('select count(*)...', Array, true)\r\n#3 /var/www/html/vendor/illuminate/database/Query/Builder.php(2291): Illuminate\\\\Database\\\\Query\\\\Builder->runSelect()\r\n#4 /var/www/html/vendor/illuminate/database/Query/Builder.php(2786): Illuminate\\\\Database\\\\Query\\\\Builder->Illuminate\\\\Database\\\\Query\\\\{closure}()\r\n#5 /var/www/html/vendor/illuminate/database/Query/Builder.php(2292): Illuminate\\\\Database\\\\Query\\\\Builder->onceWithColumns(Array, Object(Closure))\r\n#6 /var/www/html/vendor/illuminate/database/Query/Builder.php(2713): Illuminate\\\\Database\\\\Query\\\\Builder->get(Array)\r\n#7 /var/www/html/vendor/illuminate/database/Query/Builder.php(2641): Illuminate\\\\Database\\\\Query\\\\Builder->aggregate('count', Array)\r\n#8 /var/www/html/vendor/illuminate/database/Eloquent/Builder.php(1508): Illuminate\\\\Database\\\\Query\\\\Builder->count()\r\n#9 /var/www/html/vendor/illuminate/support/Traits/ForwardsCalls.php(23): Illuminate\\\\Database\\\\Eloquent\\\\Builder->__call('count', Array)\r\n#10 /var/www/html/vendor/illuminate/database/Eloquent/Model.php(1757): Illuminate\\\\Database\\\\Eloquent\\\\Model->forwardCallTo(Object(Illuminate\\\\Database\\\\Eloquent\\\\Builder), 'count', Array)\r\n#11 /var/www/html/vendor/illuminate/database/Eloquent/Model.php(1769): Illuminate\\\\Database\\\\Eloquent\\\\Model->__call('count', Array)\r\n``````\r\n\r\n**SSL: Connection timed out**\r\n\r\n`````\r\n[2020-11-12 07:20:23] production.ERROR: PDO::__construct(): SSL: Connection timed out (SQL: select * ...) {\"exception\":\"[object] (Illuminate\\\\Database\\\\QueryException(code: 0): PDO::__construct(): SSL: Connection timed out (SQL: select ...) at /var/www/html/vendor/illuminate/database/Connection.php:671)\r\n[stacktrace]\r\n#0 /var/www/html/vendor/illuminate/database/Connection.php(631): Illuminate\\\\Database\\\\Connection->runQueryCallback('select * from `...', Array, Object(Closure))\r\n#1 /var/www/html/vendor/illuminate/database/Connection.php(339): Illuminate\\\\Database\\\\Connection->run('select * from `...', Array, Object(Closure))\r\n#2 /var/www/html/vendor/illuminate/database/Query/Builder.php(2303): Illuminate\\\\Database\\\\Connection->select('select * from `...', Array, true)\r\n#3 /var/www/html/vendor/illuminate/database/Query/Builder.php(2291): Illuminate\\\\Database\\\\Query\\\\Builder->runSelect()\r\n#4 /var/www/html/vendor/illuminate/database/Query/Builder.php(2786): Illuminate\\\\Database\\\\Query\\\\Builder->Illuminate\\\\Database\\\\Query\\\\{closure}()\r\n#5 /var/www/html/vendor/illuminate/database/Query/Builder.php(2292): Illuminate\\\\Database\\\\Query\\\\Builder->onceWithColumns(Array, Object(Closure))\r\n#6 /var/www/html/vendor/illuminate/database/Eloquent/Builder.php(549): Illuminate\\\\Database\\\\Query\\\\Builder->get(Array)\r\n#7 /var/www/html/vendor/illuminate/database/Eloquent/Builder.php(533): Illuminate\\\\Database\\\\Eloquent\\\\Builder->getModels(Array)\r\n#8 /var/www/html/vendor/illuminate/database/Concerns/BuildsQueries.php(147): Illuminate\\\\Database\\\\Eloquent\\\\Builder->get(Array)\r\n````\r\n\r\n", "number": 35224, "review_comments": [], "title": "[8.x] Add lost connection messages for MySQL persistent connections" }
{ "commits": [ { "message": "[Mysql] Add lost connection messages for persistent connections" }, { "message": "Fix style" } ], "files": [ { "diff": "@@ -45,6 +45,8 @@ protected function causedByLostConnection(Throwable $e)\n 'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.',\n 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Try again',\n 'SQLSTATE[HY000]: General error: 7 SSL SYSCALL error: EOF detected',\n+ 'SQLSTATE[HY000] [2002] Connection timed out',\n+ 'SSL: Connection timed out',\n ]);\n }\n }", "filename": "src/Illuminate/Database/DetectsLostConnections.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 8.13\r\n- PHP Version: 7.4\r\n- Database Driver & Version: none\r\n\r\n### Description:\r\n\r\nRendering a component with prepended attributes but without overriding that attribute in the calling template yields an error.\r\n\r\n### Steps To Reproduce:\r\n\r\n- `composer create-project laravel/laravel testing`\r\n- `php artisan make:component TestComponent`\r\n- Copy the example from the docs into the template\r\n\r\n```blade\r\n<div {{ $attributes->merge(['data-controller' => $attributes->prepends('profile-controller')]) }}>\r\n {{ $slot }}\r\n</div>\r\n```\r\n- attempt to render the component without 'data-controller' specified.\r\n\r\nRendering this component like so: `<x-test-component data-controller=\"some-controller\" />` works as expected.\r\n\r\nRendering this component like so: `<x-test-component />` yields the following error:\r\n<img width=\"1209\" alt=\"Screen Shot 2020-11-06 at 13 59 09\" src=\"https://user-images.githubusercontent.com/6180087/98340888-41417b80-2038-11eb-852c-a6815f5f7b72.png\">\r\n\r\nI would expect to have the string `profile-controller` to be the default and only value present if no attribute named `data-controller` is specified.\r\n", "comments": [ { "body": "I've hotfixed this locally by adding a `__toString` method to [AppendableAttributeValue](https://github.com/laravel/framework/blob/8.x/src/Illuminate/View/AppendableAttributeValue.php) like so:\r\n\r\n```php\r\n<?php\r\n\r\nnamespace Illuminate\\View;\r\n\r\nclass AppendableAttributeValue\r\n{\r\n /**\r\n * The attribute value.\r\n *\r\n * @var mixed\r\n */\r\n public $value;\r\n\r\n /**\r\n * Create a new appendable attribute value.\r\n *\r\n * @param mixed $value\r\n * @return void\r\n */\r\n public function __construct($value)\r\n {\r\n $this->value = $value;\r\n }\r\n\r\n public function __toString()\r\n {\r\n return (string)$this->value;\r\n }\r\n}\r\n\r\n```\r\n\r\nNot sure how this affects other parts of the code though.", "created_at": "2020-11-06T08:13:25Z" }, { "body": "> Copy the example from the docs into the template\r\n\r\nWhich example?", "created_at": "2020-11-06T09:29:52Z" }, { "body": "@driesvints the one from the [Non-class attribute merging](https://laravel.com/docs/8.x/blade#non-class-attribute-merging) section. I've provided it verbatim in my original post.", "created_at": "2020-11-06T09:59:21Z" }, { "body": "Copy paste your `TestComponent` please.", "created_at": "2020-11-06T10:09:23Z" }, { "body": "It's just an empty default Component stub:\r\n```\r\n<?php\r\n\r\nnamespace App\\View\\Components;\r\n\r\nuse Illuminate\\View\\Component;\r\n\r\nclass TestComponent extends Component\r\n{\r\n /**\r\n * Create a new component instance.\r\n *\r\n * @return void\r\n */\r\n public function __construct()\r\n {\r\n //\r\n }\r\n\r\n /**\r\n * Get the view / contents that represent the component.\r\n *\r\n * @return \\Illuminate\\Contracts\\View\\View|string\r\n */\r\n public function render()\r\n {\r\n return view('components.test-component');\r\n }\r\n}\r\n\r\n```", "created_at": "2020-11-06T10:15:48Z" }, { "body": "Thanks. I managed to reproduce this. I think the `__toString` solution is a valid one. Can you PR it? A test would be useful as well.", "created_at": "2020-11-06T10:34:57Z" }, { "body": "Sure, I'll link it here when it's ready.", "created_at": "2020-11-06T10:42:03Z" }, { "body": "Fixed in #35131 ", "created_at": "2020-11-07T05:41:44Z" } ], "number": 35128, "title": "Prepending component attributes causes an exception when said attribute is missing in calling template" }
{ "body": "Currently, attempting to render a component which prepends a non-class attribute in it's template without actually overriding it in the calling template yields an Exception.\r\n\r\nFor example, given the following component called `test-component`:\r\n\r\n```blade\r\n<div {{ $attributes->merge(['data-controller' => $attributes->prepends('profile-controller')]) }}>\r\n {{ $slot }}\r\n</div>\r\n```\r\n\r\nRendering this component like so: `<x-test-component data-controller=\"some-controller\" />` works as expected.\r\n\r\nRendering this component like so: `<x-test-component />` yields the following error:\r\n\r\n<img width=\"1209\" alt=\"Screen Shot 2020-11-06 at 13 59 09\" src=\"https://user-images.githubusercontent.com/6180087/98340888-41417b80-2038-11eb-852c-a6815f5f7b72.png\">\r\n\r\nThis PR fixes this behavior. `<x-test-component />` will now properly render as\r\n```\r\n<div data-controller=\"profile-controller\"></div>\r\n```\r\n\r\nSee #35128 for more details.\r\n", "number": 35131, "review_comments": [ { "body": "```suggestion\r\n return (string) $this->value;\r\n```", "created_at": "2020-11-06T10:58:26Z" }, { "body": "Add a docblock in the same formatting as the rest of the framework.", "created_at": "2020-11-06T10:58:38Z" } ], "title": "[8.x] Fix appendable attributes in Blade components" }
{ "commits": [ { "message": "Update AppendableAttributeValue.php" }, { "message": "Add tests" }, { "message": "Fix tests" }, { "message": "Add docblock" }, { "message": "Fix unrelated test" }, { "message": "Update hello-span.blade.php" }, { "message": "Update BladeTest.php" }, { "message": "Update AppendableAttributeValue.php" } ], "files": [ { "diff": "@@ -21,4 +21,14 @@ public function __construct($value)\n {\n $this->value = $value;\n }\n+\n+ /**\n+ * Get the string value.\n+ *\n+ * @return string\n+ */\n+ public function __toString()\n+ {\n+ return (string) $this->value;\n+ }\n }", "filename": "src/Illuminate/View/AppendableAttributeValue.php", "status": "modified" }, { "diff": "@@ -50,11 +50,17 @@ public function test_rendering_the_same_dynamic_component_with_different_attribu\n \n public function test_appendable_attributes()\n {\n- $view = View::make('uses-appendable-panel', ['name' => 'Taylor'])->render();\n+ $view = View::make('uses-appendable-panel', ['name' => 'Taylor', 'withOutside' => true])->render();\n \n $this->assertSame('<div class=\"mt-4 bg-gray-100\" data-controller=\"inside-controller outside-controller\" foo=\"bar\">\n Hello Taylor\n </div>', trim($view));\n+\n+ $view = View::make('uses-appendable-panel', ['name' => 'Taylor', 'withOutside' => false])->render();\n+\n+ $this->assertSame('<div class=\"mt-4 bg-gray-100\" data-controller=\"inside-controller\" foo=\"bar\">\n+ Hello Taylor\n+</div>', trim($view));\n }\n \n protected function getEnvironmentSetUp($app)", "filename": "tests/Integration/View/BladeTest.php", "status": "modified" }, { "diff": "@@ -1,3 +1,9 @@\n-<x-appendable-panel class=\"bg-gray-100\" :name=\"$name\" data-controller=\"outside-controller\" foo=\"bar\">\n- Panel contents\n-</x-appendable-panel>\n+@if ($withOutside)\n+ <x-appendable-panel class=\"bg-gray-100\" :name=\"$name\" data-controller=\"outside-controller\" foo=\"bar\">\n+ Panel contents\n+ </x-appendable-panel>\n+@else\n+ <x-appendable-panel class=\"bg-gray-100\" :name=\"$name\" foo=\"bar\">\n+ Panel contents\n+ </x-appendable-panel>\n+@endif", "filename": "tests/Integration/View/templates/uses-appendable-panel.blade.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 pull request fixes the partially incorrect behavior of the `schedule:work` command (`schedule:run` is not executed if the previous execution has taken more than 1 minute).\r\n\r\nThe idea of this PR is to have a pool of executions.\r\n\r\nWhen the execution is started - it's added to the pool.\r\nWhen the execution is finished - it's removed from the pool.\r\nWhen the new output from any execution is available - it's outputted.\r\n\r\nLet's imagine we have the following scheduler setup:\r\n\r\n```php\r\nprotected function schedule(Schedule $schedule)\r\n{\r\n $schedule->command('sleep 1')->everyMinute();\r\n $schedule->command('sleep 2')->everyMinute();\r\n $schedule->command('sleep 64')->everyMinute();\r\n $schedule->command('sleep 128')->everyMinute();\r\n}\r\n```\r\n\r\n> `sleep` command just runs the `sleep()` function with the specified number of seconds \r\n\r\nCurrently, the first execution will be performed. However, executions won't be performed during the next few minutes (because executions are performed synchronously).\r\n\r\nIn this PR executions will be performed asynchronously & you'll see the following output:\r\n\r\n```\r\nSchedule worker started successfully.\r\n\r\nExecution #1 output:\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 1 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 2 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 64 > '/dev/null' 2>&1\r\n\r\nExecution #2 output:\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 1 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 2 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 64 > '/dev/null' 2>&1\r\n\r\nExecution #1 output:\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 128 > '/dev/null' 2>&1\r\n\r\nExecution #3 output:\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 1 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 2 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 64 > '/dev/null' 2>&1\r\n\r\nExecution #2 output:\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 128 > '/dev/null' 2>&1\r\n\r\nExecution #4 output:\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 1 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 2 > '/dev/null' 2>&1\r\nRunning scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' sleep 64 > '/dev/null' 2>&1\r\n```\r\n\r\nWhat do you think about this idea? Does it look fine? \r\n\r\n**_The code might probably be polished._** ", "number": 34736, "review_comments": [], "title": "[8.x] Improve `schedule:work` command" }
{ "commits": [ { "message": "wip" }, { "message": "Update ScheduleWorkCommand.php" } ], "files": [ { "diff": "@@ -4,6 +4,8 @@\n \n use Illuminate\\Console\\Command;\n use Illuminate\\Support\\Carbon;\n+use Illuminate\\Support\\Str;\n+use Symfony\\Component\\Process\\Process;\n \n class ScheduleWorkCommand extends Command\n {\n@@ -30,12 +32,47 @@ public function handle()\n {\n $this->info('Schedule worker started successfully.');\n \n+ $lastExecutionStartedAt = null;\n+\n+ $keyOfLastExecutionWithOutput = null;\n+\n+ $executions = [];\n+\n while (true) {\n- if (Carbon::now()->second === 0) {\n- $this->call('schedule:run');\n+ if (Carbon::now()->second === 0 && ! Carbon::now()->startOfMinute()->equalTo($lastExecutionStartedAt)) {\n+ $execution = new Process([PHP_BINARY, 'artisan', 'schedule:run']);\n+ $execution->start();\n+ $executions[] = $execution;\n+ $lastExecutionStartedAt = Carbon::now()->startOfMinute();\n }\n \n- sleep(1);\n+ foreach ($executions as $key => $execution) {\n+ $incrementalOutput = trim($execution->getIncrementalOutput());\n+\n+ if (Str::length($incrementalOutput) > 0) {\n+ if ($key !== $keyOfLastExecutionWithOutput) {\n+ $this->info(PHP_EOL.'Execution #'.($key + 1).' output:');\n+ $keyOfLastExecutionWithOutput = $key;\n+ }\n+\n+ $this->warn($incrementalOutput);\n+ }\n+\n+ $incrementalErrorOutput = trim($execution->getIncrementalErrorOutput());\n+\n+ if (Str::length($incrementalErrorOutput) > 0) {\n+ if ($key !== $keyOfLastExecutionWithOutput) {\n+ $this->info(PHP_EOL.'Execution #'.($key + 1).' output:');\n+ $keyOfLastExecutionWithOutput = $key;\n+ }\n+\n+ $this->error(trim($incrementalErrorOutput));\n+ }\n+\n+ if (! $execution->isRunning()) {\n+ unset($executions[$key]);\n+ }\n+ }\n }\n }\n }", "filename": "src/Illuminate/Console/Scheduling/ScheduleWorkCommand.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.2.0\r\n- PHP Version: 7.4.6\r\n- Guzzle Version: 7.0.1\r\n\r\n### Description: \r\n\r\nIf you provide middleware on your Http client it will never be invoked when using `Http::fake()`\r\n\r\n### Steps To Reproduce:\r\n\r\n\r\n```php\r\nclass HttpClientMiddlewareTest extends TestCase\r\n{\r\n public function test_it_applies_middleware_when_no_fake()\r\n {\r\n $middleware = Middleware::mapResponse(function (ResponseInterface $response) {\r\n return $response->withHeader('X-Foo', 'bar');\r\n });\r\n\r\n $response = Http::asForm()->withMiddleware($middleware)->get('http://google.com');\r\n $this->assertEquals('bar', $response->header('X-Foo'));\r\n }\r\n\r\n public function test_it_doesn_not_apply_middleware_when_fake()\r\n {\r\n $middleware = Middleware::mapResponse(function (ResponseInterface $response) {\r\n return $response->withHeader('X-Foo', 'bar');\r\n });\r\n\r\n Http::fake();\r\n\r\n $response = Http::asForm()->withMiddleware($middleware)->get('http://google.com');\r\n $this->assertEmpty($response->header('X-Foo'));\r\n }\r\n}\r\n```\r\n\r\n![Screen Shot 2020-09-24 at 2 45 56 PM](https://user-images.githubusercontent.com/340715/94094874-b3894280-fe74-11ea-9987-af7c58b4cde5.png)\r\n\r\nAs you can see the middleware is not applied in the second test\r\n\r\n* Add middleware to client `$client->withMiddleware(...)`\r\n* Call `Http::fake()`\r\n* Assert Middleware applied\r\n", "comments": [ { "body": "I'm actually not sure about this one myself. Will need input from @taylorotwell here.", "created_at": "2020-09-24T11:50:01Z" }, { "body": "I'm not sure I would expect any middleware to run at all, so to me personally this is expected behavior. If you're faking the HTTP client you are going to specify exactly what responses should returned.", "created_at": "2020-09-24T12:56:00Z" }, { "body": "@taylorotwell @driesvints I'd really appreciate if you can reconsider this, without this working its completely impossible to test that middleware is configured and working correctly.\r\n\r\nPerhaps my example of mutating the response was not great - this was for simplicity sake and was lifted directly from the [guzzle docs](http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html#middleware).\r\n\r\nI have a number of middleware that perform a range of actions such as:\r\n\r\n* Validating JSON response structure against a OAS/Swagger spec (If its invalid an exception should be thrown)\r\n* Caching responses based on provided options\r\n* Transforming responses to appropriate exceptions (eg `ValidationException::withMessages(...)`, `AuthorizationException` etc)\r\n\r\nWithout the ability to test my middleware, the `withMiddleware(...)` method is not useful to me and I've had to opt for a more procedural approach or use Guzzle directly, but honestly I much prefer the interface for `Http` and `Http:fake()`\r\n\r\nI'm happy to work on a PR for this if needed.\r\n\r\n", "created_at": "2020-09-24T20:49:03Z" }, { "body": "We're probably not going to reconsider this, sorry.", "created_at": "2020-09-25T08:47:51Z" }, { "body": "So, I also spent some time in this... Then found this issue. \r\n\r\nI think there is another good use case for this. We, very often, need to log what is sent to an api and what is received.\r\n\r\nWhen testing, using `Mail::fake()`, Testing this logger will not be possible\r\n\r\n```php \r\n$response = Http::withMiddleware(Middleware::log(\r\n app(LogManager::class)->channel(),\r\n new MessageFormatter()\r\n ))->{$method}($url, $payload);\r\n```\r\n\r\njust in case +1 on this \r\n\r\nThanks", "created_at": "2020-09-28T21:17:17Z" } ], "number": 34505, "title": "Http client not applying middleware when using Http::fake()" }
{ "body": "## What is happening?\r\n\r\nThe `HttpClient` provides the ability to have Guzzle Middlewares by using the `Http::withMiddleware()` method.\r\n\r\nThis method works just fine when using the __HttpClient__ in production code. But when using `Http::fake()`, usually when testing external services, the `Http::withMiddleware()` method has no effect.\r\n\r\n## Why does it happen?\r\n\r\nThis happens because Guzzle will always stop going through any other handlers when the Laravel `StubHandler` is executed. \r\n\r\n## How to fix?\r\n\r\nThe fix should be very simple, given the builtIn `stubHandler` is meant to give just the response we need it to give, we can move this stub handler to be executed as the last middleware in the stack.\r\n\r\n## Why?\r\n\r\nHaving the `Http::WithMiddleware()` method work as expected in tests and in production code is good for consistency in the framework and allows developers to test Middlewares in a __Feature/Integration__ way which reflects the functionality as similar as in production.\r\n\r\n## Use cases for this?\r\n\r\nA good use case for this, is having a Guzzle Middleware log, which logs requests and responses for better traceability\r\n\r\n```php\r\nHttp::withMiddleware(\r\n Middleware::log(app(LogManager::class)->channel(), new MessageFormatter())\r\n)->post($url, $payload);\r\n```\r\n\r\nThere are so many guzzle-middlewares for things like, requesting Oauth tokens, having custom error handlers, caching request/responses, logging, retrying on failures, etc. \r\n\r\n## Discussed Previously in:\r\n\r\nSome words were discussed in #34505 and I know it could be a closed PR due to this, but I wanted to expand on the topic and propose a simple solution. Thanks!!", "number": 34666, "review_comments": [], "title": "[8.x] Add ability to use middlewares in HttpClient when using Http:fake()" }
{ "commits": [ { "message": "Adds Failing test case - HttpClient & Middleware" }, { "message": "Adds support for middlewares when faking HttpClient" }, { "message": "Style Fix" } ], "files": [ { "diff": "@@ -644,11 +644,11 @@ public function buildHandlerStack()\n return tap(HandlerStack::create(), function ($stack) {\n $stack->push($this->buildBeforeSendingHandler());\n $stack->push($this->buildRecorderHandler());\n- $stack->push($this->buildStubHandler());\n-\n $this->middleware->each(function ($middleware) use ($stack) {\n $stack->push($middleware);\n });\n+\n+ $stack->push($this->buildStubHandler());\n });\n }\n ", "filename": "src/Illuminate/Http/Client/PendingRequest.php", "status": "modified" }, { "diff": "@@ -34,6 +34,26 @@ public function testStubbedResponsesAreReturnedAfterFaking()\n $this->assertTrue($response->ok());\n }\n \n+ public function testMiddlewareGetsCalled()\n+ {\n+ $this->factory->fake();\n+\n+ $middlewareWasCalled = false;\n+\n+ $middleware = function ($handler) use (&$middlewareWasCalled) {\n+ return function ($request, $options) use ($handler, &$middlewareWasCalled) {\n+ $middlewareWasCalled = true;\n+\n+ return $handler($request, $options);\n+ };\n+ };\n+\n+ $response = $this->factory->withMiddleware($middleware)->post('http://laravel.com/test-missing-page');\n+\n+ $this->assertTrue($response->ok());\n+ $this->assertTrue($middlewareWasCalled);\n+ }\n+\n public function testResponseBodyCasting()\n {\n $this->factory->fake([", "filename": "tests/Http/HttpClientTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: v8.6.0\r\n- PHP Version: 7.4.0\r\n- Database Driver & Version: irrelevant\r\n\r\n### Description:\r\n\r\n```html\r\n{{-- Works: --}}\r\n<x-foo value=\"abc\" a=\"b\" />\r\n<x-foo value=\"abc\" />\r\n\r\n{{-- Doesn't work: --}}\r\n<x-dynamic-component component=\"foo\" value=\"abc\" a=\"b\" />\r\n<x-dynamic-component component=\"foo\" value=\"xyz\" />\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a basic **anonymous** component named `foo`. It doesn't have to do anything, just make it an empty div.\r\n\r\nCreate another component that uses the code above.\r\n\r\nThe issue is that the **dynamic component call for `foo` gets compiled and cached**. Even though the call is different each time.\r\n\r\nSo the first call assumes an `$a` variable existing, but this variable is not present in the second call.\r\n\r\nHence, an exception like this is thrown:\r\n\r\n```\r\nUndefined variable: a (View: /Users/samuel/Projects/dynamic-component-wire/storage/framework/views/a553ad954f8954104deb899637465b63312af2fd.blade.php) (View: /Users/samuel/Projects/dynamic-component-wire/storage/framework/views/a553ad954f8954104deb899637465b63312af2fd.blade.php)\r\n```\r\n\r\n### Debugging\r\n\r\nWhen you open `a553ad954f8954104deb899637465b63312af2fd.blade.php`, you see:\r\n\r\n```php\r\n<?php extract(collect($attributes->getAttributes())->mapWithKeys(function ($value, $key) { return [Illuminate\\Support\\Str::camel(str_replace([':', '.'], ' ', $key)) => $value]; })->all(), EXTR_SKIP); ?>\r\n@props(['value','a'])\r\n<x-foo :value=\"$value\" :a=\"$a\" >\r\n\r\n{{ $slot ?? \"\" }}\r\n</x-foo>\r\n```\r\n\r\nThis is the **compiled & cached version of the dynamic `x-foo` call**. The issue is that the same file is used for both calls, even though they're different.\r\n\r\nThis can be proved by adding a `dump()` statement above the `@props` line:\r\n```php\r\n<?php dump(isset($a)); ?>\r\n```\r\n\r\nThis results in:\r\n\r\n![Screen Shot 2020-09-22 at 20 42 41](https://user-images.githubusercontent.com/33033094/93923813-2c24bd80-fd14-11ea-8f1a-a5908b90c6c9.png)\r\n\r\n### Expected behavior\r\n\r\nEach dynamic call can be different, therefore we shouldn't reuse compiled views for them.\r\n\r\nEach of those `<x-dynamic-component component=\"foo\" ... />` calls should have a separate compiled file.", "comments": [ { "body": "Probably will need a PR. Not sure how much time I have to keep looking into dynamic components.", "created_at": "2020-09-23T02:02:25Z" }, { "body": "Sure, appreciate the bug fixes so far.\r\n\r\nI've spent a lot of time in Blade internals at this point do I think I should be able to do this.", "created_at": "2020-09-23T06:21:45Z" }, { "body": "This fixes it:\r\n\r\n```diff\r\nprotected function bindings(string $class)\r\n{\r\n- if (! isset(static::$bindings[$class])) {\r\n [$data, $attributes] = $this->compiler()->partitionDataAndAttributes($class, $this->attributes->getAttributes());\r\n\r\n- static::$bindings[$class] = array_keys($data->all());\r\n+ return array_keys($data->all());\r\n- }\r\n\r\n- return static::$bindings[$class];\r\n}\r\n```\r\n\r\nThe `$bindings` static property on `DynamicComponent` caches the parsed bindings by component name.\r\n\r\nSo the `DynamicComponent::$bindings` array looks like:\r\n\r\n```php\r\n'components.foo' => [\r\n 0 => \"value\",\r\n 1 => \"a\",\r\n],\r\n```\r\n\r\nAnd the next time `DynamicComponent` is calling `components.foo`, it uses this cached version instead of parsing the bindings again.\r\n\r\nI will submit a PR, but before I do, could you please tell me if you know whether there's a reason for this caching? Or is that just a performance thing?\r\n\r\nThank you.", "created_at": "2020-09-23T12:49:57Z" }, { "body": "Probably just performance. I guess we will have to ditch that.", "created_at": "2020-09-23T15:17:55Z" } ], "number": 34469, "title": "Can't dynamically call the same anonymous component twice, with different attributes each time" }
{ "body": "Fixes #34469 \r\n\r\nThis removes the binding caching for dynamic components. And adds a regression test for the linked issue.\r\n\r\nHere's proof of regression test failing before the fix:\r\n\r\n![Screen Shot 2020-09-23 at 18 33 13](https://user-images.githubusercontent.com/33033094/94043071-a1ec6000-fdcc-11ea-92a4-5c30c4ffb42a.png)\r\n", "number": 34498, "review_comments": [], "title": "[8.x] Allow for dynamic calls of anonymous component with varied attributes" }
{ "commits": [ { "message": "Allow for dynamic calls of anonymous component with varied attributes, add regression test" } ], "files": [ { "diff": "@@ -29,13 +29,6 @@ class DynamicComponent extends Component\n */\n protected static $componentClasses = [];\n \n- /**\n- * The cached binding keys for component classes.\n- *\n- * @var array\n- */\n- protected static $bindings = [];\n-\n /**\n * Create a new component instance.\n *\n@@ -153,13 +146,9 @@ protected function classForComponent()\n */\n protected function bindings(string $class)\n {\n- if (! isset(static::$bindings[$class])) {\n- [$data, $attributes] = $this->compiler()->partitionDataAndAttributes($class, $this->attributes->getAttributes());\n-\n- static::$bindings[$class] = array_keys($data->all());\n- }\n+ [$data, $attributes] = $this->compiler()->partitionDataAndAttributes($class, $this->attributes->getAttributes());\n \n- return static::$bindings[$class];\n+ return array_keys($data->all());\n }\n \n /**", "filename": "src/Illuminate/View/DynamicComponent.php", "status": "modified" }, { "diff": "@@ -35,6 +35,19 @@ public function test_rendering_a_dynamic_component()\n </div>', trim($view));\n }\n \n+ public function test_rendering_the_same_dynamic_component_with_different_attributes()\n+ {\n+ $view = View::make('varied-dynamic-calls')->render();\n+\n+ $this->assertEquals('<span class=\"text-medium\">\n+ Hello Taylor\n+</span>\n+ \n+ <span >\n+ Hello Samuel\n+</span>', trim($view));\n+ }\n+\n protected function getEnvironmentSetUp($app)\n {\n $app['config']->set('view.paths', [__DIR__.'/templates']);", "filename": "tests/Integration/View/BladeTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,7 @@\n+@props([\n+ 'name',\n+])\n+\n+<span {{ $attributes }}>\n+ Hello {{ $name }}\n+</span>", "filename": "tests/Integration/View/templates/components/hello-span.blade.php", "status": "added" }, { "diff": "@@ -0,0 +1,2 @@\n+<x-dynamic-component component=\"hello-span\" name=\"Taylor\" class=\"text-medium\" />\n+<x-dynamic-component component=\"hello-span\" name=\"Samuel\" />", "filename": "tests/Integration/View/templates/varied-dynamic-calls.blade.php", "status": "added" } ] }
{ "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": "When we use illuminate/session within a lumen project. StartSession middleware fails with the following error:\r\n\r\n```\r\n[2020-09-23 11:43:38] production.ERROR: Call to a member function locksFor() on array {\"exception\":\"[object] (Error(code: 0): Call to a member function locksFor() on array at /var/www/html/vendor/illuminate/session/Middleware/StartSession.php:59)\r\n[stacktrace]\r\n#0 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): Illuminate\\\\Session\\\\Middleware\\\\StartSession->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#1 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#2 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#3 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(103): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#4 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(423): Illuminate\\\\Pipeline\\\\Pipeline->then(Object(Closure))\r\n#5 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(260): Laravel\\\\Lumen\\\\Application->sendThroughPipeline(Array, Object(Closure))\r\n#6 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(234): Laravel\\\\Lumen\\\\Application->handleFoundRoute(Array)\r\n#7 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(170): Laravel\\\\Lumen\\\\Application->handleDispatcherResponse(Array)\r\n#8 [internal function]: Laravel\\\\Lumen\\\\Application->Laravel\\\\Lumen\\\\Concerns\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#9 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(48): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#10 /var/www/html/vendor/total-services/core/src/Http/Middleware/LocaleMiddleware.php(33): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#11 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\LocaleMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#12 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#13 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#14 /var/www/html/vendor/total-services/core/src/Http/Middleware/XForwardedPathMiddleware.php(30): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#15 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\XForwardedPathMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#16 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#17 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#18 /var/www/html/vendor/fideloper/proxy/src/TrustProxies.php(57): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#19 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): Fideloper\\\\Proxy\\\\TrustProxies->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#20 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#21 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#22 /var/www/html/vendor/total-services/core/src/Http/Middleware/ConvertStringBooleansMiddleware.php(25): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#23 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\ConvertStringBooleansMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#24 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#25 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#26 /var/www/html/vendor/total-services/core/src/Http/Middleware/ConvertEmptyStringsToNull.php(15): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#27 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\ConvertEmptyStringsToNull->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#28 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#29 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#30 /var/www/html/vendor/total-services/core/src/Http/Middleware/MaintenanceModeMiddleware.php(30): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#31 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\MaintenanceModeMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#32 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#33 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#34 /var/www/html/vendor/total-services/core/src/Http/Middleware/CountryBlockerMiddleware.php(40): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#35 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\CountryBlockerMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#36 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#37 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#38 /var/www/html/app/Http/Middleware/Cors.php(29): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#39 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): App\\\\Http\\\\Middleware\\\\Cors->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#40 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#41 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#42 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(103): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#43 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(423): Illuminate\\\\Pipeline\\\\Pipeline->then(Object(Closure))\r\n#44 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(172): Laravel\\\\Lumen\\\\Application->sendThroughPipeline(Array, Object(Closure))\r\n#45 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(109): Laravel\\\\Lumen\\\\Application->dispatch(NULL)\r\n#46 /var/www/html/public/index.php(17): Laravel\\\\Lumen\\\\Application->run()\r\n#47 {main}\r\n\"} \r\n```\r\n\r\nThe reason is that Laravel\\Lumen\\Http\\Request::route() return `array|null` when Illuminate\\Http\\Request::route() return `Illuminate\\Routing\\Route|object|null`.\r\n", "number": 34491, "review_comments": [], "title": "[8.x] Fix incompatibility with Lumen route function which return an array." }
{ "commits": [ { "message": "🐛 Fix incompatibility with Lumen\n\nLumen $request->route() signature is different from Illuminate\\Http\\Request::route" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n use Closure;\n use Illuminate\\Contracts\\Session\\Session;\n use Illuminate\\Http\\Request;\n+use Illuminate\\Routing\\Route;\n use Illuminate\\Session\\SessionManager;\n use Illuminate\\Support\\Carbon;\n use Illuminate\\Support\\Facades\\Date;\n@@ -56,7 +57,7 @@ public function handle($request, Closure $next)\n $session = $this->getSession($request);\n \n if ($this->manager->shouldBlock() ||\n- ($request->route() && $request->route()->locksFor())) {\n+ ($request->route() instanceof Route && $request->route()->locksFor())) {\n return $this->handleRequestWhileBlocking($request, $session, $next);\n } else {\n return $this->handleStatefulRequest($request, $session, $next);\n@@ -73,6 +74,10 @@ public function handle($request, Closure $next)\n */\n protected function handleRequestWhileBlocking(Request $request, $session, Closure $next)\n {\n+ if (! $request->route() instanceof Route) {\n+ return;\n+ }\n+\n $lockFor = $request->route() && $request->route()->locksFor()\n ? $request->route()->locksFor()\n : 10;\n@@ -195,7 +200,7 @@ protected function configHitsLottery(array $config)\n protected function storeCurrentUrl(Request $request, $session)\n {\n if ($request->method() === 'GET' &&\n- $request->route() &&\n+ $request->route() instanceof Route &&\n ! $request->ajax() &&\n ! $request->prefetch()) {\n $session->setPreviousUrl($request->fullUrl());", "filename": "src/Illuminate/Session/Middleware/StartSession.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 we use illuminate/session within a lumen project. StartSession middleware fails with the following error:\r\n\r\n```\r\n[2020-09-23 11:43:38] production.ERROR: Call to a member function locksFor() on array {\"exception\":\"[object] (Error(code: 0): Call to a member function locksFor() on array at /var/www/html/vendor/illuminate/session/Middleware/StartSession.php:59)\r\n[stacktrace]\r\n#0 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): Illuminate\\\\Session\\\\Middleware\\\\StartSession->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#1 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#2 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#3 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(103): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#4 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(423): Illuminate\\\\Pipeline\\\\Pipeline->then(Object(Closure))\r\n#5 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(260): Laravel\\\\Lumen\\\\Application->sendThroughPipeline(Array, Object(Closure))\r\n#6 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(234): Laravel\\\\Lumen\\\\Application->handleFoundRoute(Array)\r\n#7 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(170): Laravel\\\\Lumen\\\\Application->handleDispatcherResponse(Array)\r\n#8 [internal function]: Laravel\\\\Lumen\\\\Application->Laravel\\\\Lumen\\\\Concerns\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#9 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(48): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#10 /var/www/html/vendor/total-services/core/src/Http/Middleware/LocaleMiddleware.php(33): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#11 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\LocaleMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#12 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#13 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#14 /var/www/html/vendor/total-services/core/src/Http/Middleware/XForwardedPathMiddleware.php(30): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#15 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\XForwardedPathMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#16 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#17 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#18 /var/www/html/vendor/fideloper/proxy/src/TrustProxies.php(57): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#19 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): Fideloper\\\\Proxy\\\\TrustProxies->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#20 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#21 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#22 /var/www/html/vendor/total-services/core/src/Http/Middleware/ConvertStringBooleansMiddleware.php(25): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#23 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\ConvertStringBooleansMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#24 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#25 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#26 /var/www/html/vendor/total-services/core/src/Http/Middleware/ConvertEmptyStringsToNull.php(15): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#27 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\ConvertEmptyStringsToNull->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#28 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#29 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#30 /var/www/html/vendor/total-services/core/src/Http/Middleware/MaintenanceModeMiddleware.php(30): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#31 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\MaintenanceModeMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#32 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#33 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#34 /var/www/html/vendor/total-services/core/src/Http/Middleware/CountryBlockerMiddleware.php(40): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#35 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): TotalServices\\\\Core\\\\Http\\\\Middleware\\\\CountryBlockerMiddleware->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#36 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#37 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#38 /var/www/html/app/Http/Middleware/Cors.php(29): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#39 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(167): App\\\\Http\\\\Middleware\\\\Cors->handle(Object(Laravel\\\\Lumen\\\\Http\\\\Request), Object(Closure))\r\n#40 [internal function]: Illuminate\\\\Pipeline\\\\Pipeline->Illuminate\\\\Pipeline\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#41 /var/www/html/vendor/laravel/lumen-framework/src/Routing/Pipeline.php(30): call_user_func(Object(Closure), Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#42 /var/www/html/vendor/illuminate/pipeline/Pipeline.php(103): Laravel\\\\Lumen\\\\Routing\\\\Pipeline->Laravel\\\\Lumen\\\\Routing\\\\{closure}(Object(Laravel\\\\Lumen\\\\Http\\\\Request))\r\n#43 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(423): Illuminate\\\\Pipeline\\\\Pipeline->then(Object(Closure))\r\n#44 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(172): Laravel\\\\Lumen\\\\Application->sendThroughPipeline(Array, Object(Closure))\r\n#45 /var/www/html/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php(109): Laravel\\\\Lumen\\\\Application->dispatch(NULL)\r\n#46 /var/www/html/public/index.php(17): Laravel\\\\Lumen\\\\Application->run()\r\n#47 {main}\r\n\"} \r\n```\r\n\r\nThe reason is that Laravel\\Lumen\\Http\\Request::route() return `array|null` when Illuminate\\Http\\Request::route() return `Illuminate\\Routing\\Route|object|null`.\r\n", "number": 34491, "review_comments": [], "title": "[8.x] Fix incompatibility with Lumen route function which return an array." }
{ "commits": [ { "message": "🐛 Fix incompatibility with Lumen\n\nLumen $request->route() signature is different from Illuminate\\Http\\Request::route" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n use Closure;\n use Illuminate\\Contracts\\Session\\Session;\n use Illuminate\\Http\\Request;\n+use Illuminate\\Routing\\Route;\n use Illuminate\\Session\\SessionManager;\n use Illuminate\\Support\\Carbon;\n use Illuminate\\Support\\Facades\\Date;\n@@ -56,7 +57,7 @@ public function handle($request, Closure $next)\n $session = $this->getSession($request);\n \n if ($this->manager->shouldBlock() ||\n- ($request->route() && $request->route()->locksFor())) {\n+ ($request->route() instanceof Route && $request->route()->locksFor())) {\n return $this->handleRequestWhileBlocking($request, $session, $next);\n } else {\n return $this->handleStatefulRequest($request, $session, $next);\n@@ -73,6 +74,10 @@ public function handle($request, Closure $next)\n */\n protected function handleRequestWhileBlocking(Request $request, $session, Closure $next)\n {\n+ if (! $request->route() instanceof Route) {\n+ return;\n+ }\n+\n $lockFor = $request->route() && $request->route()->locksFor()\n ? $request->route()->locksFor()\n : 10;\n@@ -195,7 +200,7 @@ protected function configHitsLottery(array $config)\n protected function storeCurrentUrl(Request $request, $session)\n {\n if ($request->method() === 'GET' &&\n- $request->route() &&\n+ $request->route() instanceof Route &&\n ! $request->ajax() &&\n ! $request->prefetch()) {\n $session->setPreviousUrl($request->fullUrl());", "filename": "src/Illuminate/Session/Middleware/StartSession.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": " Log file \r\n\r\n [2020-09-09 17:06:14] local.ERROR: syntax error, unexpected ')' {\r\n\"exception\":\"[object] (ParseError(code: 0): syntax error, unexpected ')' \r\nat /var/www/laravel8/vendor/laravel/framework/src/Illuminate/Bus/BusServiceProvider.php:51)\r\n[stacktrace]\r\n#0 /var/www/laravel8/vendor/composer/ClassLoader.php(322): Composer\\\\Autoload\\\\includeFile('/var/www/larave...')\r\n#1 [internal function]: Composer\\\\Autoload\\\\ClassLoader->loadClass('Illuminate\\\\\\\\Bus\\\\\\\\...')\r\n#2 /var/www/laravel8/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(761): spl_autoload_call('Illuminate\\\\\\\\Bus\\\\\\\\...')\r\n#3 /var/www/laravel8/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(741): Illuminate\\\\Foundation\\\\Application->registerDeferredProvider('Illuminate\\\\\\\\Bus\\\\\\\\...', 'Illuminate\\\\\\\\Bus\\\\\\\\...')\r\n#4 /var/www/laravel8/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(717): Illuminate\\\\Foundation\\\\Application->loadDeferredProvider('Illuminate\\\\\\\\Bus\\\\\\\\...')\r\n#5 /var/www/laravel8/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(313): Illuminate\\\\Foundation\\\\Application->loadDeferredProviders()\r\n#6 /var/www/laravel8/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(127): Illuminate\\\\Foundation\\\\Console\\\\Kernel->bootstrap()\r\n#7 Command line code(1): Illuminate\\\\Foundation\\\\Console\\\\Kernel->handle(Object(Symfony\\\\Component\\\\Console\\\\Input\\\\ArgvInput), Object(Symfony\\\\Component\\\\Console\\\\Output\\\\ConsoleOutput))\r\n#8 {main}\r\n\"} \r\n\r\n\r\n----\r\nOn line 50 at vendor/laravel/framework/src/Illuminate/Bus/BusServiceProvider.php\r\n there is \",\" more\r\n\r\n protected function registerBatchServices()\r\n {\r\n $this->app->singleton(BatchRepository::class, DatabaseBatchRepository::class);\r\n\r\n $this->app->singleton(DatabaseBatchRepository::class, function ($app) {\r\n return new DatabaseBatchRepository(\r\n $app->make(BatchFactory::class),\r\n $app->make('db')->connection(config('queue.batching.database')),\r\n config('queue.batching.table', 'job_batches'),\r\n );\r\n });\r\n }", "number": 34234, "review_comments": [], "title": "Trailing comma in function calls" }
{ "commits": [ { "message": " update dockblock" }, { "message": "Remove unnecessary comma" }, { "message": "Merge pull request #34106 from hnassr/patch-1\n\nRemove additional comma" }, { "message": "Merge branch '8.x' into master" }, { "message": "Fixed current branch variable" }, { "message": "Bumped version to 9" }, { "message": "Merge pull request #34120 from laravel/bump\n\n[9.x] Bumped version to 9" }, { "message": "Update PHPUnit and Testbench (#34122)" }, { "message": "Merge branch '8.x' into master" }, { "message": "fix conflicts" } ], "files": [ { "diff": "@@ -10,7 +10,7 @@ then\n exit 1\n fi\n \n-RELEASE_BRANCH=\"8.x\"\n+RELEASE_BRANCH=\"master\"\n CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)\n VERSION=$1\n ", "filename": "bin/release.sh", "status": "modified" }, { "diff": "@@ -3,7 +3,7 @@\n set -e\n set -x\n \n-CURRENT_BRANCH=\"8.x\"\n+CURRENT_BRANCH=\"master\"\n \n function split()\n {", "filename": "bin/split.sh", "status": "modified" }, { "diff": "@@ -84,9 +84,9 @@\n \"guzzlehttp/guzzle\": \"^6.5.5|^7.0.1\",\n \"league/flysystem-cached-adapter\": \"^1.0\",\n \"mockery/mockery\": \"^1.3.1\",\n- \"orchestra/testbench-core\": \"^6.0\",\n+ \"orchestra/testbench-core\": \"^7.0\",\n \"pda/pheanstalk\": \"^4.0\",\n- \"phpunit/phpunit\": \"^8.4|^9.0\",\n+ \"phpunit/phpunit\": \"^9.0\",\n \"predis/predis\": \"^1.1.1\",\n \"symfony/cache\": \"^5.1\"\n },\n@@ -118,7 +118,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {", "filename": "composer.json", "status": "modified" }, { "diff": "@@ -15,12 +15,12 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/http\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/queue\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/http\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/queue\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -29,13 +29,13 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/console\": \"Required to use the auth:clear-resets command (^8.0).\",\n- \"illuminate/queue\": \"Required to fire login / logout events (^8.0).\",\n- \"illuminate/session\": \"Required to use the session based guard (^8.0).\"\n+ \"illuminate/console\": \"Required to use the auth:clear-resets command (^9.0).\",\n+ \"illuminate/queue\": \"Required to fire login / logout events (^9.0).\",\n+ \"illuminate/session\": \"Required to use the session based guard (^9.0).\"\n },\n \"config\": {\n \"sort-packages\": true", "filename": "src/Illuminate/Auth/composer.json", "status": "modified" }, { "diff": "@@ -17,11 +17,11 @@\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n \"psr/log\": \"^1.0\",\n- \"illuminate/bus\": \"^8.0\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/queue\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/bus\": \"^9.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/queue\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -30,7 +30,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {", "filename": "src/Illuminate/Broadcasting/composer.json", "status": "modified" }, { "diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/pipeline\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/pipeline\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -27,7 +27,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {", "filename": "src/Illuminate/Bus/composer.json", "status": "modified" }, { "diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -27,14 +27,14 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n \"ext-memcached\": \"Required to use the memcache cache driver.\",\n- \"illuminate/database\": \"Required to use the database cache driver (^8.0).\",\n- \"illuminate/filesystem\": \"Required to use the file cache driver (^8.0).\",\n- \"illuminate/redis\": \"Required to use the redis cache driver (^8.0).\",\n+ \"illuminate/database\": \"Required to use the database cache driver (^9.0).\",\n+ \"illuminate/filesystem\": \"Required to use the file cache driver (^9.0).\",\n+ \"illuminate/redis\": \"Required to use the redis cache driver (^9.0).\",\n \"symfony/cache\": \"Required to PSR-6 cache bridge (^5.1).\"\n },\n \"config\": {", "filename": "src/Illuminate/Cache/composer.json", "status": "modified" }, { "diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\"\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Collections/composer.json", "status": "modified" }, { "diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\"\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Config/composer.json", "status": "modified" }, { "diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/console\": \"^5.1\",\n \"symfony/process\": \"^5.1\"\n },\n@@ -29,16 +29,16 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n \"dragonmantank/cron-expression\": \"Required to use scheduler (^3.0).\",\n \"guzzlehttp/guzzle\": \"Required to use the ping methods on schedules (^6.5.5|^7.0.1).\",\n- \"illuminate/bus\": \"Required to use the scheduled job dispatcher (^8.0).\",\n- \"illuminate/container\": \"Required to use the scheduler (^8.0).\",\n- \"illuminate/filesystem\": \"Required to use the generator command (^8.0).\",\n- \"illuminate/queue\": \"Required to use closures for scheduled jobs (^8.0).\"\n+ \"illuminate/bus\": \"Required to use the scheduled job dispatcher (^9.0).\",\n+ \"illuminate/container\": \"Required to use the scheduler (^9.0).\",\n+ \"illuminate/filesystem\": \"Required to use the generator command (^9.0).\",\n+ \"illuminate/queue\": \"Required to use closures for scheduled jobs (^9.0).\"\n },\n \"config\": {\n \"sort-packages\": true", "filename": "src/Illuminate/Console/composer.json", "status": "modified" }, { "diff": "@@ -15,7 +15,7 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/contracts\": \"^8.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n \"psr/container\": \"^1.0\"\n },\n \"provide\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Container/composer.json", "status": "modified" }, { "diff": "@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Contracts/composer.json", "status": "modified" }, { "diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/http-foundation\": \"^5.1\",\n \"symfony/http-kernel\": \"^5.1\"\n },\n@@ -29,7 +29,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Cookie/composer.json", "status": "modified" }, { "diff": "@@ -17,11 +17,11 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/container\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/container\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/console\": \"^5.1\"\n },\n \"autoload\": {\n@@ -31,16 +31,16 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n \"doctrine/dbal\": \"Required to rename columns and drop SQLite columns (^2.6).\",\n \"fzaninotto/faker\": \"Required to use the eloquent factory builder (^1.9.1).\",\n- \"illuminate/console\": \"Required to use the database commands (^8.0).\",\n- \"illuminate/events\": \"Required to use the observers with Eloquent (^8.0).\",\n- \"illuminate/filesystem\": \"Required to use the migrations (^8.0).\",\n- \"illuminate/pagination\": \"Required to paginate the result set (^8.0).\",\n+ \"illuminate/console\": \"Required to use the database commands (^9.0).\",\n+ \"illuminate/events\": \"Required to use the observers with Eloquent (^9.0).\",\n+ \"illuminate/filesystem\": \"Required to use the migrations (^9.0).\",\n+ \"illuminate/pagination\": \"Required to paginate the result set (^9.0).\",\n \"symfony/finder\": \"Required to use Eloquent model factories (^5.1).\"\n },\n \"config\": {", "filename": "src/Illuminate/Database/composer.json", "status": "modified" }, { "diff": "@@ -18,8 +18,8 @@\n \"ext-json\": \"*\",\n \"ext-mbstring\": \"*\",\n \"ext-openssl\": \"*\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Encryption/composer.json", "status": "modified" }, { "diff": "@@ -15,12 +15,12 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/bus\": \"^8.0\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/container\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/bus\": \"^9.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/container\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -32,7 +32,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Events/composer.json", "status": "modified" }, { "diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/finder\": \"^5.1\"\n },\n \"autoload\": {\n@@ -28,7 +28,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {", "filename": "src/Illuminate/Filesystem/composer.json", "status": "modified" }, { "diff": "@@ -33,7 +33,7 @@ class Application extends Container implements ApplicationContract, CachesConfig\n *\n * @var string\n */\n- const VERSION = '8.0.2';\n+ const VERSION = '9.x-dev';\n \n /**\n * The base path for the Laravel installation.", "filename": "src/Illuminate/Foundation/Application.php", "status": "modified" }, { "diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Hashing/composer.json", "status": "modified" }, { "diff": "@@ -16,10 +16,10 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/session\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/session\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/http-foundation\": \"^5.1\",\n \"symfony/http-kernel\": \"^5.1\",\n \"symfony/mime\": \"^5.1\"\n@@ -35,7 +35,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Http/composer.json", "status": "modified" }, { "diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"monolog/monolog\": \"^2.0\"\n },\n \"autoload\": {\n@@ -26,7 +26,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Log/composer.json", "status": "modified" }, { "diff": "@@ -23,7 +23,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Macroable/composer.json", "status": "modified" }, { "diff": "@@ -16,11 +16,11 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/container\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/container\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"league/commonmark\": \"^1.3\",\n \"psr/log\": \"^1.0\",\n \"swiftmailer/swiftmailer\": \"^6.0\",\n@@ -33,7 +33,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {", "filename": "src/Illuminate/Mail/composer.json", "status": "modified" }, { "diff": "@@ -15,15 +15,15 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/broadcasting\": \"^8.0\",\n- \"illuminate/bus\": \"^8.0\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/container\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/filesystem\": \"^8.0\",\n- \"illuminate/mail\": \"^8.0\",\n- \"illuminate/queue\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/broadcasting\": \"^9.0\",\n+ \"illuminate/bus\": \"^9.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/container\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/filesystem\": \"^9.0\",\n+ \"illuminate/mail\": \"^9.0\",\n+ \"illuminate/queue\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -32,11 +32,11 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/database\": \"Required to use the database transport (^8.0).\"\n+ \"illuminate/database\": \"Required to use the database transport (^9.0).\"\n },\n \"config\": {\n \"sort-packages\": true", "filename": "src/Illuminate/Notifications/composer.json", "status": "modified" }, { "diff": "@@ -16,9 +16,9 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -27,7 +27,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Pagination/composer.json", "status": "modified" }, { "diff": "@@ -15,8 +15,8 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -25,7 +25,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Pipeline/composer.json", "status": "modified" }, { "diff": "@@ -16,14 +16,14 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/console\": \"^8.0\",\n- \"illuminate/container\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/database\": \"^8.0\",\n- \"illuminate/filesystem\": \"^8.0\",\n- \"illuminate/pipeline\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/console\": \"^9.0\",\n+ \"illuminate/container\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/database\": \"^9.0\",\n+ \"illuminate/filesystem\": \"^9.0\",\n+ \"illuminate/pipeline\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"opis/closure\": \"^3.5.3\",\n \"ramsey/uuid\": \"^4.0\",\n \"symfony/process\": \"^5.1\"\n@@ -35,14 +35,14 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n \"ext-pcntl\": \"Required to use all features of the queue worker.\",\n \"ext-posix\": \"Required to use all features of the queue worker.\",\n \"aws/aws-sdk-php\": \"Required to use the SQS queue driver and DynamoDb failed job storage (^3.0).\",\n- \"illuminate/redis\": \"Required to use the Redis queue driver (^8.0).\",\n+ \"illuminate/redis\": \"Required to use the Redis queue driver (^9.0).\",\n \"pda/pheanstalk\": \"Required to use the Beanstalk queue driver (^4.0).\"\n },\n \"config\": {", "filename": "src/Illuminate/Queue/composer.json", "status": "modified" }, { "diff": "@@ -15,10 +15,10 @@\n ],\n \"require\": {\n \"php\": \"^7.3\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\"\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -31,7 +31,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Redis/composer.json", "status": "modified" }, { "diff": "@@ -16,14 +16,14 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/container\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/http\": \"^8.0\",\n- \"illuminate/macroable\": \"^8.0\",\n- \"illuminate/pipeline\": \"^8.0\",\n- \"illuminate/session\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/container\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/http\": \"^9.0\",\n+ \"illuminate/macroable\": \"^9.0\",\n+ \"illuminate/pipeline\": \"^9.0\",\n+ \"illuminate/session\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/http-foundation\": \"^5.1\",\n \"symfony/http-kernel\": \"^5.1\",\n \"symfony/routing\": \"^5.1\"\n@@ -35,11 +35,11 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/console\": \"Required to use the make commands (^8.0).\",\n+ \"illuminate/console\": \"Required to use the make commands (^9.0).\",\n \"nyholm/psr7\": \"Required to use PSR-7 bridging features (^1.2).\",\n \"symfony/psr-http-message-bridge\": \"Required to use PSR-7 bridging features (^2.0).\"\n },", "filename": "src/Illuminate/Routing/composer.json", "status": "modified" }, { "diff": "@@ -16,10 +16,10 @@\n \"require\": {\n \"php\": \"^7.3\",\n \"ext-json\": \"*\",\n- \"illuminate/collections\": \"^8.0\",\n- \"illuminate/contracts\": \"^8.0\",\n- \"illuminate/filesystem\": \"^8.0\",\n- \"illuminate/support\": \"^8.0\",\n+ \"illuminate/collections\": \"^9.0\",\n+ \"illuminate/contracts\": \"^9.0\",\n+ \"illuminate/filesystem\": \"^9.0\",\n+ \"illuminate/support\": \"^9.0\",\n \"symfony/finder\": \"^5.1\",\n \"symfony/http-foundation\": \"^5.1\"\n },\n@@ -30,11 +30,11 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"8.x-dev\"\n+ \"dev-master\": \"9.x-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/console\": \"Required to use the session:table command (^8.0).\"\n+ \"illuminate/console\": \"Required to use the session:table command (^9.0).\"\n },\n \"config\": {\n \"sort-packages\": true", "filename": "src/Illuminate/Session/composer.json", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.0.0\r\n- PHP Version: 7.4.*\r\n- Database Driver & Version: mysqldump 8 and mysqld 5.7\r\n\r\n### Description:\r\nexecuting :\r\n```\r\nphp artisan schema:dump\r\n```\r\nI receive an error\r\n\r\n```\r\nmysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, '$.\"number-of-buckets-specified\"') FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = 'db_laravel_8' AND TABLE_NAME = 'failed_jobs';': Unknown table 'column_statistics' in information_schema (1109)\r\n```\r\ndue to the different version mysqldump 8 against an older mysql daemon 5.7.\r\nschema:dump execute mysqldump local command. The version 8 has the flag column-statistics set as 1 (true) by default. mysql5.7 could not have \"information_schema.COLUMN_STATISTICS\".\r\n\r\n\r\n### Steps To Reproduce:\r\nIn a envirnoment where you have mysqldump 8 and mysql5.7 execute php artisan schema:dump\r\n\r\n### Fix\r\n- In baseDumpCommand() (MySqlSchemaState.php) add option column-statistic=0\r\n```\r\n protected function baseDumpCommand()\r\n {\r\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\r\n $statisticOff = \" --column-statistics=0 \";\r\n return 'mysqldump ' . $statisticOff . ''.$gtidPurged.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\r\n }\r\n```\r\n", "comments": [ { "body": "Do you want to PR your fix?", "created_at": "2020-08-31T20:03:08Z" }, { "body": "Sure!", "created_at": "2020-08-31T20:06:21Z" }, { "body": "I submitted the PR : #34079 ", "created_at": "2020-08-31T21:06:26Z" }, { "body": "mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\nI got this error when try to run php artisan schema:dump", "created_at": "2020-09-03T09:40:06Z" }, { "body": "@vanthao03596 which database driver and version are you running?", "created_at": "2020-09-03T09:41:24Z" }, { "body": "> mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\n> I got this error when try to run php artisan schema:dump\r\n\r\n@vanthao03596 Which version of mysqldump ? mysqldump --version\r\n", "created_at": "2020-09-03T09:43:38Z" }, { "body": "I replicated the error.\r\nWith mysql-client (mysqldump) 8 , column-statistics is supported;\r\nwith mysql-client (mysqldump) 5.7, column statistic is NOT supported.\r\n\r\nUsing column-statistics=0, it allows to use mysqdump8 with a mysql5.7(server)\r\nUsing column-statistcis=0 fails with mysqldump5.7\r\n\r\nPossible solutions that I have in mind:\r\n- avoid to use column-statistics by default, and add a option in schema:dump (for example disable-statistic)\r\n- try to do some \"magic\": executing mysqldump without column-statistci, if it fails, try with column-statisctics.\r\n\r\nI like more the first one.\r\n\r\n\r\n", "created_at": "2020-09-03T10:15:11Z" }, { "body": "@roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n", "created_at": "2020-09-03T10:46:54Z" }, { "body": "@roberto-butti so it seems it's not just mysql 5.7", "created_at": "2020-09-03T10:48:56Z" }, { "body": "> @roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n> ![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n\r\n@vanthao03596 just to clarify, \r\nmysqldump is version 5.7.30 and the mysql database service is 8.0.2. Is it correct ?\r\n\r\n@driesvints do you want i add a option in DumpCommand to allow the user to \"disable\" statistics and force (--column-statistics=0) only.\r\nThe parameter could be column-statistics-off, or something similar. \r\nI could create a PR in my break lunch or this evening.\r\n", "created_at": "2020-09-03T11:05:06Z" }, { "body": "I think you'd want statistics off by default? The migrations are only meant for your DB structure, nothing else really.", "created_at": "2020-09-03T11:08:15Z" }, { "body": "ok, I agree to keep --column-statistics=0 in the code as default (now we have this, in the latest codebase).\r\nAnd allow to the user to declare in command line to skip column-statistics (with an option) if the user has a old version of mysqldump.\r\n--skip-column-statistics (the name of the option in the signature of the command).\r\nIs it ok for you, @driesvints ?", "created_at": "2020-09-03T11:19:28Z" }, { "body": " I think we need to find a solution where it never faults, on any MySQL version. In which specific situations does it fail now?", "created_at": "2020-09-03T11:21:11Z" }, { "body": "As far as i know on mysqldump 5.7 it fails bacause it doesn't support column-statistics=0 .\r\nIt is quite a common problem on backup software that rely on mysqldump. I see that lot of them has the option in the configuration to set or not the column-statistics.\r\nI'm courious to see if also DbDumper of Spatie has the same problem...", "created_at": "2020-09-03T11:29:47Z" }, { "body": "Is there any way we can check for the MySQL version in that command to not use the flag when it's 5.7?", "created_at": "2020-09-03T11:36:45Z" }, { "body": "I mean mysqldump 5.7", "created_at": "2020-09-03T11:37:01Z" }, { "body": "As far as i know we have mysqldump --version.\r\nBut the output is differente based on the version , the build and the architecture.\r\nFor mysqldump 8 :\r\n```\r\nmysqldump Ver 8.0.19 for osx10.15 on x86_64 (Homebrew)\r\n```\r\nor, for mysqldump 5.7:\r\n```\r\nmysqldump Ver 10.13 Distrib 5.7.29, for osx10.15 (x86_64)\r\n```\r\nSee _Ver_ and the _Distrib_.\r\nSo I think that we can't rely on the version output.\r\n", "created_at": "2020-09-03T12:13:56Z" }, { "body": "We could just state that the feature requires a certain version of mysqldump?", "created_at": "2020-09-03T12:53:41Z" }, { "body": "Sure @taylorotwell . \r\nAt this point my suggestion is : \r\nthe requirements is to have mysqldump version 8.\r\n\r\nMy additional suggestion is , for the user with an older version of mysqldump, allow them to use and additional option in command line, and allow them to use the feature schema:dump (is a kind of \"legacy\" option). What do you think ?\r\n", "created_at": "2020-09-03T13:07:21Z" }, { "body": "@roberto-butti mysqldump5.7 is installed in my local machine, mysql 8 is running in docker.", "created_at": "2020-09-03T14:18:19Z" }, { "body": "I'm going to release a PR, if you agree.\r\n\r\nI think that i'm covering all scenarios.\r\nLet me know what do you think ab out this proposal.\r\n\r\nThe only thing requested by the user for not having errors, is to force the user to use the option --column-statistics-off in the condition with mysqldump 8 and mysqld 5.7.\r\nConsidering that is an edge case, the great library of spatie DbDumper it doesn't support this scenario (i think that i will drop a PR also for that package).\r\n\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\n", "created_at": "2020-09-03T17:09:02Z" }, { "body": "Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.", "created_at": "2020-09-03T17:10:42Z" }, { "body": "> Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.\r\n\r\nCurrently I'm not able to determine a reliable way to identify exactly the version :(", "created_at": "2020-09-03T17:20:48Z" }, { "body": "PR #34125 \r\nTested with:\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\nTested also with Posgtres connection (pg_dump) with php artisan schema:dump\r\n\r\n\r\n", "created_at": "2020-09-03T20:33:30Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961490-9e9f6600-252b-11eb-8a05-752812995747.png)\r\n", "created_at": "2020-11-12T15:41:29Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961543-aeb74580-252b-11eb-8a1c-ae75cd6c2f08.png)\r\nand the file is .dump not .sql ?", "created_at": "2020-11-12T15:42:02Z" }, { "body": "I know this is closed but my solution on ubuntu 20.04 was to do the following : \r\n```\r\napt remove mysql-client\r\napt install mariadb-client\r\n\r\n```\r\nMake sure you use the client made for your mysql server type.", "created_at": "2021-10-14T17:00:55Z" } ], "number": 34078, "title": "php artisan schema:dump error (mysqldump8 and mysqld 5.7)" }
{ "body": "#34078 \r\n\r\nI'm creating a new PR on the 8.x branch instead of master as requested by @GrahamCampbell and @driesvints \r\n\r\n", "number": 34140, "review_comments": [ { "body": "Missing phpdoc.", "created_at": "2020-09-04T14:20:44Z" }, { "body": "Don't need brackets.", "created_at": "2020-09-04T14:21:03Z" } ], "title": "[8.x] Add skip Column Statistics for php artisan schema:dump" }
{ "commits": [ { "message": "Add skip Column Statistics for php artisan schema:dump\n\n#34078" }, { "message": "schema:dump, check if the error message contains column_statistics" }, { "message": "fix styles" }, { "message": "fix style" }, { "message": "Merge branch '8.x' of https://github.com/laravel/framework into 8.x" }, { "message": "adding check for column statistics also for appendMigrationData()" }, { "message": "Update MySqlSchemaState for Style CI" }, { "message": "Update MySqlSchemaState for Style CI" }, { "message": "Update MySqlSchemaState for Style CI" } ], "files": [ { "diff": "@@ -2,21 +2,54 @@\n \n namespace Illuminate\\Database\\Schema;\n \n+use Illuminate\\Support\\Str;\n+\n class MySqlSchemaState extends SchemaState\n {\n /**\n- * Dump the database's schema into a file.\n- *\n- * @param string $path\n- * @return void\n+ * Keep track if it is needed to turn on the statistics.\n+ * @var bool\n */\n- public function dump($path)\n+ public $columnStatisticsOff = false;\n+\n+ /**\n+ * Make the process and run it for dumping the schema.\n+ * @param $path\n+ */\n+ private function makeDumpProcess($path)\n {\n $this->makeProcess(\n $this->baseDumpCommand().' --routines --result-file=$LARAVEL_LOAD_PATH --no-data'\n )->mustRun($this->output, array_merge($this->baseVariables($this->connection->getConfig()), [\n 'LARAVEL_LOAD_PATH' => $path,\n ]));\n+ }\n+\n+ /**\n+ * @param \\Exception $e\n+ * @return bool\n+ */\n+ private function isColumnStatisticsIssue(\\Exception $e)\n+ {\n+ return Str::contains($e->getMessage(), 'column_statistics');\n+ }\n+\n+ /**\n+ * Dump the database's schema into a file.\n+ *\n+ * @param string $path\n+ * @return void\n+ */\n+ public function dump($path)\n+ {\n+ try {\n+ $this->makeDumpProcess($path);\n+ } catch (\\Exception $e) {\n+ if ($this->isColumnStatisticsIssue($e)) {\n+ $this->columnStatisticsOff = true;\n+ $this->makeDumpProcess($path);\n+ }\n+ }\n \n $this->removeAutoIncrementingState($path);\n \n@@ -39,20 +72,39 @@ protected function removeAutoIncrementingState(string $path)\n }\n \n /**\n- * Append the migration data to the schema dump.\n- *\n- * @param string $path\n- * @return void\n+ * @return \\Symfony\\Component\\Process\\Process\n */\n- protected function appendMigrationData(string $path)\n+ private function makeMigrationProcess()\n {\n with($process = $this->makeProcess(\n $this->baseDumpCommand().' migrations --no-create-info --skip-extended-insert --skip-routines --compact'\n ))->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [\n //\n ]));\n \n- $this->files->append($path, $process->getOutput());\n+ return $process;\n+ }\n+\n+ /**\n+ * Append the migration data to the schema dump.\n+ *\n+ * @param string $path\n+ * @return void\n+ */\n+ protected function appendMigrationData(string $path)\n+ {\n+ $process = null;\n+ try {\n+ $process = $this->makeMigrationProcess();\n+ } catch (\\Exception $e) {\n+ if ($this->isColumnStatisticsIssue($e) && ! $this->columnStatisticsOff) {\n+ $this->columnStatisticsOff = true;\n+ $process = $this->makeMigrationProcess();\n+ }\n+ }\n+ if (! is_null($process)) {\n+ $this->files->append($path, $process->getOutput());\n+ }\n }\n \n /**\n@@ -78,8 +130,9 @@ public function load($path)\n protected function baseDumpCommand()\n {\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\n+ $columnStatisticsOption = $this->columnStatisticsOff ? ' --column-statistics=0' : '';\n \n- return 'mysqldump '.$gtidPurged.' --column-statistics=0 --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n+ return 'mysqldump '.$gtidPurged.$columnStatisticsOption.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/MySqlSchemaState.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.0.0\r\n- PHP Version: 7.4.*\r\n- Database Driver & Version: mysqldump 8 and mysqld 5.7\r\n\r\n### Description:\r\nexecuting :\r\n```\r\nphp artisan schema:dump\r\n```\r\nI receive an error\r\n\r\n```\r\nmysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, '$.\"number-of-buckets-specified\"') FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = 'db_laravel_8' AND TABLE_NAME = 'failed_jobs';': Unknown table 'column_statistics' in information_schema (1109)\r\n```\r\ndue to the different version mysqldump 8 against an older mysql daemon 5.7.\r\nschema:dump execute mysqldump local command. The version 8 has the flag column-statistics set as 1 (true) by default. mysql5.7 could not have \"information_schema.COLUMN_STATISTICS\".\r\n\r\n\r\n### Steps To Reproduce:\r\nIn a envirnoment where you have mysqldump 8 and mysql5.7 execute php artisan schema:dump\r\n\r\n### Fix\r\n- In baseDumpCommand() (MySqlSchemaState.php) add option column-statistic=0\r\n```\r\n protected function baseDumpCommand()\r\n {\r\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\r\n $statisticOff = \" --column-statistics=0 \";\r\n return 'mysqldump ' . $statisticOff . ''.$gtidPurged.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\r\n }\r\n```\r\n", "comments": [ { "body": "Do you want to PR your fix?", "created_at": "2020-08-31T20:03:08Z" }, { "body": "Sure!", "created_at": "2020-08-31T20:06:21Z" }, { "body": "I submitted the PR : #34079 ", "created_at": "2020-08-31T21:06:26Z" }, { "body": "mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\nI got this error when try to run php artisan schema:dump", "created_at": "2020-09-03T09:40:06Z" }, { "body": "@vanthao03596 which database driver and version are you running?", "created_at": "2020-09-03T09:41:24Z" }, { "body": "> mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\n> I got this error when try to run php artisan schema:dump\r\n\r\n@vanthao03596 Which version of mysqldump ? mysqldump --version\r\n", "created_at": "2020-09-03T09:43:38Z" }, { "body": "I replicated the error.\r\nWith mysql-client (mysqldump) 8 , column-statistics is supported;\r\nwith mysql-client (mysqldump) 5.7, column statistic is NOT supported.\r\n\r\nUsing column-statistics=0, it allows to use mysqdump8 with a mysql5.7(server)\r\nUsing column-statistcis=0 fails with mysqldump5.7\r\n\r\nPossible solutions that I have in mind:\r\n- avoid to use column-statistics by default, and add a option in schema:dump (for example disable-statistic)\r\n- try to do some \"magic\": executing mysqldump without column-statistci, if it fails, try with column-statisctics.\r\n\r\nI like more the first one.\r\n\r\n\r\n", "created_at": "2020-09-03T10:15:11Z" }, { "body": "@roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n", "created_at": "2020-09-03T10:46:54Z" }, { "body": "@roberto-butti so it seems it's not just mysql 5.7", "created_at": "2020-09-03T10:48:56Z" }, { "body": "> @roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n> ![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n\r\n@vanthao03596 just to clarify, \r\nmysqldump is version 5.7.30 and the mysql database service is 8.0.2. Is it correct ?\r\n\r\n@driesvints do you want i add a option in DumpCommand to allow the user to \"disable\" statistics and force (--column-statistics=0) only.\r\nThe parameter could be column-statistics-off, or something similar. \r\nI could create a PR in my break lunch or this evening.\r\n", "created_at": "2020-09-03T11:05:06Z" }, { "body": "I think you'd want statistics off by default? The migrations are only meant for your DB structure, nothing else really.", "created_at": "2020-09-03T11:08:15Z" }, { "body": "ok, I agree to keep --column-statistics=0 in the code as default (now we have this, in the latest codebase).\r\nAnd allow to the user to declare in command line to skip column-statistics (with an option) if the user has a old version of mysqldump.\r\n--skip-column-statistics (the name of the option in the signature of the command).\r\nIs it ok for you, @driesvints ?", "created_at": "2020-09-03T11:19:28Z" }, { "body": " I think we need to find a solution where it never faults, on any MySQL version. In which specific situations does it fail now?", "created_at": "2020-09-03T11:21:11Z" }, { "body": "As far as i know on mysqldump 5.7 it fails bacause it doesn't support column-statistics=0 .\r\nIt is quite a common problem on backup software that rely on mysqldump. I see that lot of them has the option in the configuration to set or not the column-statistics.\r\nI'm courious to see if also DbDumper of Spatie has the same problem...", "created_at": "2020-09-03T11:29:47Z" }, { "body": "Is there any way we can check for the MySQL version in that command to not use the flag when it's 5.7?", "created_at": "2020-09-03T11:36:45Z" }, { "body": "I mean mysqldump 5.7", "created_at": "2020-09-03T11:37:01Z" }, { "body": "As far as i know we have mysqldump --version.\r\nBut the output is differente based on the version , the build and the architecture.\r\nFor mysqldump 8 :\r\n```\r\nmysqldump Ver 8.0.19 for osx10.15 on x86_64 (Homebrew)\r\n```\r\nor, for mysqldump 5.7:\r\n```\r\nmysqldump Ver 10.13 Distrib 5.7.29, for osx10.15 (x86_64)\r\n```\r\nSee _Ver_ and the _Distrib_.\r\nSo I think that we can't rely on the version output.\r\n", "created_at": "2020-09-03T12:13:56Z" }, { "body": "We could just state that the feature requires a certain version of mysqldump?", "created_at": "2020-09-03T12:53:41Z" }, { "body": "Sure @taylorotwell . \r\nAt this point my suggestion is : \r\nthe requirements is to have mysqldump version 8.\r\n\r\nMy additional suggestion is , for the user with an older version of mysqldump, allow them to use and additional option in command line, and allow them to use the feature schema:dump (is a kind of \"legacy\" option). What do you think ?\r\n", "created_at": "2020-09-03T13:07:21Z" }, { "body": "@roberto-butti mysqldump5.7 is installed in my local machine, mysql 8 is running in docker.", "created_at": "2020-09-03T14:18:19Z" }, { "body": "I'm going to release a PR, if you agree.\r\n\r\nI think that i'm covering all scenarios.\r\nLet me know what do you think ab out this proposal.\r\n\r\nThe only thing requested by the user for not having errors, is to force the user to use the option --column-statistics-off in the condition with mysqldump 8 and mysqld 5.7.\r\nConsidering that is an edge case, the great library of spatie DbDumper it doesn't support this scenario (i think that i will drop a PR also for that package).\r\n\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\n", "created_at": "2020-09-03T17:09:02Z" }, { "body": "Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.", "created_at": "2020-09-03T17:10:42Z" }, { "body": "> Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.\r\n\r\nCurrently I'm not able to determine a reliable way to identify exactly the version :(", "created_at": "2020-09-03T17:20:48Z" }, { "body": "PR #34125 \r\nTested with:\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\nTested also with Posgtres connection (pg_dump) with php artisan schema:dump\r\n\r\n\r\n", "created_at": "2020-09-03T20:33:30Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961490-9e9f6600-252b-11eb-8a05-752812995747.png)\r\n", "created_at": "2020-11-12T15:41:29Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961543-aeb74580-252b-11eb-8a1c-ae75cd6c2f08.png)\r\nand the file is .dump not .sql ?", "created_at": "2020-11-12T15:42:02Z" }, { "body": "I know this is closed but my solution on ubuntu 20.04 was to do the following : \r\n```\r\napt remove mysql-client\r\napt install mariadb-client\r\n\r\n```\r\nMake sure you use the client made for your mysql server type.", "created_at": "2021-10-14T17:00:55Z" } ], "number": 34078, "title": "php artisan schema:dump error (mysqldump8 and mysqld 5.7)" }
{ "body": "In some specific case like mysqldump 8 and mysqlserver version 5.7 the command failed. It is added --column-statistics-off option to mitigate this issue. The issue is : #34078\r\nI'm creating a new PR on the 8.x branch instead of master as requested by @GrahamCampbell", "number": 34133, "review_comments": [], "title": "Adding --column-statistics-off for php artisan schema:dump " }
{ "commits": [ { "message": " update dockblock" }, { "message": "Remove unnecessary comma" }, { "message": "Merge pull request #34106 from hnassr/patch-1\n\nRemove additional comma" }, { "message": "Merge branch '8.x' into master" }, { "message": "Fixed current branch variable" }, { "message": "Adding --column-statistics-off for php artisan schema:dump\n\nIn some specific case like mysqdump 8 and mysqlserver version 5.7 the command failed. It is added --column-statistics-off option to mitigate this issue. The issue is : #34078" }, { "message": "Fix style" }, { "message": "restore release branch" } ], "files": [ { "diff": "@@ -19,7 +19,8 @@ class DumpCommand extends Command\n protected $signature = 'schema:dump\n {--database= : The database connection to use}\n {--path= : The path where the schema dump file should be stored}\n- {--prune : Delete all existing migration files}';\n+ {--prune : Delete all existing migration files}\n+ {--column-statistics-off : use column-statics off in case of mysqldump 8 against mysqld 5.7}';\n \n /**\n * The console command description.\n@@ -35,9 +36,12 @@ class DumpCommand extends Command\n */\n public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher)\n {\n- $this->schemaState(\n+ $schemaState = $this->schemaState(\n $connection = $connections->connection($database = $this->input->getOption('database'))\n- )->dump($path = $this->path($connection));\n+ );\n+ $schemaState->columnStatisticsOff = $this->option('column-statistics-off');\n+\n+ $schemaState->dump($path = $this->path($connection));\n \n $dispatcher->dispatch(new SchemaDumped($connection, $path));\n ", "filename": "src/Illuminate/Database/Console/DumpCommand.php", "status": "modified" }, { "diff": "@@ -4,6 +4,8 @@\n \n class MySqlSchemaState extends SchemaState\n {\n+ public $columnStatisticsOff = false;\n+\n /**\n * Dump the database's schema into a file.\n *\n@@ -78,8 +80,9 @@ public function load($path)\n protected function baseDumpCommand()\n {\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\n+ $columnStatisticsOption = ($this->columnStatisticsOff) ? ' --column-statistics=0' : '';\n \n- return 'mysqldump '.$gtidPurged.' --column-statistics=0 --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n+ return 'mysqldump '.$gtidPurged.$columnStatisticsOption.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/MySqlSchemaState.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.0.0\r\n- PHP Version: 7.4.*\r\n- Database Driver & Version: mysqldump 8 and mysqld 5.7\r\n\r\n### Description:\r\nexecuting :\r\n```\r\nphp artisan schema:dump\r\n```\r\nI receive an error\r\n\r\n```\r\nmysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, '$.\"number-of-buckets-specified\"') FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = 'db_laravel_8' AND TABLE_NAME = 'failed_jobs';': Unknown table 'column_statistics' in information_schema (1109)\r\n```\r\ndue to the different version mysqldump 8 against an older mysql daemon 5.7.\r\nschema:dump execute mysqldump local command. The version 8 has the flag column-statistics set as 1 (true) by default. mysql5.7 could not have \"information_schema.COLUMN_STATISTICS\".\r\n\r\n\r\n### Steps To Reproduce:\r\nIn a envirnoment where you have mysqldump 8 and mysql5.7 execute php artisan schema:dump\r\n\r\n### Fix\r\n- In baseDumpCommand() (MySqlSchemaState.php) add option column-statistic=0\r\n```\r\n protected function baseDumpCommand()\r\n {\r\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\r\n $statisticOff = \" --column-statistics=0 \";\r\n return 'mysqldump ' . $statisticOff . ''.$gtidPurged.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\r\n }\r\n```\r\n", "comments": [ { "body": "Do you want to PR your fix?", "created_at": "2020-08-31T20:03:08Z" }, { "body": "Sure!", "created_at": "2020-08-31T20:06:21Z" }, { "body": "I submitted the PR : #34079 ", "created_at": "2020-08-31T21:06:26Z" }, { "body": "mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\nI got this error when try to run php artisan schema:dump", "created_at": "2020-09-03T09:40:06Z" }, { "body": "@vanthao03596 which database driver and version are you running?", "created_at": "2020-09-03T09:41:24Z" }, { "body": "> mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\n> I got this error when try to run php artisan schema:dump\r\n\r\n@vanthao03596 Which version of mysqldump ? mysqldump --version\r\n", "created_at": "2020-09-03T09:43:38Z" }, { "body": "I replicated the error.\r\nWith mysql-client (mysqldump) 8 , column-statistics is supported;\r\nwith mysql-client (mysqldump) 5.7, column statistic is NOT supported.\r\n\r\nUsing column-statistics=0, it allows to use mysqdump8 with a mysql5.7(server)\r\nUsing column-statistcis=0 fails with mysqldump5.7\r\n\r\nPossible solutions that I have in mind:\r\n- avoid to use column-statistics by default, and add a option in schema:dump (for example disable-statistic)\r\n- try to do some \"magic\": executing mysqldump without column-statistci, if it fails, try with column-statisctics.\r\n\r\nI like more the first one.\r\n\r\n\r\n", "created_at": "2020-09-03T10:15:11Z" }, { "body": "@roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n", "created_at": "2020-09-03T10:46:54Z" }, { "body": "@roberto-butti so it seems it's not just mysql 5.7", "created_at": "2020-09-03T10:48:56Z" }, { "body": "> @roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n> ![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n\r\n@vanthao03596 just to clarify, \r\nmysqldump is version 5.7.30 and the mysql database service is 8.0.2. Is it correct ?\r\n\r\n@driesvints do you want i add a option in DumpCommand to allow the user to \"disable\" statistics and force (--column-statistics=0) only.\r\nThe parameter could be column-statistics-off, or something similar. \r\nI could create a PR in my break lunch or this evening.\r\n", "created_at": "2020-09-03T11:05:06Z" }, { "body": "I think you'd want statistics off by default? The migrations are only meant for your DB structure, nothing else really.", "created_at": "2020-09-03T11:08:15Z" }, { "body": "ok, I agree to keep --column-statistics=0 in the code as default (now we have this, in the latest codebase).\r\nAnd allow to the user to declare in command line to skip column-statistics (with an option) if the user has a old version of mysqldump.\r\n--skip-column-statistics (the name of the option in the signature of the command).\r\nIs it ok for you, @driesvints ?", "created_at": "2020-09-03T11:19:28Z" }, { "body": " I think we need to find a solution where it never faults, on any MySQL version. In which specific situations does it fail now?", "created_at": "2020-09-03T11:21:11Z" }, { "body": "As far as i know on mysqldump 5.7 it fails bacause it doesn't support column-statistics=0 .\r\nIt is quite a common problem on backup software that rely on mysqldump. I see that lot of them has the option in the configuration to set or not the column-statistics.\r\nI'm courious to see if also DbDumper of Spatie has the same problem...", "created_at": "2020-09-03T11:29:47Z" }, { "body": "Is there any way we can check for the MySQL version in that command to not use the flag when it's 5.7?", "created_at": "2020-09-03T11:36:45Z" }, { "body": "I mean mysqldump 5.7", "created_at": "2020-09-03T11:37:01Z" }, { "body": "As far as i know we have mysqldump --version.\r\nBut the output is differente based on the version , the build and the architecture.\r\nFor mysqldump 8 :\r\n```\r\nmysqldump Ver 8.0.19 for osx10.15 on x86_64 (Homebrew)\r\n```\r\nor, for mysqldump 5.7:\r\n```\r\nmysqldump Ver 10.13 Distrib 5.7.29, for osx10.15 (x86_64)\r\n```\r\nSee _Ver_ and the _Distrib_.\r\nSo I think that we can't rely on the version output.\r\n", "created_at": "2020-09-03T12:13:56Z" }, { "body": "We could just state that the feature requires a certain version of mysqldump?", "created_at": "2020-09-03T12:53:41Z" }, { "body": "Sure @taylorotwell . \r\nAt this point my suggestion is : \r\nthe requirements is to have mysqldump version 8.\r\n\r\nMy additional suggestion is , for the user with an older version of mysqldump, allow them to use and additional option in command line, and allow them to use the feature schema:dump (is a kind of \"legacy\" option). What do you think ?\r\n", "created_at": "2020-09-03T13:07:21Z" }, { "body": "@roberto-butti mysqldump5.7 is installed in my local machine, mysql 8 is running in docker.", "created_at": "2020-09-03T14:18:19Z" }, { "body": "I'm going to release a PR, if you agree.\r\n\r\nI think that i'm covering all scenarios.\r\nLet me know what do you think ab out this proposal.\r\n\r\nThe only thing requested by the user for not having errors, is to force the user to use the option --column-statistics-off in the condition with mysqldump 8 and mysqld 5.7.\r\nConsidering that is an edge case, the great library of spatie DbDumper it doesn't support this scenario (i think that i will drop a PR also for that package).\r\n\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\n", "created_at": "2020-09-03T17:09:02Z" }, { "body": "Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.", "created_at": "2020-09-03T17:10:42Z" }, { "body": "> Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.\r\n\r\nCurrently I'm not able to determine a reliable way to identify exactly the version :(", "created_at": "2020-09-03T17:20:48Z" }, { "body": "PR #34125 \r\nTested with:\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\nTested also with Posgtres connection (pg_dump) with php artisan schema:dump\r\n\r\n\r\n", "created_at": "2020-09-03T20:33:30Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961490-9e9f6600-252b-11eb-8a05-752812995747.png)\r\n", "created_at": "2020-11-12T15:41:29Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961543-aeb74580-252b-11eb-8a1c-ae75cd6c2f08.png)\r\nand the file is .dump not .sql ?", "created_at": "2020-11-12T15:42:02Z" }, { "body": "I know this is closed but my solution on ubuntu 20.04 was to do the following : \r\n```\r\napt remove mysql-client\r\napt install mariadb-client\r\n\r\n```\r\nMake sure you use the client made for your mysql server type.", "created_at": "2021-10-14T17:00:55Z" } ], "number": 34078, "title": "php artisan schema:dump error (mysqldump8 and mysqld 5.7)" }
{ "body": "In some specific case like mysqldump 8 and mysqlserver version 5.7 the command failed. It is added --column-statistics-off option to mitigate this issue. The issue is : #34078\r\nI'm creating a new PR on the _8.x_ branch instead of _master_ as requested by @GrahamCampbell ", "number": 34132, "review_comments": [], "title": "Adding --column-statistics-off for php artisan schema:dump" }
{ "commits": [ { "message": " update dockblock" }, { "message": "Remove unnecessary comma" }, { "message": "Merge pull request #34106 from hnassr/patch-1\n\nRemove additional comma" }, { "message": "Merge branch '8.x' into master" }, { "message": "Fixed current branch variable" }, { "message": "Adding --column-statistics-off for php artisan schema:dump\n\nIn some specific case like mysqdump 8 and mysqlserver version 5.7 the command failed. It is added --column-statistics-off option to mitigate this issue. The issue is : #34078" }, { "message": "Fix style" } ], "files": [ { "diff": "@@ -10,7 +10,7 @@ then\n exit 1\n fi\n \n-RELEASE_BRANCH=\"8.x\"\n+RELEASE_BRANCH=\"master\"\n CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)\n VERSION=$1\n ", "filename": "bin/release.sh", "status": "modified" }, { "diff": "@@ -3,7 +3,7 @@\n set -e\n set -x\n \n-CURRENT_BRANCH=\"8.x\"\n+CURRENT_BRANCH=\"master\"\n \n function split()\n {", "filename": "bin/split.sh", "status": "modified" }, { "diff": "@@ -19,7 +19,8 @@ class DumpCommand extends Command\n protected $signature = 'schema:dump\n {--database= : The database connection to use}\n {--path= : The path where the schema dump file should be stored}\n- {--prune : Delete all existing migration files}';\n+ {--prune : Delete all existing migration files}\n+ {--column-statistics-off : use column-statics off in case of mysqldump 8 against mysqld 5.7}';\n \n /**\n * The console command description.\n@@ -35,9 +36,12 @@ class DumpCommand extends Command\n */\n public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher)\n {\n- $this->schemaState(\n+ $schemaState = $this->schemaState(\n $connection = $connections->connection($database = $this->input->getOption('database'))\n- )->dump($path = $this->path($connection));\n+ );\n+ $schemaState->columnStatisticsOff = $this->option('column-statistics-off');\n+\n+ $schemaState->dump($path = $this->path($connection));\n \n $dispatcher->dispatch(new SchemaDumped($connection, $path));\n ", "filename": "src/Illuminate/Database/Console/DumpCommand.php", "status": "modified" }, { "diff": "@@ -4,6 +4,8 @@\n \n class MySqlSchemaState extends SchemaState\n {\n+ public $columnStatisticsOff = false;\n+\n /**\n * Dump the database's schema into a file.\n *\n@@ -78,8 +80,9 @@ public function load($path)\n protected function baseDumpCommand()\n {\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\n+ $columnStatisticsOption = ($this->columnStatisticsOff) ? ' --column-statistics=0' : '';\n \n- return 'mysqldump '.$gtidPurged.' --column-statistics=0 --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n+ return 'mysqldump '.$gtidPurged.$columnStatisticsOption.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/MySqlSchemaState.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.0.0\r\n- PHP Version: 7.4.*\r\n- Database Driver & Version: mysqldump 8 and mysqld 5.7\r\n\r\n### Description:\r\nexecuting :\r\n```\r\nphp artisan schema:dump\r\n```\r\nI receive an error\r\n\r\n```\r\nmysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, '$.\"number-of-buckets-specified\"') FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = 'db_laravel_8' AND TABLE_NAME = 'failed_jobs';': Unknown table 'column_statistics' in information_schema (1109)\r\n```\r\ndue to the different version mysqldump 8 against an older mysql daemon 5.7.\r\nschema:dump execute mysqldump local command. The version 8 has the flag column-statistics set as 1 (true) by default. mysql5.7 could not have \"information_schema.COLUMN_STATISTICS\".\r\n\r\n\r\n### Steps To Reproduce:\r\nIn a envirnoment where you have mysqldump 8 and mysql5.7 execute php artisan schema:dump\r\n\r\n### Fix\r\n- In baseDumpCommand() (MySqlSchemaState.php) add option column-statistic=0\r\n```\r\n protected function baseDumpCommand()\r\n {\r\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\r\n $statisticOff = \" --column-statistics=0 \";\r\n return 'mysqldump ' . $statisticOff . ''.$gtidPurged.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\r\n }\r\n```\r\n", "comments": [ { "body": "Do you want to PR your fix?", "created_at": "2020-08-31T20:03:08Z" }, { "body": "Sure!", "created_at": "2020-08-31T20:06:21Z" }, { "body": "I submitted the PR : #34079 ", "created_at": "2020-08-31T21:06:26Z" }, { "body": "mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\nI got this error when try to run php artisan schema:dump", "created_at": "2020-09-03T09:40:06Z" }, { "body": "@vanthao03596 which database driver and version are you running?", "created_at": "2020-09-03T09:41:24Z" }, { "body": "> mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\n> I got this error when try to run php artisan schema:dump\r\n\r\n@vanthao03596 Which version of mysqldump ? mysqldump --version\r\n", "created_at": "2020-09-03T09:43:38Z" }, { "body": "I replicated the error.\r\nWith mysql-client (mysqldump) 8 , column-statistics is supported;\r\nwith mysql-client (mysqldump) 5.7, column statistic is NOT supported.\r\n\r\nUsing column-statistics=0, it allows to use mysqdump8 with a mysql5.7(server)\r\nUsing column-statistcis=0 fails with mysqldump5.7\r\n\r\nPossible solutions that I have in mind:\r\n- avoid to use column-statistics by default, and add a option in schema:dump (for example disable-statistic)\r\n- try to do some \"magic\": executing mysqldump without column-statistci, if it fails, try with column-statisctics.\r\n\r\nI like more the first one.\r\n\r\n\r\n", "created_at": "2020-09-03T10:15:11Z" }, { "body": "@roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n", "created_at": "2020-09-03T10:46:54Z" }, { "body": "@roberto-butti so it seems it's not just mysql 5.7", "created_at": "2020-09-03T10:48:56Z" }, { "body": "> @roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n> ![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n\r\n@vanthao03596 just to clarify, \r\nmysqldump is version 5.7.30 and the mysql database service is 8.0.2. Is it correct ?\r\n\r\n@driesvints do you want i add a option in DumpCommand to allow the user to \"disable\" statistics and force (--column-statistics=0) only.\r\nThe parameter could be column-statistics-off, or something similar. \r\nI could create a PR in my break lunch or this evening.\r\n", "created_at": "2020-09-03T11:05:06Z" }, { "body": "I think you'd want statistics off by default? The migrations are only meant for your DB structure, nothing else really.", "created_at": "2020-09-03T11:08:15Z" }, { "body": "ok, I agree to keep --column-statistics=0 in the code as default (now we have this, in the latest codebase).\r\nAnd allow to the user to declare in command line to skip column-statistics (with an option) if the user has a old version of mysqldump.\r\n--skip-column-statistics (the name of the option in the signature of the command).\r\nIs it ok for you, @driesvints ?", "created_at": "2020-09-03T11:19:28Z" }, { "body": " I think we need to find a solution where it never faults, on any MySQL version. In which specific situations does it fail now?", "created_at": "2020-09-03T11:21:11Z" }, { "body": "As far as i know on mysqldump 5.7 it fails bacause it doesn't support column-statistics=0 .\r\nIt is quite a common problem on backup software that rely on mysqldump. I see that lot of them has the option in the configuration to set or not the column-statistics.\r\nI'm courious to see if also DbDumper of Spatie has the same problem...", "created_at": "2020-09-03T11:29:47Z" }, { "body": "Is there any way we can check for the MySQL version in that command to not use the flag when it's 5.7?", "created_at": "2020-09-03T11:36:45Z" }, { "body": "I mean mysqldump 5.7", "created_at": "2020-09-03T11:37:01Z" }, { "body": "As far as i know we have mysqldump --version.\r\nBut the output is differente based on the version , the build and the architecture.\r\nFor mysqldump 8 :\r\n```\r\nmysqldump Ver 8.0.19 for osx10.15 on x86_64 (Homebrew)\r\n```\r\nor, for mysqldump 5.7:\r\n```\r\nmysqldump Ver 10.13 Distrib 5.7.29, for osx10.15 (x86_64)\r\n```\r\nSee _Ver_ and the _Distrib_.\r\nSo I think that we can't rely on the version output.\r\n", "created_at": "2020-09-03T12:13:56Z" }, { "body": "We could just state that the feature requires a certain version of mysqldump?", "created_at": "2020-09-03T12:53:41Z" }, { "body": "Sure @taylorotwell . \r\nAt this point my suggestion is : \r\nthe requirements is to have mysqldump version 8.\r\n\r\nMy additional suggestion is , for the user with an older version of mysqldump, allow them to use and additional option in command line, and allow them to use the feature schema:dump (is a kind of \"legacy\" option). What do you think ?\r\n", "created_at": "2020-09-03T13:07:21Z" }, { "body": "@roberto-butti mysqldump5.7 is installed in my local machine, mysql 8 is running in docker.", "created_at": "2020-09-03T14:18:19Z" }, { "body": "I'm going to release a PR, if you agree.\r\n\r\nI think that i'm covering all scenarios.\r\nLet me know what do you think ab out this proposal.\r\n\r\nThe only thing requested by the user for not having errors, is to force the user to use the option --column-statistics-off in the condition with mysqldump 8 and mysqld 5.7.\r\nConsidering that is an edge case, the great library of spatie DbDumper it doesn't support this scenario (i think that i will drop a PR also for that package).\r\n\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\n", "created_at": "2020-09-03T17:09:02Z" }, { "body": "Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.", "created_at": "2020-09-03T17:10:42Z" }, { "body": "> Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.\r\n\r\nCurrently I'm not able to determine a reliable way to identify exactly the version :(", "created_at": "2020-09-03T17:20:48Z" }, { "body": "PR #34125 \r\nTested with:\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\nTested also with Posgtres connection (pg_dump) with php artisan schema:dump\r\n\r\n\r\n", "created_at": "2020-09-03T20:33:30Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961490-9e9f6600-252b-11eb-8a05-752812995747.png)\r\n", "created_at": "2020-11-12T15:41:29Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961543-aeb74580-252b-11eb-8a1c-ae75cd6c2f08.png)\r\nand the file is .dump not .sql ?", "created_at": "2020-11-12T15:42:02Z" }, { "body": "I know this is closed but my solution on ubuntu 20.04 was to do the following : \r\n```\r\napt remove mysql-client\r\napt install mariadb-client\r\n\r\n```\r\nMake sure you use the client made for your mysql server type.", "created_at": "2021-10-14T17:00:55Z" } ], "number": 34078, "title": "php artisan schema:dump error (mysqldump8 and mysqld 5.7)" }
{ "body": "In some specific case like mysqdump 8 and mysqlserver version 5.7 the command failed. It is added --column-statistics-off option to mitigate this issue. The issue is : #34078\r\n\r\n<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n", "number": 34125, "review_comments": [], "title": "[9.x] Adding --column-statistics-off for php artisan schema:dump" }
{ "commits": [ { "message": "Adding --column-statistics-off for php artisan schema:dump\n\nIn some specific case like mysqdump 8 and mysqlserver version 5.7 the command failed. It is added --column-statistics-off option to mitigate this issue. The issue is : #34078" }, { "message": "Fix style" } ], "files": [ { "diff": "@@ -19,7 +19,8 @@ class DumpCommand extends Command\n protected $signature = 'schema:dump\n {--database= : The database connection to use}\n {--path= : The path where the schema dump file should be stored}\n- {--prune : Delete all existing migration files}';\n+ {--prune : Delete all existing migration files}\n+ {--column-statistics-off : use column-statics off in case of mysqldump 8 against mysqld 5.7}';\n \n /**\n * The console command description.\n@@ -35,9 +36,12 @@ class DumpCommand extends Command\n */\n public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher)\n {\n- $this->schemaState(\n+ $schemaState = $this->schemaState(\n $connection = $connections->connection($database = $this->input->getOption('database'))\n- )->dump($path = $this->path($connection));\n+ );\n+ $schemaState->columnStatisticsOff = $this->option('column-statistics-off');\n+\n+ $schemaState->dump($path = $this->path($connection));\n \n $dispatcher->dispatch(new SchemaDumped($connection, $path));\n ", "filename": "src/Illuminate/Database/Console/DumpCommand.php", "status": "modified" }, { "diff": "@@ -4,6 +4,8 @@\n \n class MySqlSchemaState extends SchemaState\n {\n+ public $columnStatisticsOff = false;\n+\n /**\n * Dump the database's schema into a file.\n *\n@@ -78,8 +80,9 @@ public function load($path)\n protected function baseDumpCommand()\n {\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\n+ $columnStatisticsOption = ($this->columnStatisticsOff) ? ' --column-statistics=0' : '';\n \n- return 'mysqldump '.$gtidPurged.' --column-statistics=0 --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n+ return 'mysqldump '.$gtidPurged.$columnStatisticsOption.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/MySqlSchemaState.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.29\r\n- PHP Version: 7.3.7\r\n- Database Driver & Version: MySQL 8.0\r\n\r\n### Description:\r\n\r\nAfter the commit 42c19bd tests like these will break:\r\n\r\n```\r\n$this->artisan('command:list')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| ID | Name | Params |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| 1 | Test | {\"foo\":\"bar\"} |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->assertExitCode(0);\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\nWrite a test for a command, which expects a table output:\r\n\r\n```\r\n$this->artisan('command:list')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| ID | Name | Params |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| 1 | Test | {\"foo\":\"bar\"} |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->assertExitCode(0);\r\n```\r\n", "comments": [ { "body": "Can you provide the `command:list` code as well?", "created_at": "2019-08-12T10:20:48Z" }, { "body": "Command Example:\r\n\r\n```\r\nuse Illuminate\\Console\\Command;\r\n\r\nclass ListCommand extends Command\r\n{\r\n /**\r\n * The name and signature of the console command.\r\n *\r\n * @var string\r\n */\r\n protected $signature = 'command:list';\r\n\r\n /**\r\n * Execute the console command.\r\n *\r\n * @return mixed\r\n */\r\n public function handle()\r\n {\r\n $this->table(['ID', 'Name', 'Params'], [\r\n [1, 'Test', '{\"foo\":\"bar\"}'],\r\n ]);\r\n }\r\n}\r\n```\r\n\r\nTest Example:\r\n\r\n```\r\nuse Tests\\TestCase;\r\n\r\nclass ListCommandTest extends TestCase\r\n{\r\n /**\r\n * Test whether the command lists all items.\r\n *\r\n * @return void\r\n */\r\n public function testCommandLists(): void\r\n {\r\n $this->artisan('command:list')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| ID | Name | Params |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| 1 | Test | {\"foo\":\"bar\"} |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->assertExitCode(0);\r\n }\r\n}\r\n```", "created_at": "2019-08-12T13:18:29Z" }, { "body": "I can indeed reproduce this. From what I can tell it's probably best to revert it but that'll break the new behavior again.", "created_at": "2019-08-13T09:49:26Z" }, { "body": "This doesn't only affect table command tests, but other 'ordered' expected outputs as well.\r\nWe are facing a problem with commands tests after https://github.com/laravel/framework/commit/42c19bd4482ef1c2f850851cf607badeff111a8d . \r\n\r\nIn our case it's a question that is being asked in a loop, so it can appear more than once in the output, but when the question is being expected for the second time, the test breaks.\r\n\r\n```php\r\n $this->artisan('create:admin')\r\n ->expectsQuestion('Please provide name for your admin.', 'first')\r\n ->expectsOutput(\"Admin with 'first' name successfully created. Admin ID: 1\")\r\n ->expectsQuestion('Would you like to create another admin?', true)\r\n ->expectsQuestion('Please provide name for your admin.', 'second')\r\n ->expectsOutput(\"Admin with 'second' name successfully created. Admin ID: 2\")\r\n ->expectsQuestion('Would you like to create another admin?', false)\r\n ->assertExitCode(0);\r\n```\r\nSo here the second 'Please provide name for your admin' will break the code due to mockery error: \r\n`Method Mockery_1_Illuminate_Console_OutputStyle::askQuestion(<Closure===true>)() called out of order: expected order 1, was 2`", "created_at": "2019-08-15T07:23:39Z" }, { "body": "@prwnr can you try with the patch provided by mohamed and let us know if that fixes your issues? https://github.com/laravel/framework/pull/29580", "created_at": "2019-08-15T11:45:00Z" }, { "body": "@driesvints works fine with my tests as it was working with v5.8.29 \r\nI did additional test with the same question being asked 3 times, works regardless of how many times same question appears. ", "created_at": "2019-08-15T12:43:10Z" }, { "body": "Mohamed's PR was merged and will be in the next minor release for Laravel.", "created_at": "2019-08-16T11:47:24Z" } ], "number": 29521, "title": "Table command tests will break" }
{ "body": "**Purpose:**\r\n\r\nThe addition of the `expectstTable()` method will allow you to easily assert the expectation of generated console table(s). \r\n\r\nWithout this, you must determine the exact size of the table's output and assert the table structure line by line. This is really cumbersome, and this PR resolves this.\r\n\r\nThis PR also supports multiple console table expectations, so you're able assert as many tables as required.\r\n\r\nI would define tests, but I wasn't able to locate any currently for the test artisan command assertions. Please let me know if this is necessary and I will resubmit.\r\n\r\n**Example command:**\r\n\r\n```php\r\nuse Illuminate\\Console\\Command;\r\n\r\nclass ListCommand extends Command\r\n{\r\n protected $signature = 'command:list';\r\n\r\n public function handle()\r\n {\r\n $this->table(['ID', 'Name', 'Params'], [\r\n [1, 'Test', '{\"foo\":\"bar\"}'],\r\n ]);\r\n }\r\n}\r\n```\r\n\r\n**Before this change:**\r\n\r\n```php\r\npublic function testCommandList()\r\n{\r\n $this->artisan('command:list')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| ID | Name | Params |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->expectsOutput('| 1 | Test | {\"foo\":\"bar\"} |')\r\n ->expectsOutput('+----+------+---------------+')\r\n ->assertExitCode(0);\r\n}\r\n```\r\n\r\n**After this change:**\r\n\r\n```php\r\npublic function testCommandList()\r\n{\r\n $this->artisan('command:list')\r\n ->expectsTable(['ID', 'Name', 'Params'], [[1, 'Test', '{\"foo\":\"bar\"}']])\r\n ->assertExitCode(0);\r\n}\r\n```\r\n\r\n\r\n**Related:** #29521\r\n\r\nI aligned the arguments with their types in the `expectsTable()` method with the `table()` method in the `InteractsWithIO` trait:\r\n\r\nhttps://github.com/laravel/framework/blob/17777a92da9b3cf0026f26462d289d596420e6d0/src/Illuminate/Console/Concerns/InteractsWithIO.php#L223\r\n\r\n<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n", "number": 34090, "review_comments": [], "title": "[7.x] Added expectsTable console test assertion" }
{ "commits": [ { "message": "Added expectsTable console assertion\n\nThis will allow you to easily assert the expectation of a generated console table. Without this, you must determine the exact size of the tables output and assert the table structure line by line." }, { "message": "Fix spacing." }, { "message": "Fix style" } ], "files": [ { "diff": "@@ -22,6 +22,13 @@ trait InteractsWithConsole\n */\n public $expectedOutput = [];\n \n+ /**\n+ * All of the expected ouput tables.\n+ *\n+ * @var array\n+ */\n+ public $expectedTables = [];\n+\n /**\n * All of the expected questions.\n *", "filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php", "status": "modified" }, { "diff": "@@ -5,10 +5,12 @@\n use Illuminate\\Console\\OutputStyle;\n use Illuminate\\Contracts\\Console\\Kernel;\n use Illuminate\\Contracts\\Container\\Container;\n+use Illuminate\\Contracts\\Support\\Arrayable;\n use Illuminate\\Support\\Arr;\n use Mockery;\n use Mockery\\Exception\\NoMatchingExpectationException;\n use PHPUnit\\Framework\\TestCase as PHPUnitTestCase;\n+use Symfony\\Component\\Console\\Helper\\Table;\n use Symfony\\Component\\Console\\Input\\ArrayInput;\n use Symfony\\Component\\Console\\Output\\BufferedOutput;\n \n@@ -131,6 +133,27 @@ public function expectsOutput($output)\n return $this;\n }\n \n+ /**\n+ * Specify a table that should be printed when the command runs.\n+ *\n+ * @param array $headers\n+ * @param \\Illuminate\\Contracts\\Support\\Arrayable|array $rows\n+ * @param string $tableStyle\n+ * @param array $columnStyles\n+ * @return $this\n+ */\n+ public function expectsTable($headers, $rows, $tableStyle = 'default', array $columnStyles = [])\n+ {\n+ $this->test->expectedTables[] = [\n+ 'headers' => (array) $headers,\n+ 'rows' => $rows instanceof Arrayable ? $rows->toArray() : $rows,\n+ 'tableStyle' => $tableStyle,\n+ 'columnStyles' => $columnStyles,\n+ ];\n+\n+ return $this;\n+ }\n+\n /**\n * Assert that the command has the given exit code.\n *\n@@ -264,6 +287,8 @@ private function createABufferedOutputMock()\n ->shouldAllowMockingProtectedMethods()\n ->shouldIgnoreMissing();\n \n+ $this->applyOutputTableExpectations($mock);\n+\n foreach ($this->test->expectedOutput as $i => $output) {\n $mock->shouldReceive('doWrite')\n ->once()\n@@ -277,6 +302,36 @@ private function createABufferedOutputMock()\n return $mock;\n }\n \n+ /**\n+ * Apply the output table expectations to the mock.\n+ *\n+ * @param \\Mockery\\MockInterface $mock\n+ * @return void\n+ */\n+ private function applyOutputTableExpectations($mock)\n+ {\n+ foreach ($this->test->expectedTables as $consoleTable) {\n+ $table = (new Table($output = new BufferedOutput))\n+ ->setHeaders($consoleTable['headers'])\n+ ->setRows($consoleTable['rows'])\n+ ->setStyle($consoleTable['tableStyle']);\n+\n+ foreach ($consoleTable['columnStyles'] as $columnIndex => $columnStyle) {\n+ $table->setColumnStyle($columnIndex, $columnStyle);\n+ }\n+\n+ $table->render();\n+\n+ $lines = array_filter(\n+ preg_split(\"/\\n/\", $output->fetch())\n+ );\n+\n+ foreach ($lines as $line) {\n+ $this->expectsOutput($line);\n+ }\n+ }\n+ }\n+\n /**\n * Handle the object's destruction.\n *", "filename": "src/Illuminate/Testing/PendingCommand.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.0.0\r\n- PHP Version: 7.4.*\r\n- Database Driver & Version: mysqldump 8 and mysqld 5.7\r\n\r\n### Description:\r\nexecuting :\r\n```\r\nphp artisan schema:dump\r\n```\r\nI receive an error\r\n\r\n```\r\nmysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, '$.\"number-of-buckets-specified\"') FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = 'db_laravel_8' AND TABLE_NAME = 'failed_jobs';': Unknown table 'column_statistics' in information_schema (1109)\r\n```\r\ndue to the different version mysqldump 8 against an older mysql daemon 5.7.\r\nschema:dump execute mysqldump local command. The version 8 has the flag column-statistics set as 1 (true) by default. mysql5.7 could not have \"information_schema.COLUMN_STATISTICS\".\r\n\r\n\r\n### Steps To Reproduce:\r\nIn a envirnoment where you have mysqldump 8 and mysql5.7 execute php artisan schema:dump\r\n\r\n### Fix\r\n- In baseDumpCommand() (MySqlSchemaState.php) add option column-statistic=0\r\n```\r\n protected function baseDumpCommand()\r\n {\r\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\r\n $statisticOff = \" --column-statistics=0 \";\r\n return 'mysqldump ' . $statisticOff . ''.$gtidPurged.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\r\n }\r\n```\r\n", "comments": [ { "body": "Do you want to PR your fix?", "created_at": "2020-08-31T20:03:08Z" }, { "body": "Sure!", "created_at": "2020-08-31T20:06:21Z" }, { "body": "I submitted the PR : #34079 ", "created_at": "2020-08-31T21:06:26Z" }, { "body": "mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\nI got this error when try to run php artisan schema:dump", "created_at": "2020-09-03T09:40:06Z" }, { "body": "@vanthao03596 which database driver and version are you running?", "created_at": "2020-09-03T09:41:24Z" }, { "body": "> mysqldump: [ERROR] unknown variable 'column-statistics=0'\r\n> I got this error when try to run php artisan schema:dump\r\n\r\n@vanthao03596 Which version of mysqldump ? mysqldump --version\r\n", "created_at": "2020-09-03T09:43:38Z" }, { "body": "I replicated the error.\r\nWith mysql-client (mysqldump) 8 , column-statistics is supported;\r\nwith mysql-client (mysqldump) 5.7, column statistic is NOT supported.\r\n\r\nUsing column-statistics=0, it allows to use mysqdump8 with a mysql5.7(server)\r\nUsing column-statistcis=0 fails with mysqldump5.7\r\n\r\nPossible solutions that I have in mind:\r\n- avoid to use column-statistics by default, and add a option in schema:dump (for example disable-statistic)\r\n- try to do some \"magic\": executing mysqldump without column-statistci, if it fails, try with column-statisctics.\r\n\r\nI like more the first one.\r\n\r\n\r\n", "created_at": "2020-09-03T10:15:11Z" }, { "body": "@roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n", "created_at": "2020-09-03T10:46:54Z" }, { "body": "@roberto-butti so it seems it's not just mysql 5.7", "created_at": "2020-09-03T10:48:56Z" }, { "body": "> @roberto-butti @driesvints I'm using mysqldump5.7, mysql 8.0.2\r\n> ![1](https://user-images.githubusercontent.com/34786441/92105788-8dd8c280-ee0d-11ea-9ad3-e38f12fdd9fe.png)\r\n\r\n@vanthao03596 just to clarify, \r\nmysqldump is version 5.7.30 and the mysql database service is 8.0.2. Is it correct ?\r\n\r\n@driesvints do you want i add a option in DumpCommand to allow the user to \"disable\" statistics and force (--column-statistics=0) only.\r\nThe parameter could be column-statistics-off, or something similar. \r\nI could create a PR in my break lunch or this evening.\r\n", "created_at": "2020-09-03T11:05:06Z" }, { "body": "I think you'd want statistics off by default? The migrations are only meant for your DB structure, nothing else really.", "created_at": "2020-09-03T11:08:15Z" }, { "body": "ok, I agree to keep --column-statistics=0 in the code as default (now we have this, in the latest codebase).\r\nAnd allow to the user to declare in command line to skip column-statistics (with an option) if the user has a old version of mysqldump.\r\n--skip-column-statistics (the name of the option in the signature of the command).\r\nIs it ok for you, @driesvints ?", "created_at": "2020-09-03T11:19:28Z" }, { "body": " I think we need to find a solution where it never faults, on any MySQL version. In which specific situations does it fail now?", "created_at": "2020-09-03T11:21:11Z" }, { "body": "As far as i know on mysqldump 5.7 it fails bacause it doesn't support column-statistics=0 .\r\nIt is quite a common problem on backup software that rely on mysqldump. I see that lot of them has the option in the configuration to set or not the column-statistics.\r\nI'm courious to see if also DbDumper of Spatie has the same problem...", "created_at": "2020-09-03T11:29:47Z" }, { "body": "Is there any way we can check for the MySQL version in that command to not use the flag when it's 5.7?", "created_at": "2020-09-03T11:36:45Z" }, { "body": "I mean mysqldump 5.7", "created_at": "2020-09-03T11:37:01Z" }, { "body": "As far as i know we have mysqldump --version.\r\nBut the output is differente based on the version , the build and the architecture.\r\nFor mysqldump 8 :\r\n```\r\nmysqldump Ver 8.0.19 for osx10.15 on x86_64 (Homebrew)\r\n```\r\nor, for mysqldump 5.7:\r\n```\r\nmysqldump Ver 10.13 Distrib 5.7.29, for osx10.15 (x86_64)\r\n```\r\nSee _Ver_ and the _Distrib_.\r\nSo I think that we can't rely on the version output.\r\n", "created_at": "2020-09-03T12:13:56Z" }, { "body": "We could just state that the feature requires a certain version of mysqldump?", "created_at": "2020-09-03T12:53:41Z" }, { "body": "Sure @taylorotwell . \r\nAt this point my suggestion is : \r\nthe requirements is to have mysqldump version 8.\r\n\r\nMy additional suggestion is , for the user with an older version of mysqldump, allow them to use and additional option in command line, and allow them to use the feature schema:dump (is a kind of \"legacy\" option). What do you think ?\r\n", "created_at": "2020-09-03T13:07:21Z" }, { "body": "@roberto-butti mysqldump5.7 is installed in my local machine, mysql 8 is running in docker.", "created_at": "2020-09-03T14:18:19Z" }, { "body": "I'm going to release a PR, if you agree.\r\n\r\nI think that i'm covering all scenarios.\r\nLet me know what do you think ab out this proposal.\r\n\r\nThe only thing requested by the user for not having errors, is to force the user to use the option --column-statistics-off in the condition with mysqldump 8 and mysqld 5.7.\r\nConsidering that is an edge case, the great library of spatie DbDumper it doesn't support this scenario (i think that i will drop a PR also for that package).\r\n\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\n", "created_at": "2020-09-03T17:09:02Z" }, { "body": "Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.", "created_at": "2020-09-03T17:10:42Z" }, { "body": "> Is there really no way to determine the MySQL version in the command? Then we can work around this entirely.\r\n\r\nCurrently I'm not able to determine a reliable way to identify exactly the version :(", "created_at": "2020-09-03T17:20:48Z" }, { "body": "PR #34125 \r\nTested with:\r\n\r\nmysqldump version | mysql service version | artisan command to use\r\n-|-|-\r\n5.7 | 5.7 | php artisan schema:dump\r\n8 | 8 | php artisan schema:dump\r\n5.7 | 8 | php artisan schema:dump\r\n8 | 5.7 | php artisan schema:dump --column-statistics-off\r\n\r\nTested also with Posgtres connection (pg_dump) with php artisan schema:dump\r\n\r\n\r\n", "created_at": "2020-09-03T20:33:30Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961490-9e9f6600-252b-11eb-8a05-752812995747.png)\r\n", "created_at": "2020-11-12T15:41:29Z" }, { "body": "![image](https://user-images.githubusercontent.com/15264938/98961543-aeb74580-252b-11eb-8a1c-ae75cd6c2f08.png)\r\nand the file is .dump not .sql ?", "created_at": "2020-11-12T15:42:02Z" }, { "body": "I know this is closed but my solution on ubuntu 20.04 was to do the following : \r\n```\r\napt remove mysql-client\r\napt install mariadb-client\r\n\r\n```\r\nMake sure you use the client made for your mysql server type.", "created_at": "2021-10-14T17:00:55Z" } ], "number": 34078, "title": "php artisan schema:dump error (mysqldump8 and mysqld 5.7)" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nAs commented in #34078 , I disable column-statistics option for mysqldump\r\n", "number": 34079, "review_comments": [], "title": "[8.0] schema:dump adding column-statistics=0 for mysqldump" }
{ "commits": [ { "message": "schema:dump adding column-statistics=0 for mysqldump" } ], "files": [ { "diff": "@@ -79,7 +79,7 @@ protected function baseDumpCommand()\n {\n $gtidPurged = $this->connection->isMaria() ? '' : '--set-gtid-purged=OFF';\n \n- return 'mysqldump '.$gtidPurged.' --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n+ return 'mysqldump '.$gtidPurged.' --column-statistics=0 --skip-add-drop-table --skip-add-locks --skip-comments --skip-set-charset --tz-utc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --user=$LARAVEL_LOAD_USER --password=$LARAVEL_LOAD_PASSWORD $LARAVEL_LOAD_DATABASE';\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/MySqlSchemaState.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 8.x-dev\r\n- PHP Version: 7.4.8\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\nRight now it appears that using Closure factory states alongside Faker does not work, this is because the Closure is created in another instance of the factory then where it is eventually invoked, so when it is invoked `$this->faker` still references the old instance's faker (which, depending on the situation, may or may not be null). So instead attributes created via faker this way will be null.\r\n\r\n### Steps To Reproduce:\r\n- Create a fresh Laravel 8.x-dev application `composer create-project laravel/laravel:dev-develop`\r\n- Paste the following snippet in the UserFactory:\r\n```\r\n public function foo()\r\n {\r\n return $this->state(fn () => [\r\n 'name' => $this->faker->name,\r\n ]);\r\n }\r\n```\r\n- Open Tinker\r\n- Paste the following line `User::factory()->foo()->make()`\r\n\r\n### Potential fix:\r\nI was able to get it working by adding `$state = $state->bindTo($this);` within the reduce callback in `Factory::getRawAttributes()`, this works because `$this->faker = $this->withFaker()` is called right before the states are resolved, but I don't know what further implications this has.", "comments": [ { "body": "Thanks! We've fixed this.", "created_at": "2020-08-31T16:46:41Z" }, { "body": "Is it just me or is this still broken?\r\n\r\n- `laravel new testProject` (Laravel 8.0.0)\r\n- Paste the following snippet in the `UserFactory.php`\r\n```php\r\npublic function foo()\r\n {\r\n return $this->state([\r\n 'name' => $this->faker->name,\r\n ]);\r\n }\r\n```\r\n- Open Tinker\r\n- Paste the following line: `User::factory()->foo()->make()`\r\n- returns `PHP Notice: Trying to get property 'name' of non-object`\r\n- `dd($this->faker);` returns `null`\r\n\r\n@axlon @driesvints \r\n\r\n(note the example method here is not returning a closure, but an array as demonstrated in the docs)", "created_at": "2020-09-08T20:46:17Z" }, { "body": "@drbyte could it be that you're using a unit test where the framework isn't booted?", "created_at": "2020-09-09T16:47:19Z" }, { "body": "@driesvints no, it's a proper FeatureTest which properly extends TestCase\r\n\r\nHere's a blank repo with a commit showing how to reproduce it:\r\nhttps://github.com/drbyte/withFaker-bug/commit/45442006ed35c394a23f2372cc5b8012f5463f6d", "created_at": "2020-09-09T18:01:44Z" }, { "body": "@drbyte its because your state is not within a closure, when you use it like this the state will be resolved as soon as you call the method, before faker is initialised\r\n\r\nChanging it to the snippet below should fix it:\r\n\r\n```\r\n public function male()\r\n {\r\n return $this->state(fn () => [\r\n 'name' => $this->faker->firstNameMale,\r\n ]);\r\n }\r\n```\r\n\r\nEdit (as I didn't read your first comment initially) : I haven't checked the docs yet, so I don't know if it shows an example without a Closure but AFAIK it won't work without a closure unless you manually instantiate faker on the factory instance (which I wouldn't recommend because of the way factories work internally)", "created_at": "2020-09-09T18:12:25Z" }, { "body": "Thanks. My brain was treating it as a regular class, but of course it's not. 😄 \r\n\r\nThe docs don't mention it, but I've submitted a PR. https://github.com/laravel/docs/pull/6329/files", "created_at": "2020-09-09T18:24:14Z" } ], "number": 34069, "title": "[8.x] Faker doesn't work within model factory states" }
{ "body": "This fixes #34069 and corrects #34074 which contains a typo.\r\n\r\nEdit: I also changed the `is_callable` check to` instanceof Closure`, because `Sequence` is callable and will otherwise break", "number": 34077, "review_comments": [], "title": "[8.x] Bind state to current factory instance" }
{ "commits": [ { "message": "Correct factory state binding check" }, { "message": "Replace is_callable with instanceof Closure" } ], "files": [ { "diff": "@@ -325,7 +325,7 @@ protected function getRawAttributes(?Model $parent)\n return $this->parentResolvers();\n }], $states->all()));\n })->reduce(function ($carry, $state) use ($parent) {\n- if (is_callable($parent)) {\n+ if ($state instanceof Closure) {\n $state = $state->bindTo($this);\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Factories/Factory.php", "status": "modified" } ] }
{ "body": "<!--\r\nPlease use this issue tracker only for reporting Laravel bugs.\r\n\r\nIf you need support, please use the forums:\r\n\r\n- https://laracasts.com/discuss \r\n- https://laravel.io/forum\r\n\r\nAlternatively, you may use Slack (https://larachat.co/) or Stack Overflow (http://stackoverflow.com/questions/tagged/laravel).\r\n\r\nIf you would like to propose new Laravel features, please make a pull request, or open an issue at https://github.com/laravel/internals/issues.\r\n-->\r\n\r\n- Laravel Version: 5.5.33\r\n- PHP Version: 7.1.8\r\n- Database Driver & Version: Mysql 5.7\r\n\r\n### Description:\r\n#### Eloquent/Model::withCount doesn't specify database/schema name\r\nI have 2 models User and Problem. Their table locates in different database/schema in same server (`users` locates in connection `mysql` a.k.a. schema `acm`, `problem` locates in connection `mysql2` a.k.a. schema `boj` in my case).\r\nI have defined `protected $connection` for these two models. Anything other works well. \r\nAnd when I call `User::with('solved')` it works well, but when calling `User::withCount('solved')`, the generated sql sentence doesn't specify the `problem` table's database/schema, which will cause an error.\r\n\r\n(formatted)\r\n```\r\n(3/3) QueryException\r\nSQLSTATE[42S02]: Base table or view not found: 1146 Table 'acm.problem' doesn't exist (SQL: \r\n```\r\n```sql\r\nselect `users`.*, (\r\n select count(*) from `problem` \r\n inner join `boj`.`solution` on `problem`.`problem_id` = `boj`.`solution`.`problem_id` \r\n where `users`.`id` = `boj`.`solution`.`acm_user_id` and `boj`.`solution`.`result` = 4\r\n) as `solved_count` \r\nfrom `users` order by `active_at` desc limit 150 offset 0)\r\n```\r\n\r\n\r\n\r\n\r\n### Steps To Reproduce:\r\n#### Defines\r\n```php\r\nclass User\r\n{\r\n protected $connection = 'mysql';\r\n // some other defines \r\n\r\n public function solved()\r\n {\r\n $mysql2 = config('database.connections.mysql2.database');\r\n return $this\r\n ->belongsToMany(Problem::class, \"$mysql2.solution\", 'acm_user_id', 'problem_id')\r\n ->wherePivot('result', 4);\r\n }\r\n}\r\n```\r\nI believe it doen't matter where the `solution` table locates and how I call it... Although it may looks ugly.\r\n```php\r\nclass Problem\r\n{\r\n protected $connection = 'mysql2';\r\n protected $table = 'problem';\r\n // some other defines\r\n}\r\n```\r\n#### Call\r\n```php\r\nUser::with('roles')->withCount('solved')->orderBy('active_at', 'desc')->paginate(150);\r\n```", "comments": [ { "body": "Besides, `withCount` a `hasMany` relation will cause the same problem.", "created_at": "2018-02-06T07:14:19Z" }, { "body": "me too", "created_at": "2018-05-03T06:22:45Z" }, { "body": "@foreshadow, try this\r\n```php\r\nUser::with('roles')\r\n ->withCount(['solved' => function($query) {\r\n $mysql2 = config('database.connections.mysql2.database');\r\n $query->from(\"$mysql2.problem\");\r\n }])\r\n ->orderBy('active_at', 'desc')\r\n ->paginate(150);\r\n```", "created_at": "2018-10-07T15:37:27Z" }, { "body": "@miki131's approach works for me. However.. the odd thing is that if you use with() instead of withCount.. on top of with() not requiring to specify the 2nd db connection.. running ->count() on the related model fetched from with() is at least 2x as fast as when using withCount\r\n\r\nwithCount is supposed to be faster, but it seems that doing it the way @miki131 proposed, while it works, it seems less optimized somehow and is much slower\r\n\r\nedit: after adding an index on the join column, it's now super fast. Still odd that it was much slower than the with()->count() without the index", "created_at": "2018-11-12T18:04:50Z" }, { "body": "Is this issue scheduled to be fixed soon?", "created_at": "2019-01-04T13:28:48Z" }, { "body": "@nowox we're open to PRs for this. I'm working my way through all of the bugs but it'll take time.", "created_at": "2019-01-04T14:01:48Z" }, { "body": "In the meantime, you can use this package: https://github.com/hoyvoy/laravel-cross-database-subqueries", "created_at": "2019-01-05T15:36:14Z" }, { "body": "I have found a quick fix. I modified `Illuminate\\Database\\Eloquent\\Builder::setModel` method like this:\r\n\r\n````php\r\n /**\r\n * Set a model instance for the model being queried.\r\n *\r\n * @param \\Illuminate\\Database\\Eloquent\\Model $model\r\n * @return $this\r\n */\r\n public function setModel(Model $model)\r\n {\r\n $this->model = $model;\r\n\r\n $this->query->from($model->getConnection()->getDatabaseName() . '.' . $model->getTable());\r\n // Original:\r\n // $this->query->from($model->getTable());\r\n\r\n return $this;\r\n }\r\n````\r\n\r\nWhat I did was force prepend the name of the database to the table name within `FROM`. The db name is obtained using the model's connection name.\r\n\r\nI made this change to fix #29125 \r\n\r\nI applied this change and so far my application is working fine and it does not seem to have broken anything that was working. The only issue I see is the rather longer queries.\r\n\r\nI could create a PR if this fix does not break anything", "created_at": "2019-07-12T04:38:00Z" }, { "body": "@alwintom the pr you sent in seems too much of a breaking change. What do you think @staudenmeir ?", "created_at": "2019-07-12T11:53:14Z" }, { "body": "I think so too. I have alreday closed the PR after realizing that. During\r\ntesting against sqlite DBs it failed.\r\n\r\nHowever i am going to keep it for my application as we strictly use mysql\r\nand it seems to work for us\r\n\r\n@driesvints \r\nThe changes made as part of the PR will cause the name of the database to be prepended to table names in every generated query, even if all tables in the query belong to the same database. Normally this wouldn't be a problem. But when using sqlite this could be a problem as the database name is actually a filename.\r\n\r\nHowever as far as I know to make inter-schema joins in sqlite one would have to use the `attach` option. Does eloquent support inter-schema joins with sqlite backend? \r\n\r\nOn Fri 12 Jul, 2019, 5:23 PM Dries Vints, <notifications@github.com> wrote:\r\n\r\n> @alwintom <https://github.com/alwintom> the pr you sent in seems too much\r\n> of a breaking change. What do you think @staudenmeir\r\n> <https://github.com/staudenmeir> ?\r\n>\r\n> —\r\n> You are receiving this because you were mentioned.\r\n> Reply to this email directly, view it on GitHub\r\n> <https://github.com/laravel/framework/issues/23042?email_source=notifications&email_token=ABYZ4MUWJ3UMOLCXMSU44YLP7BWFLA5CNFSM4EPKLOTKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODZZRJXQ#issuecomment-510858462>,\r\n> or mute the thread\r\n> <https://github.com/notifications/unsubscribe-auth/ABYZ4MWFRGC6QH3G5DLWCS3P7BWFLANCNFSM4EPKLOTA>\r\n> .\r\n>\r\n", "created_at": "2019-07-12T12:50:48Z" }, { "body": "> I have found a quick fix. I modified `Illuminate\\Database\\Eloquent\\Builder::setModel` method like this:\r\n> \r\n> ```\r\n> /**\r\n> * Set a model instance for the model being queried.\r\n> *\r\n> * @param \\Illuminate\\Database\\Eloquent\\Model $model\r\n> * @return $this\r\n> */\r\n> public function setModel(Model $model)\r\n> {\r\n> $this->model = $model;\r\n> \r\n> $this->query->from($model->getConnection()->getDatabaseName() . '.' . $model->getTable());\r\n> // Original:\r\n> // $this->query->from($model->getTable());\r\n> \r\n> return $this;\r\n> }\r\n> ```\r\n> \r\n> What I did was force prepend the name of the database to the table name within `FROM`. The db name is obtained using the model's connection name.\r\n> \r\n> I made this change to fix #29125\r\n> \r\n> I applied this change and so far my application is working fine and it does not seem to have broken anything that was working. The only issue I see is the rather longer queries.\r\n> \r\n> I could create a PR if this fix does not break anything\r\n\r\n\r\nIt works, if it fails with sqlite why dont add a validation only to check that is not sqlite? Or what other problems happens with using this code?", "created_at": "2020-01-10T19:09:04Z" }, { "body": "I've been trying to look into this again but haven't made much progress so far. I *think* the problem is that the `newQuery` returned from below doesn't have the custom connection from the related model defined but I cannot figure out why that is.\r\n\r\nhttps://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L386\r\n\r\nAppreciating any help with figuring this out.", "created_at": "2020-04-24T13:42:28Z" }, { "body": "One workaround for this at the moment is prefixing the table with the database name:\r\n\r\n```\r\nclass Problem extends Model\r\n{\r\n protected $table = 'mysql2.problem';\r\n} \r\n```", "created_at": "2020-05-01T13:47:22Z" }, { "body": "> \r\n> \r\n> One workaround for this at the moment is prefixing the table with the database name:\r\n> \r\n> ```\r\n> class Problem extends Model\r\n> {\r\n> protected $table = 'mysql2.problem';\r\n> } \r\n> ```\r\n\r\nThis will result in the builder generating queries like this:\r\n`SELECT ..... from ::memory::.users`\r\nwhen you use an in-memory sqlite database.\r\n\r\nThat being said, I resorted to a solution similar to yours in my application and added a ENV check to make sure my in-memory sqlite based unit tests to pass as well.", "created_at": "2020-05-01T14:41:47Z" }, { "body": "> I've been trying to look into this again but haven't made much progress so far. I _think_ the problem is that the `newQuery` returned from below doesn't have the custom connection from the related model defined but I cannot figure out why that is.\r\n> \r\n> https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L386\r\n> \r\n> Appreciating any help with figuring this out.\r\n\r\n\r\n@driesvints I followed your lead but i guess that part is OK. I think the problem is that the [`selectSub`](https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L408) is [parsing](https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Query/Builder.php#L338) the query object into SQL query string. That drops the custom connection from the relation. I couldn't figure out how to fix it. :man_shrugging: ", "created_at": "2020-05-01T15:08:33Z" }, { "body": "In principle, the package's implementation is the right approach:\r\nhttps://github.com/hoyvoy/laravel-cross-database-subqueries/blob/master/src/Eloquent/Concerns/QueriesRelationships.php#L84\r\n\r\nWe compare the connections and prefix the subquery's table name if they are different. I only find the temporary separator `<-->` to be a weird choice, not sure why they implemented it this way.\r\n\r\nThe trait also uses the same approach to fix the issue for `has()`/`whereHas()` subqueries. It makes sense to fix both issues in one go and extract the necessary code into a shared helper method.\r\n\r\nWe also need to consider the package's open [issues](https://github.com/hoyvoy/laravel-cross-database-subqueries/issues), especially [this](https://github.com/hoyvoy/laravel-cross-database-subqueries/issues/12) one.", "created_at": "2020-05-02T05:38:52Z" }, { "body": "@staudenmeir but this won't support `:memory:`, right?", "created_at": "2020-05-02T05:49:57Z" }, { "body": "@yaim No. IMO, cross-database queries on SQLite are _way_ too much of an edge case.\r\n\r\nThey are [possible](https://www.sqlite.org/lang_attach.html) for file-based databases and apparently even for in-memory ones, but I don't think that would work with Laravel. ", "created_at": "2020-05-02T06:14:06Z" }, { "body": "Hi there, we want to write that for us all work fine in mysql with package [cross-database](https://github.com/hoyvoy/laravel-cross-database-subqueries).\r\n\r\n![image](https://user-images.githubusercontent.com/29952045/86354491-70e70e00-bc69-11ea-9ef7-e801cdfb899b.png)\r\n\r\nIn this query User are in DB1 and categories are in DB2. the result work great!\r\n\r\n![image](https://user-images.githubusercontent.com/29952045/86354653-b572a980-bc69-11ea-9b87-4858c756ac98.png)\r\n\r\nFor us, we must specify relation connection ('database.relation') in : \r\n\r\n![image](https://user-images.githubusercontent.com/29952045/86354747-df2bd080-bc69-11ea-8420-17976b69dc74.png)\r\n\r\nAnd for User, we must replace Authenticatable with new model class:\r\n\r\n![image](https://user-images.githubusercontent.com/29952045/86354822-01255300-bc6a-11ea-928f-60c026b7ec38.png)\r\n\r\n![image](https://user-images.githubusercontent.com/29952045/86354850-0bdfe800-bc6a-11ea-9f53-90bbf9862258.png)\r\n\r\nThanks for the trick :+1: ", "created_at": "2020-07-02T11:44:39Z" }, { "body": "I've done some testing on this, and I can't recreate the issue you're having @driesvints. The query created in `QueriesRelationships::withCount()` definitely has the new connection. The problem is that the query is turned into its raw SQL and added as a subquery.\r\n\r\nLooking at it, the best solution I can see is one where the database name is appended to the from in [`Builder::parseSub()`](https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Query/Builder.php#L339). The method could be made to be something like this.\r\n\r\n```php\r\nprotected function parseSub($query)\r\n{\r\n if ($query instanceof self || $query instanceof EloquentBuilder || $query instanceof Relation) {\r\n if ($query->getConnection()->getDatabaseName() !== $this->getConnection()->getDatabaseName()) {\r\n $databaseName = $query->getConnection()->getDatabaseName();\r\n\r\n\t\t\tif (strpos($query->from, $databaseName) !== 0) {\r\n\t\t\t\t$query->from($databaseName .'.'.$query->from);\r\n }\r\n }\r\n\r\n return [$query->toSql(), $query->getBindings()];\r\n } elseif (is_string($query)) {\r\n return [$query, []];\r\n } else {\r\n throw new InvalidArgumentException(\r\n 'A subquery must be a query builder instance, a Closure, or a string.'\r\n );\r\n }\r\n}\r\n```\r\n\r\nI can't think of anything prettier. This should have the benefit that it'll work for any cross-database subqueries, as long as they're not on totally different connections. It could perhaps check for the presence of `.` instead of the database name.\r\n\r\nI can make a PR if you wish.", "created_at": "2020-07-28T12:03:29Z" }, { "body": "@foreshadow @MwSpaceLLC does the solution from @ollieread work for you?", "created_at": "2020-07-28T12:48:27Z" }, { "body": "@driesvints for now we use package cross-database.😁", "created_at": "2020-07-28T13:15:25Z" }, { "body": "@MwSpaceLLC yes but I'm asking that if your problem is resolved if you apply the patch from @ollieread. Without that package installed.", "created_at": "2020-07-28T13:21:46Z" }, { "body": "@driesvints now the project is under production and we not have any time for testing. when i have some time to test i reply here", "created_at": "2020-07-28T13:54:04Z" }, { "body": "To all on this thread: I'm going to leave this open for a few days to give any of you the time to test @ollieread's solution. After that I'll close it. We're of course still accepting PRs if anyone's up for it. Thanks", "created_at": "2020-07-28T13:57:18Z" }, { "body": "@driesvints I've tested it locally and all seems to work for me. I'm happy to submit a PR with that solution.", "created_at": "2020-07-28T17:43:48Z" }, { "body": "@ollieread could do that yeah. But we'll need to make sure we don't break any tests.", "created_at": "2020-07-28T18:04:57Z" }, { "body": "Send to 6.x please, thanks!", "created_at": "2020-07-28T18:05:05Z" }, { "body": "> I've done some testing on this, and I can't recreate the issue you're having @driesvints. The query created in `QueriesRelationships::withCount()` definitely has the new connection. The problem is that the query is turned into its raw SQL and added as a subquery.\r\n> \r\n> Looking at it, the best solution I can see is one where the database name is appended to the from in [`Builder::parseSub()`](https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Query/Builder.php#L339). The method could be made to be something like this.\r\n> \r\n> ```\r\n> protected function parseSub($query)\r\n> {\r\n> if ($query instanceof self || $query instanceof EloquentBuilder || $query instanceof Relation) {\r\n> if ($query->getConnection()->getDatabaseName() !== $this->getConnection()->getDatabaseName()) {\r\n> $databaseName = $query->getConnection()->getDatabaseName();\r\n> \r\n> \t\t\tif (strpos($query->from, $databaseName) !== 0) {\r\n> \t\t\t\t$query->from($databaseName .'.'.$query->from);\r\n> }\r\n> }\r\n> \r\n> return [$query->toSql(), $query->getBindings()];\r\n> } elseif (is_string($query)) {\r\n> return [$query, []];\r\n> } else {\r\n> throw new InvalidArgumentException(\r\n> 'A subquery must be a query builder instance, a Closure, or a string.'\r\n> );\r\n> }\r\n> }\r\n> ```\r\n> \r\n> I can't think of anything prettier. This should have the benefit that it'll work for any cross-database subqueries, as long as they're not on totally different connections. It could perhaps check for the presence of `.` instead of the database name.\r\n> \r\n> I can make a PR if you wish.\r\n\r\n@ollieread , @driesvints , Thank you this works very well in my case", "created_at": "2020-08-04T12:06:15Z" }, { "body": "@driesvints The fix for this has now been merged in (#33755) so this should now be sorted.", "created_at": "2020-08-05T15:57:15Z" } ], "number": 23042, "title": "Eloquent/Model::withCount doesn't specify database/schema name" }
{ "body": "If the database name for the relationship isn't the same as the current, append it to the table name for the count subquery. Addresses #23042\r\n", "number": 33747, "review_comments": [], "title": "[6.x] Append database name for withCount" }
{ "commits": [ { "message": "Append database name for withCount\n\nIf the database name for the relationship isn't the same as the current, append it to the table name for the count subquery. Addresses #23042" }, { "message": "StyleCI changes" } ], "files": [ { "diff": "@@ -338,6 +338,14 @@ protected function createSub($query)\n protected function parseSub($query)\n {\n if ($query instanceof self || $query instanceof EloquentBuilder) {\n+ if ($query->getConnection()->getDatabaseName() !== $this->getConnection()->getDatabaseName()) {\n+ $databaseName = $query->getConnection()->getDatabaseName();\n+\n+ if (strpos($query->from, $databaseName) !== 0 && strpos($query->from, '.') === false) {\n+ $query->from($databaseName.'.'.$query->from);\n+ }\n+ }\n+\n return [$query->toSql(), $query->getBindings()];\n } elseif (is_string($query)) {\n return [$query, []];", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7.22.0\r\n- PHP Version: 7.4.0\r\n- Database Driver & Version: sqlite\r\n\r\n### Description:\r\n\r\nWith the introduction of the cookies prefix the assertCookie test function is broken.\r\n\r\n### Steps To Reproduce:\r\n1. Create a test route to set a cookie via the middleware:\r\n```\r\npublic function test()\r\n{\r\n return response('test')->cookie('name', 'value');\r\n}\r\n```\r\n\r\n2. Add to routes\r\n3. Write a basic test\r\n```\r\npublic function testCookies()\r\n{\r\n $response = $this->get('test');\r\n $response->assertCookie('name','value');\r\n}\r\n```\r\n4. See the failing test:\r\nCookie [name] was found, but value [791a5xxxxxxxxxx0662|value] does not match [value].\r\nFailed asserting that two strings are equal.\r\nExpected :'value'\r\nActual :'791a5xxxxxxxxxx0662|value'", "comments": [ { "body": "Please upgrade to 7.22.2. :)", "created_at": "2020-07-27T17:28:23Z" }, { "body": "@GrahamCampbell I'm on the latest version and can't get it working. Looking at the source the cookie is decrypted inside the test (not using the EncryptCookies middleware). As in the EncryptCookies middleware the prefix was added, it also needs to be added inside this cookie test.\r\n\r\nI believe you would have to add something like this to the code in https://github.com/laravel/framework/blob/7.x/src/Illuminate/Testing/TestResponse.php#L304\r\n ```\r\n$prefix = hash_hmac('sha1', $cookie->getName().'v2', app('encrypter')->getKey());\r\n\r\nPHPUnit::assertEquals(\r\n $prefix.'|'.$value, $actual,\r\n \"Cookie [{$cookieName}] was found, but value [{$actual}] does not match [{$value}].\"\r\n );\r\n```\r\n", "created_at": "2020-07-27T17:38:57Z" }, { "body": "@SamuelWei are you sure that you're on 7.22.2? Can you run `php artisan --version`?", "created_at": "2020-07-27T18:10:06Z" }, { "body": "@driesvints Yes, I can confirm. Can you run my test without any problems?\r\n![image](https://user-images.githubusercontent.com/4281791/88576209-5b38ee80-d045-11ea-8ab2-746c241893ad.png)\r\n![image](https://user-images.githubusercontent.com/4281791/88576266-74419f80-d045-11ea-8392-ddcad3bc7189.png)\r\n", "created_at": "2020-07-27T18:12:44Z" }, { "body": "@SamuelWei thanks. I think I see the problem. Looking into it now.", "created_at": "2020-07-27T18:16:09Z" }, { "body": "Fixed in v7.22.4\r\nThanks for your quick fix @taylorotwell ", "created_at": "2020-07-27T18:31:34Z" } ], "number": 33671, "title": "[v7.22.0] Changes in EncryptCookies breaks assertCookie test" }
{ "body": "This pull request should add the in v7.22 introduced CookieValuePrefix to the assertCookie test.\r\nFixes #33671 ", "number": 33676, "review_comments": [], "title": "Fix missing cookie prefix" }
{ "commits": [ { "message": "Update TestResponse.php" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n use ArrayAccess;\n use Closure;\n use Illuminate\\Contracts\\View\\View;\n+use Illuminate\\Cookie\\CookieValuePrefix;\n use Illuminate\\Database\\Eloquent\\Model;\n use Illuminate\\Support\\Arr;\n use Illuminate\\Support\\Carbon;\n@@ -302,7 +303,7 @@ public function assertCookie($cookieName, $value = null, $encrypted = true, $uns\n ? app('encrypter')->decrypt($cookieValue, $unserialize) : $cookieValue;\n \n PHPUnit::assertEquals(\n- $value, $actual,\n+ CookieValuePrefix::create($cookie->getName(), app('encrypter')->getKey()).$value, $actual,\n \"Cookie [{$cookieName}] was found, but value [{$actual}] does not match [{$value}].\"\n );\n ", "filename": "src/Illuminate/Testing/TestResponse.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": "Currently, if I set `FilesystemAdapter::putFile`'s argument `$options` as `'public'`, it makes warning.\r\n\r\n```php\r\nFilesystemAdapter::putFile('photos', new File('/path/to/photo'), 'public');\r\n// => Parameter #3 $options of method Illuminate\\Filesystem\\FilesystemAdapter::putFile() expects array, string given.\r\n```\r\n\r\nThis PR fixes it by adding `string` to `@param`.", "number": 33631, "review_comments": [], "title": "[7.x] Fix @param $options type of FilesystemAdapter::putFile" }
{ "commits": [ { "message": "Fix @param $options type of FilesystemAdapter::putFile" } ], "files": [ { "diff": "@@ -236,7 +236,7 @@ public function put($path, $contents, $options = [])\n *\n * @param string $path\n * @param \\Illuminate\\Http\\File|\\Illuminate\\Http\\UploadedFile|string $file\n- * @param array $options\n+ * @param array|string $options\n * @return string|false\n */\n public function putFile($path, $file, $options = [])\n@@ -252,7 +252,7 @@ public function putFile($path, $file, $options = [])\n * @param string $path\n * @param \\Illuminate\\Http\\File|\\Illuminate\\Http\\UploadedFile|string $file\n * @param string $name\n- * @param array $options\n+ * @param array|string $options\n * @return string|false\n */\n public function putFileAs($path, $file, $name, $options = [])", "filename": "src/Illuminate/Filesystem/FilesystemAdapter.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7\r\n- PHP Version: 7.4\r\n- Database Driver & Version: PDP_SQLSRV\r\n\r\n### Description:\r\nWhen creating records of a model using create the returned record will have a wrong value for primary key if the table has a trigger on it which itself creates (inserts) a record in another table.\r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a table (with an auto incrementing primary key) and add a trigger to it which inserts another record in another table). Then calling the create method on the model will return the just created record with the wrong value for the primary key field.\r\n\r\n### Note\r\n\r\nit is the same issue as #27452, close for lack of activity but the problem is still valid\r\n\r\nThe fix [staudenmeir@b4a8f81](https://github.com/staudenmeir/framework/commit/b4a8f81c35c27e65c3fbc92c38afb84bbffcec44) solves the problem but is not integrated into Laravel.", "comments": [ { "body": "@kadevland i dont think this is a laravel bug.\r\n\r\nit seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n\r\n\r\nIts php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n\r\nsee class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`", "created_at": "2020-05-19T09:54:57Z" }, { "body": "@kadevland I would advise using Laravel Eloquent events instead of database triggers for your logic.", "created_at": "2020-05-19T09:56:17Z" }, { "body": "> @kadevland i dont think this is a laravel bug.\r\n> \r\n> it seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n> \r\n> Its php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n> \r\n> see class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`\r\n\r\n\r\nYou see Doctrine fix by append but laravel not append so that my purpose of issu.\r\nIt's Bug of Eloquent can not return write value of ID ( doctrine can, and if do the same in eleoquent )\r\n\r\nYou can't not replace trigger logical by php.\r\n\r\nIt possible to integrete same logical witch use in doctrice and all ready use un driver pgsql in laravel\r\n\r\nfor exemple :\r\n\r\nIlluminate\\Database\\Query\\Grammars\\PostgresGrammar \r\n``` \r\n public function compileInsertGetId(Builder $query, $values, $sequence)\r\n {\r\n return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id');\r\n }\r\n``` \r\nIlluminate\\Database\\Query\\Processors\\PostgresProcessor\r\n``` \r\n public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)\r\n {\r\n $result = $query->getConnection()->selectFromWriteConnection($sql, $values)[0];\r\n\r\n $sequence = $sequence ?: 'id';\r\n\r\n $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\r\n\r\n return is_numeric($id) ? (int) $id : $id;\r\n }\r\n``` \r\n\r\n\r\n\r\n\r\n\r\n\r\n", "created_at": "2020-05-19T10:28:59Z" }, { "body": "Anyone is welcome to PR a fix. I do not use SQL Server nor can I test it easily.", "created_at": "2020-05-19T14:21:52Z" }, { "body": "@taylorotwell Can i add a docker-compose file to test sql-server (Unit)Tests and can this be integrated in the CI build process or not possible?", "created_at": "2020-05-19T15:04:51Z" }, { "body": "@joelharkes i can post DDL table and trigger, make the fixe on sqlsrvGrammar and procces\r\nbut for CI/test i'm not good at all", "created_at": "2020-05-19T19:03:18Z" }, { "body": "I Got a working docker-compose setup for SQL server unit tests.\r\n\r\nNow I have to add the test case and discuss with Laravel team how/where to put my files.\r\n\r\nIt got:\r\n- dockerfile to make php with SQL server drivers\r\n- compose file\r\n- docker entry point file to wait for host & port\r\n- PHP script to create a database in SQL server (it starts without database)\r\n\r\n\r\nWhere do I put these files?\r\nWhat do I do with phpunit tests that should only be executed in this container?", "created_at": "2020-05-20T21:20:44Z" }, { "body": "update: I've got a working unit test, working on fix this week.", "created_at": "2020-05-21T09:15:17Z" }, { "body": "Got a fix working on finalizing PR.", "created_at": "2020-05-21T09:27:27Z" }, { "body": "THX.\r\nWhen you finalizing PR, i will test on my project", "created_at": "2020-05-22T20:30:33Z" }, { "body": "@kadevland fixed it on master, lets see what they say :) you can upvote the PR if you like.", "created_at": "2020-05-25T18:50:57Z" }, { "body": "https://github.com/laravel/framework/pull/32957 was closed pending inactivity but we welcome any help with resurrecting it.", "created_at": "2020-06-25T14:25:10Z" }, { "body": "Fixed by @rodrigopedra in https://github.com/laravel/framework/pull/33430\r\n\r\nThanks!", "created_at": "2020-07-04T16:24:19Z" }, { "body": "thx @rodrigopedra ", "created_at": "2020-07-04T23:18:58Z" }, { "body": "You're welcome!", "created_at": "2020-07-05T00:40:11Z" }, { "body": "Re-opened because we had to revert the fix. It caused failures on certain drivers. See https://github.com/laravel/framework/pull/33496", "created_at": "2020-07-10T11:34:21Z" }, { "body": "When doing a new attempt we should keep in mind https://github.com/laravel/framework/issues/33485", "created_at": "2020-07-10T11:36:57Z" }, { "body": "I've dealt with this in my own production environment, and it was an issue caused by inserting another record during an `INSERT` trigger, since `SCOPE_IDENTITY` will return the lastly inserted ID in execution the scope.\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-429909285\r\n\r\nResource:\r\n\r\nhttps://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-2017\r\n\r\nThe fix was to reset the `SCOPE_IDENTITY` on the `INSERT` trigger, which can be done like so:\r\n\r\n```sql\r\n-- The trigger\r\nALTER TRIGGER [Inventory].[OnInsertTriggerHistory] ON [Inventory].[Inventory] \r\nFOR INSERT AS\r\n\r\nSET NOCOUNT ON\r\n\r\n-- The child table insert\r\nINSERT INTO [Inventory].[InventoryHistory] (...) VALUES (...)\r\n\r\n-- Reset the `SCOPE_IDENTITY()` by performing an insert into a temp table.\r\nIF (SELECT COUNT(1) from inserted) = 1 BEGIN \r\n CREATE TABLE #TempIdTable (ResetIdentity int identity(1, 1))\r\n \r\n SET identity_insert #TempIdTable ON\r\n INSERT INTO #TempIdTable (ResetIdentity)\r\n SELECT InventoryId FROM inserted SET identity_insert #TempIdTable OFF\r\nEND\r\n\r\n-- Drop the temp table if it exists.\r\nIF OBJECT_ID('tempdb..#TempIdTable') IS NOT NULL DROP TABLE #TempIdTable\r\n```\r\n\r\nI'm skeptical on calling this an Laravel issue...", "created_at": "2020-07-13T21:07:13Z" }, { "body": "For some projects the application developer does not have accesses to change database triggers. \r\n\r\nAs noted by another comment on the thread @stevebauman linked, adding the `SET NO COUNT` before the `INSERT`, and adding the `SELECT SCOPE_IDENTITY` to the same clause makes PDO to return the expected last inserted ID:\r\n\r\nReferences:\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-352672920\r\nAnd https://github.com/microsoft/msphpsql/issues/288#issuecomment-352814829\r\n\r\nI agree with @stevebauman that this is not primarily a Laravel issue. But as this can be *\"workaround-ed\"* I would add it to Laravel.\r\n\r\nIssue is allowing any driver like the freeTDS one. If we restrict SQL Server drivers to the official one from Microsoft, fixes introduced by PR #33430 would work.\r\n\r\nReason I reverted that PR is because it was targeted to v6.x (LTS) and v7.x that broke some apps that used the unofficial freeTDS driver. \r\n\r\nBut I guess that for a newer version (8 maybe) we can add a requirement to only support Microsoft official drivers. \r\n", "created_at": "2020-07-15T11:01:21Z" }, { "body": "Amazing work on that PR @rodrigopedra! 🙌\r\n\r\nIs there any possibility we could have a flag inside the developers `sqlsrv` configuration that enables / swaps compatibility with FreeTDS, while the MSSQL driver is supported by default?\r\n\r\nWe would of course have to create separate grammars or grammar methods to compile the insert statement. But then instead of dropping support completely, users can set the flag to true (maybe `'freetds' => true`).\r\n\r\nWhat are your thoughts?\r\n\r\nSince we have access to the configuration in the `SqlServerConnection` we could, we could retrieve this option and apply it to the `Grammar` instance:\r\n\r\nhttps://github.com/laravel/framework/blob/d3d36f059ef1c56e17d8e434e9fd3dfd6cbe6e53/src/Illuminate/Database/SqlServerConnection.php#L55-L63\r\n\r\n**Example:**\r\n```php\r\n/**\r\n * Get the default query grammar instance.\r\n *\r\n * @return \\Illuminate\\Database\\Query\\Grammars\\SqlServerGrammar\r\n */\r\nprotected function getDefaultQueryGrammar()\r\n{\r\n $grammar = new QueryGrammar;\r\n \r\n if ($this->getConfig('freetds') === true) {\r\n $grammar->usingFreeTds();\r\n }\r\n \r\n return $this->withTablePrefix($grammar);\r\n}\r\n```\r\n\r\nOr, even better, if we have the ability to detect which Sqlsrv driver is being used, then can enable the `Grammar` option without breaking backwards compatibility. Not sure if this is doable though...", "created_at": "2020-07-15T12:24:20Z" }, { "body": "Thanks @stevebauman !\r\n\r\nOne of the suggestions I made in here:\r\n\r\nhttps://github.com/laravel/framework/pull/33430#commitcomment-40493561\r\n\r\nWas having some feature detection in place for that.\r\n\r\nLaravel already does that for the ODBC driver:\r\n\r\nhttps://github.com/laravel/framework/blob/97c8d87991672604e22f2a7c05e717ea2743aa0b/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php#L26-L30\r\n\r\nBut I fear adding more branches to that `if` should be a reason to drop SQL Server support altogether.\r\n\r\nI still think that adding the requirement to use the official driver is a better way to go, as it would simplify code and make maintenance easier. Support for alternative drivers could be added by third-party packages.\r\n", "created_at": "2020-07-15T16:06:37Z" }, { "body": "How much drivers are there for SQL Server and how popular are they?", "created_at": "2020-07-16T15:41:37Z" }, { "body": "@driesvints All I know of is the [official SQL Server drivers](https://github.com/microsoft/msphpsql/releases) and [FreeTDS](http://www.freetds.org), but I haven't touched FreeTDS since PHP 5.4. Unsure why anyone would use FreeTDS over the official drivers to be honest, maybe for legacy Ubuntu servers?\r\n\r\n@rodrigopedra You're right, if it gets too complicated then it's probably best to support only the official SQL Server driver from Microsoft. However, if it's only one additional `if` statement to offer a fix **and** backwards compatibility, I'm not sure if that's a large maintenance overhead (imho).", "created_at": "2020-07-16T15:58:11Z" }, { "body": "@stevebauman well, if it's really one if statement I suspect we would have resolved this issue much sooner. I also don't think it's reasonable to support every driver out there. But I want to figure out how much there are and how popular they are first.", "created_at": "2020-07-16T16:01:02Z" }, { "body": "Apologies @driesvints, I wasn't intending to oversimplify the issue. I was referring to the need to extract both the PR's logic, and the in-place working logic (that is already working with FreeTDS) into two separate method calls and adding an `if` to simply check if the server is using the FreeTDS driver, or the Microsoft SQL Driver -- then execute the compatible insert.", "created_at": "2020-07-16T16:21:56Z" }, { "body": "No need to apologize :)", "created_at": "2020-07-16T16:55:01Z" }, { "body": "Since this issue has only been raised by a single person and @stevebauman has since posted a fix in the trigger itself (no response from OP) I'm going to close this.", "created_at": "2020-09-23T20:01:21Z" }, { "body": "This is still an issue in 2021\r\n\r\n`$post = Post::create([\r\n 'author_id' => $request->author,\r\n 'series_id' => $request->series,\r\n 'content' => $request->content,\r\n ]);\r\n`\r\nAfter calling create method, `$post->id` will have a wrong value.", "created_at": "2021-09-10T13:13:11Z" }, { "body": "Hi @peter-olom, do you have any `insert` SQL triggers tied to your `posts` DB table? \r\n\r\nIf you're going to say this is still an issue, then you have to create a programmatic test illustrating such. Saying it's still an issue provides maintainers nothing to work with.\r\n\r\nYou can utilize Azure SQL Server for free in GitHub actions if you'd like to take on the task: https://docs.microsoft.com/en-us/azure/azure-sql/database/connect-github-actions-sql-db", "created_at": "2021-09-10T13:22:08Z" }, { "body": "> This is still an issue in 2021\r\n\r\nOf course it is, the fix was reverted to avoid breaking apps that were using different drivers, as described in the thread above.\r\n\r\nIf you read all the thread you will see no changes were made, as there is a workaround one can make to their own database server to circumvent this.\r\n\r\nBy the way, have you tried adding the trigger workaround by @stevebauman above?\r\n\r\nIf you think the framework should drop support for other SQL Servers drivers that didn't work out with the fix sent in 2020, without requiring developers to use the trigger workaround available in this thread, I would suggest you to:\r\n\r\n- send a PR re-submitting the fix, or better yet with an improved fix that might work with users using the FreeTDS driver\r\n- If a fix cannot accommodate FreeTDS applications, discuss with the maintainers if only the drivers from Microsoft should be supported\r\n- If they agree, send a PR to the docs clarifying this new requirement and noting it in the upgrade docs\r\n\r\nUntil an alternative fix that works for both Microsoft drivers and FreeTDS drivers, or an agreement on only supporting Microsoft official drivers and using the then proposed fix sent in 2020, or an improved one, please try using the trigger workaround as discussed in the thread.\r\n ", "created_at": "2021-09-10T13:24:43Z" } ], "number": 32883, "title": "Create method on model returning wrong primary key value (SQLSRV)" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\n***This is the same as PR #33488 but target at 6.x branch, text below is adapted from that PR***\r\n\r\nAs noted by issue #33485 PR #33453 (backport of #33430) breaks a Laravel app when using the freeTDS driver to connect to SQL Server.\r\n\r\nPR PR #33453 (backport of #33430) was sent to address issue #32883, but when implementing it I didn't test it against freeTDS drivers. I only tested against Microsoft official drivers ( https://github.com/Microsoft/msphpsql ). It seems freeTDS is widely used , specially with older versions of SQL Server.\r\n\r\nAfter the issue was reported I started investigating a solution that could solve both issues #33485 and #32883 but I could not find one. \r\n\r\nSo I am sending this PR to revert the changes made. Issue #32883 will still need to be addressed after reverting it.\r\n\r\nI shared some of my findings on a comment on PR #33430 discussion and also presented some alternatives. Please refer to comment https://github.com/laravel/framework/pull/33430#commitcomment-40493561 to have more details about it.\r\n\r\nThere I said I would send PR for both 6.x and 7.x branches, but I will wait on feedback on this one before sending the second one as maintainers could have a different workflow on back porting features and fixes.\r\n\r\nIf someone has a better suggestion on how to address this I would be glad to help.\r\n", "number": 33496, "review_comments": [], "title": "[6.x] revert PR #33453 (backport of #33430)" }
{ "commits": [ { "message": "revert PR #33453" } ], "files": [ { "diff": "@@ -305,19 +305,6 @@ public function compileExists(Builder $query)\n return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1));\n }\n \n- /**\n- * Compile an insert and get ID statement into SQL.\n- *\n- * @param \\Illuminate\\Database\\Query\\Builder $query\n- * @param array $values\n- * @param string $sequence\n- * @return string\n- */\n- public function compileInsertGetId(Builder $query, $values, $sequence)\n- {\n- return 'set nocount on;'.$this->compileInsert($query, $values).';select scope_identity() as '.$this->wrap($sequence ?: 'id');\n- }\n-\n /**\n * Compile an update statement with joins into SQL.\n *", "filename": "src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -2,6 +2,8 @@\n \n namespace Illuminate\\Database\\Query\\Processors;\n \n+use Exception;\n+use Illuminate\\Database\\Connection;\n use Illuminate\\Database\\Query\\Builder;\n \n class SqlServerProcessor extends Processor\n@@ -19,15 +21,38 @@ public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu\n {\n $connection = $query->getConnection();\n \n- $connection->recordsHaveBeenModified();\n+ $connection->insert($sql, $values);\n \n- $result = $connection->selectFromWriteConnection($sql, $values)[0];\n+ if ($connection->getConfig('odbc') === true) {\n+ $id = $this->processInsertGetIdForOdbc($connection);\n+ } else {\n+ $id = $connection->getPdo()->lastInsertId();\n+ }\n \n- $sequence = $sequence ?: 'id';\n+ return is_numeric($id) ? (int) $id : $id;\n+ }\n \n- $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\n+ /**\n+ * Process an \"insert get ID\" query for ODBC.\n+ *\n+ * @param \\Illuminate\\Database\\Connection $connection\n+ * @return int\n+ *\n+ * @throws \\Exception\n+ */\n+ protected function processInsertGetIdForOdbc(Connection $connection)\n+ {\n+ $result = $connection->selectFromWriteConnection(\n+ 'SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'\n+ );\n \n- return is_numeric($id) ? (int) $id : $id;\n+ if (! $result) {\n+ throw new Exception('Unable to retrieve lastInsertID for ODBC.');\n+ }\n+\n+ $row = $result[0];\n+\n+ return is_object($row) ? $row->insertid : $row['insertid'];\n }\n \n /**", "filename": "src/Illuminate/Database/Query/Processors/SqlServerProcessor.php", "status": "modified" }, { "diff": "@@ -2071,7 +2071,7 @@ public function testInsertGetIdWithEmptyValues()\n $builder->from('users')->insertGetId([]);\n \n $builder = $this->getSqlServerBuilder();\n- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'set nocount on;insert into [users] default values;select scope_identity() as [id]', [], null);\n+ $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'insert into [users] default values', [], null);\n $builder->from('users')->insertGetId([]);\n }\n \n@@ -2410,14 +2410,6 @@ public function testPostgresInsertGetId()\n $this->assertEquals(1, $result);\n }\n \n- public function testSqlServerInsertGetId()\n- {\n- $builder = $this->getSqlServerBuilder();\n- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'set nocount on;insert into [users] ([email]) values (?);select scope_identity() as [id]', ['foo'], 'id')->andReturn(1);\n- $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id');\n- $this->assertEquals(1, $result);\n- }\n-\n public function testMySqlWrapping()\n {\n $builder = $this->getMySqlBuilder();", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7\r\n- PHP Version: 7.4\r\n- Database Driver & Version: PDP_SQLSRV\r\n\r\n### Description:\r\nWhen creating records of a model using create the returned record will have a wrong value for primary key if the table has a trigger on it which itself creates (inserts) a record in another table.\r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a table (with an auto incrementing primary key) and add a trigger to it which inserts another record in another table). Then calling the create method on the model will return the just created record with the wrong value for the primary key field.\r\n\r\n### Note\r\n\r\nit is the same issue as #27452, close for lack of activity but the problem is still valid\r\n\r\nThe fix [staudenmeir@b4a8f81](https://github.com/staudenmeir/framework/commit/b4a8f81c35c27e65c3fbc92c38afb84bbffcec44) solves the problem but is not integrated into Laravel.", "comments": [ { "body": "@kadevland i dont think this is a laravel bug.\r\n\r\nit seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n\r\n\r\nIts php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n\r\nsee class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`", "created_at": "2020-05-19T09:54:57Z" }, { "body": "@kadevland I would advise using Laravel Eloquent events instead of database triggers for your logic.", "created_at": "2020-05-19T09:56:17Z" }, { "body": "> @kadevland i dont think this is a laravel bug.\r\n> \r\n> it seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n> \r\n> Its php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n> \r\n> see class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`\r\n\r\n\r\nYou see Doctrine fix by append but laravel not append so that my purpose of issu.\r\nIt's Bug of Eloquent can not return write value of ID ( doctrine can, and if do the same in eleoquent )\r\n\r\nYou can't not replace trigger logical by php.\r\n\r\nIt possible to integrete same logical witch use in doctrice and all ready use un driver pgsql in laravel\r\n\r\nfor exemple :\r\n\r\nIlluminate\\Database\\Query\\Grammars\\PostgresGrammar \r\n``` \r\n public function compileInsertGetId(Builder $query, $values, $sequence)\r\n {\r\n return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id');\r\n }\r\n``` \r\nIlluminate\\Database\\Query\\Processors\\PostgresProcessor\r\n``` \r\n public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)\r\n {\r\n $result = $query->getConnection()->selectFromWriteConnection($sql, $values)[0];\r\n\r\n $sequence = $sequence ?: 'id';\r\n\r\n $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\r\n\r\n return is_numeric($id) ? (int) $id : $id;\r\n }\r\n``` \r\n\r\n\r\n\r\n\r\n\r\n\r\n", "created_at": "2020-05-19T10:28:59Z" }, { "body": "Anyone is welcome to PR a fix. I do not use SQL Server nor can I test it easily.", "created_at": "2020-05-19T14:21:52Z" }, { "body": "@taylorotwell Can i add a docker-compose file to test sql-server (Unit)Tests and can this be integrated in the CI build process or not possible?", "created_at": "2020-05-19T15:04:51Z" }, { "body": "@joelharkes i can post DDL table and trigger, make the fixe on sqlsrvGrammar and procces\r\nbut for CI/test i'm not good at all", "created_at": "2020-05-19T19:03:18Z" }, { "body": "I Got a working docker-compose setup for SQL server unit tests.\r\n\r\nNow I have to add the test case and discuss with Laravel team how/where to put my files.\r\n\r\nIt got:\r\n- dockerfile to make php with SQL server drivers\r\n- compose file\r\n- docker entry point file to wait for host & port\r\n- PHP script to create a database in SQL server (it starts without database)\r\n\r\n\r\nWhere do I put these files?\r\nWhat do I do with phpunit tests that should only be executed in this container?", "created_at": "2020-05-20T21:20:44Z" }, { "body": "update: I've got a working unit test, working on fix this week.", "created_at": "2020-05-21T09:15:17Z" }, { "body": "Got a fix working on finalizing PR.", "created_at": "2020-05-21T09:27:27Z" }, { "body": "THX.\r\nWhen you finalizing PR, i will test on my project", "created_at": "2020-05-22T20:30:33Z" }, { "body": "@kadevland fixed it on master, lets see what they say :) you can upvote the PR if you like.", "created_at": "2020-05-25T18:50:57Z" }, { "body": "https://github.com/laravel/framework/pull/32957 was closed pending inactivity but we welcome any help with resurrecting it.", "created_at": "2020-06-25T14:25:10Z" }, { "body": "Fixed by @rodrigopedra in https://github.com/laravel/framework/pull/33430\r\n\r\nThanks!", "created_at": "2020-07-04T16:24:19Z" }, { "body": "thx @rodrigopedra ", "created_at": "2020-07-04T23:18:58Z" }, { "body": "You're welcome!", "created_at": "2020-07-05T00:40:11Z" }, { "body": "Re-opened because we had to revert the fix. It caused failures on certain drivers. See https://github.com/laravel/framework/pull/33496", "created_at": "2020-07-10T11:34:21Z" }, { "body": "When doing a new attempt we should keep in mind https://github.com/laravel/framework/issues/33485", "created_at": "2020-07-10T11:36:57Z" }, { "body": "I've dealt with this in my own production environment, and it was an issue caused by inserting another record during an `INSERT` trigger, since `SCOPE_IDENTITY` will return the lastly inserted ID in execution the scope.\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-429909285\r\n\r\nResource:\r\n\r\nhttps://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-2017\r\n\r\nThe fix was to reset the `SCOPE_IDENTITY` on the `INSERT` trigger, which can be done like so:\r\n\r\n```sql\r\n-- The trigger\r\nALTER TRIGGER [Inventory].[OnInsertTriggerHistory] ON [Inventory].[Inventory] \r\nFOR INSERT AS\r\n\r\nSET NOCOUNT ON\r\n\r\n-- The child table insert\r\nINSERT INTO [Inventory].[InventoryHistory] (...) VALUES (...)\r\n\r\n-- Reset the `SCOPE_IDENTITY()` by performing an insert into a temp table.\r\nIF (SELECT COUNT(1) from inserted) = 1 BEGIN \r\n CREATE TABLE #TempIdTable (ResetIdentity int identity(1, 1))\r\n \r\n SET identity_insert #TempIdTable ON\r\n INSERT INTO #TempIdTable (ResetIdentity)\r\n SELECT InventoryId FROM inserted SET identity_insert #TempIdTable OFF\r\nEND\r\n\r\n-- Drop the temp table if it exists.\r\nIF OBJECT_ID('tempdb..#TempIdTable') IS NOT NULL DROP TABLE #TempIdTable\r\n```\r\n\r\nI'm skeptical on calling this an Laravel issue...", "created_at": "2020-07-13T21:07:13Z" }, { "body": "For some projects the application developer does not have accesses to change database triggers. \r\n\r\nAs noted by another comment on the thread @stevebauman linked, adding the `SET NO COUNT` before the `INSERT`, and adding the `SELECT SCOPE_IDENTITY` to the same clause makes PDO to return the expected last inserted ID:\r\n\r\nReferences:\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-352672920\r\nAnd https://github.com/microsoft/msphpsql/issues/288#issuecomment-352814829\r\n\r\nI agree with @stevebauman that this is not primarily a Laravel issue. But as this can be *\"workaround-ed\"* I would add it to Laravel.\r\n\r\nIssue is allowing any driver like the freeTDS one. If we restrict SQL Server drivers to the official one from Microsoft, fixes introduced by PR #33430 would work.\r\n\r\nReason I reverted that PR is because it was targeted to v6.x (LTS) and v7.x that broke some apps that used the unofficial freeTDS driver. \r\n\r\nBut I guess that for a newer version (8 maybe) we can add a requirement to only support Microsoft official drivers. \r\n", "created_at": "2020-07-15T11:01:21Z" }, { "body": "Amazing work on that PR @rodrigopedra! 🙌\r\n\r\nIs there any possibility we could have a flag inside the developers `sqlsrv` configuration that enables / swaps compatibility with FreeTDS, while the MSSQL driver is supported by default?\r\n\r\nWe would of course have to create separate grammars or grammar methods to compile the insert statement. But then instead of dropping support completely, users can set the flag to true (maybe `'freetds' => true`).\r\n\r\nWhat are your thoughts?\r\n\r\nSince we have access to the configuration in the `SqlServerConnection` we could, we could retrieve this option and apply it to the `Grammar` instance:\r\n\r\nhttps://github.com/laravel/framework/blob/d3d36f059ef1c56e17d8e434e9fd3dfd6cbe6e53/src/Illuminate/Database/SqlServerConnection.php#L55-L63\r\n\r\n**Example:**\r\n```php\r\n/**\r\n * Get the default query grammar instance.\r\n *\r\n * @return \\Illuminate\\Database\\Query\\Grammars\\SqlServerGrammar\r\n */\r\nprotected function getDefaultQueryGrammar()\r\n{\r\n $grammar = new QueryGrammar;\r\n \r\n if ($this->getConfig('freetds') === true) {\r\n $grammar->usingFreeTds();\r\n }\r\n \r\n return $this->withTablePrefix($grammar);\r\n}\r\n```\r\n\r\nOr, even better, if we have the ability to detect which Sqlsrv driver is being used, then can enable the `Grammar` option without breaking backwards compatibility. Not sure if this is doable though...", "created_at": "2020-07-15T12:24:20Z" }, { "body": "Thanks @stevebauman !\r\n\r\nOne of the suggestions I made in here:\r\n\r\nhttps://github.com/laravel/framework/pull/33430#commitcomment-40493561\r\n\r\nWas having some feature detection in place for that.\r\n\r\nLaravel already does that for the ODBC driver:\r\n\r\nhttps://github.com/laravel/framework/blob/97c8d87991672604e22f2a7c05e717ea2743aa0b/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php#L26-L30\r\n\r\nBut I fear adding more branches to that `if` should be a reason to drop SQL Server support altogether.\r\n\r\nI still think that adding the requirement to use the official driver is a better way to go, as it would simplify code and make maintenance easier. Support for alternative drivers could be added by third-party packages.\r\n", "created_at": "2020-07-15T16:06:37Z" }, { "body": "How much drivers are there for SQL Server and how popular are they?", "created_at": "2020-07-16T15:41:37Z" }, { "body": "@driesvints All I know of is the [official SQL Server drivers](https://github.com/microsoft/msphpsql/releases) and [FreeTDS](http://www.freetds.org), but I haven't touched FreeTDS since PHP 5.4. Unsure why anyone would use FreeTDS over the official drivers to be honest, maybe for legacy Ubuntu servers?\r\n\r\n@rodrigopedra You're right, if it gets too complicated then it's probably best to support only the official SQL Server driver from Microsoft. However, if it's only one additional `if` statement to offer a fix **and** backwards compatibility, I'm not sure if that's a large maintenance overhead (imho).", "created_at": "2020-07-16T15:58:11Z" }, { "body": "@stevebauman well, if it's really one if statement I suspect we would have resolved this issue much sooner. I also don't think it's reasonable to support every driver out there. But I want to figure out how much there are and how popular they are first.", "created_at": "2020-07-16T16:01:02Z" }, { "body": "Apologies @driesvints, I wasn't intending to oversimplify the issue. I was referring to the need to extract both the PR's logic, and the in-place working logic (that is already working with FreeTDS) into two separate method calls and adding an `if` to simply check if the server is using the FreeTDS driver, or the Microsoft SQL Driver -- then execute the compatible insert.", "created_at": "2020-07-16T16:21:56Z" }, { "body": "No need to apologize :)", "created_at": "2020-07-16T16:55:01Z" }, { "body": "Since this issue has only been raised by a single person and @stevebauman has since posted a fix in the trigger itself (no response from OP) I'm going to close this.", "created_at": "2020-09-23T20:01:21Z" }, { "body": "This is still an issue in 2021\r\n\r\n`$post = Post::create([\r\n 'author_id' => $request->author,\r\n 'series_id' => $request->series,\r\n 'content' => $request->content,\r\n ]);\r\n`\r\nAfter calling create method, `$post->id` will have a wrong value.", "created_at": "2021-09-10T13:13:11Z" }, { "body": "Hi @peter-olom, do you have any `insert` SQL triggers tied to your `posts` DB table? \r\n\r\nIf you're going to say this is still an issue, then you have to create a programmatic test illustrating such. Saying it's still an issue provides maintainers nothing to work with.\r\n\r\nYou can utilize Azure SQL Server for free in GitHub actions if you'd like to take on the task: https://docs.microsoft.com/en-us/azure/azure-sql/database/connect-github-actions-sql-db", "created_at": "2021-09-10T13:22:08Z" }, { "body": "> This is still an issue in 2021\r\n\r\nOf course it is, the fix was reverted to avoid breaking apps that were using different drivers, as described in the thread above.\r\n\r\nIf you read all the thread you will see no changes were made, as there is a workaround one can make to their own database server to circumvent this.\r\n\r\nBy the way, have you tried adding the trigger workaround by @stevebauman above?\r\n\r\nIf you think the framework should drop support for other SQL Servers drivers that didn't work out with the fix sent in 2020, without requiring developers to use the trigger workaround available in this thread, I would suggest you to:\r\n\r\n- send a PR re-submitting the fix, or better yet with an improved fix that might work with users using the FreeTDS driver\r\n- If a fix cannot accommodate FreeTDS applications, discuss with the maintainers if only the drivers from Microsoft should be supported\r\n- If they agree, send a PR to the docs clarifying this new requirement and noting it in the upgrade docs\r\n\r\nUntil an alternative fix that works for both Microsoft drivers and FreeTDS drivers, or an agreement on only supporting Microsoft official drivers and using the then proposed fix sent in 2020, or an improved one, please try using the trigger workaround as discussed in the thread.\r\n ", "created_at": "2021-09-10T13:24:43Z" } ], "number": 32883, "title": "Create method on model returning wrong primary key value (SQLSRV)" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nAs noted by issue #33485 PR #33430 breaks a Laravel app when using the freeTDS driver to connect to SQL Server.\r\n\r\nPR #33430 was sent to address issue #32883, but when implementing it I didn't test it against freeTDS drivers. I only tested against Microsoft official drivers ( https://github.com/Microsoft/msphpsql ). It seems freeTDS ise widely used , specially with older versions of SQL Server.\r\n\r\nAfter the issue was reported I started investigating a solution that could solve both issues #33485 and #32883 but I could not find one. \r\n\r\nSo I am sending this PR to revert the changes made. Issue #32883 will still need to be addressed after reverting it.\r\n\r\nI shared some of my findings on a comment on PR #33430 discussion and also presented some alternatives. Please refer to comment https://github.com/laravel/framework/pull/33430#commitcomment-40493561 to have more details about it.\r\n\r\nThere I said I would send PR for both 6.x and 7.x branches, but I will wait on feedback on this one before sending the second one as maintainers could have a different workflow on back porting features and fixes.\r\n\r\nIf someone has a better suggestion on how to address this I would be glad to help.\r\n", "number": 33488, "review_comments": [], "title": "[7.x] revert PR #33430" }
{ "commits": [ { "message": "revert PR #33430" } ], "files": [ { "diff": "@@ -323,19 +323,6 @@ public function compileExists(Builder $query)\n return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1));\n }\n \n- /**\n- * Compile an insert and get ID statement into SQL.\n- *\n- * @param \\Illuminate\\Database\\Query\\Builder $query\n- * @param array $values\n- * @param string $sequence\n- * @return string\n- */\n- public function compileInsertGetId(Builder $query, $values, $sequence)\n- {\n- return 'set nocount on;'.$this->compileInsert($query, $values).';select scope_identity() as '.$this->wrap($sequence ?: 'id');\n- }\n-\n /**\n * Compile an update statement with joins into SQL.\n *", "filename": "src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -2,6 +2,8 @@\n \n namespace Illuminate\\Database\\Query\\Processors;\n \n+use Exception;\n+use Illuminate\\Database\\Connection;\n use Illuminate\\Database\\Query\\Builder;\n \n class SqlServerProcessor extends Processor\n@@ -19,15 +21,38 @@ public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu\n {\n $connection = $query->getConnection();\n \n- $connection->recordsHaveBeenModified();\n+ $connection->insert($sql, $values);\n \n- $result = $connection->selectFromWriteConnection($sql, $values)[0];\n+ if ($connection->getConfig('odbc') === true) {\n+ $id = $this->processInsertGetIdForOdbc($connection);\n+ } else {\n+ $id = $connection->getPdo()->lastInsertId();\n+ }\n \n- $sequence = $sequence ?: 'id';\n+ return is_numeric($id) ? (int) $id : $id;\n+ }\n \n- $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\n+ /**\n+ * Process an \"insert get ID\" query for ODBC.\n+ *\n+ * @param \\Illuminate\\Database\\Connection $connection\n+ * @return int\n+ *\n+ * @throws \\Exception\n+ */\n+ protected function processInsertGetIdForOdbc(Connection $connection)\n+ {\n+ $result = $connection->selectFromWriteConnection(\n+ 'SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'\n+ );\n \n- return is_numeric($id) ? (int) $id : $id;\n+ if (! $result) {\n+ throw new Exception('Unable to retrieve lastInsertID for ODBC.');\n+ }\n+\n+ $row = $result[0];\n+\n+ return is_object($row) ? $row->insertid : $row['insertid'];\n }\n \n /**", "filename": "src/Illuminate/Database/Query/Processors/SqlServerProcessor.php", "status": "modified" }, { "diff": "@@ -2130,7 +2130,7 @@ public function testInsertGetIdWithEmptyValues()\n $builder->from('users')->insertGetId([]);\n \n $builder = $this->getSqlServerBuilder();\n- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'set nocount on;insert into [users] default values;select scope_identity() as [id]', [], null);\n+ $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'insert into [users] default values', [], null);\n $builder->from('users')->insertGetId([]);\n }\n \n@@ -2474,14 +2474,6 @@ public function testPostgresInsertGetId()\n $this->assertEquals(1, $result);\n }\n \n- public function testSqlServerInsertGetId()\n- {\n- $builder = $this->getSqlServerBuilder();\n- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'set nocount on;insert into [users] ([email]) values (?);select scope_identity() as [id]', ['foo'], 'id')->andReturn(1);\n- $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id');\n- $this->assertEquals(1, $result);\n- }\n-\n public function testMySqlWrapping()\n {\n $builder = $this->getMySqlBuilder();", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7\r\n- PHP Version: 7.4\r\n- Database Driver & Version: PDP_SQLSRV\r\n\r\n### Description:\r\nWhen creating records of a model using create the returned record will have a wrong value for primary key if the table has a trigger on it which itself creates (inserts) a record in another table.\r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a table (with an auto incrementing primary key) and add a trigger to it which inserts another record in another table). Then calling the create method on the model will return the just created record with the wrong value for the primary key field.\r\n\r\n### Note\r\n\r\nit is the same issue as #27452, close for lack of activity but the problem is still valid\r\n\r\nThe fix [staudenmeir@b4a8f81](https://github.com/staudenmeir/framework/commit/b4a8f81c35c27e65c3fbc92c38afb84bbffcec44) solves the problem but is not integrated into Laravel.", "comments": [ { "body": "@kadevland i dont think this is a laravel bug.\r\n\r\nit seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n\r\n\r\nIts php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n\r\nsee class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`", "created_at": "2020-05-19T09:54:57Z" }, { "body": "@kadevland I would advise using Laravel Eloquent events instead of database triggers for your logic.", "created_at": "2020-05-19T09:56:17Z" }, { "body": "> @kadevland i dont think this is a laravel bug.\r\n> \r\n> it seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n> \r\n> Its php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n> \r\n> see class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`\r\n\r\n\r\nYou see Doctrine fix by append but laravel not append so that my purpose of issu.\r\nIt's Bug of Eloquent can not return write value of ID ( doctrine can, and if do the same in eleoquent )\r\n\r\nYou can't not replace trigger logical by php.\r\n\r\nIt possible to integrete same logical witch use in doctrice and all ready use un driver pgsql in laravel\r\n\r\nfor exemple :\r\n\r\nIlluminate\\Database\\Query\\Grammars\\PostgresGrammar \r\n``` \r\n public function compileInsertGetId(Builder $query, $values, $sequence)\r\n {\r\n return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id');\r\n }\r\n``` \r\nIlluminate\\Database\\Query\\Processors\\PostgresProcessor\r\n``` \r\n public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)\r\n {\r\n $result = $query->getConnection()->selectFromWriteConnection($sql, $values)[0];\r\n\r\n $sequence = $sequence ?: 'id';\r\n\r\n $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\r\n\r\n return is_numeric($id) ? (int) $id : $id;\r\n }\r\n``` \r\n\r\n\r\n\r\n\r\n\r\n\r\n", "created_at": "2020-05-19T10:28:59Z" }, { "body": "Anyone is welcome to PR a fix. I do not use SQL Server nor can I test it easily.", "created_at": "2020-05-19T14:21:52Z" }, { "body": "@taylorotwell Can i add a docker-compose file to test sql-server (Unit)Tests and can this be integrated in the CI build process or not possible?", "created_at": "2020-05-19T15:04:51Z" }, { "body": "@joelharkes i can post DDL table and trigger, make the fixe on sqlsrvGrammar and procces\r\nbut for CI/test i'm not good at all", "created_at": "2020-05-19T19:03:18Z" }, { "body": "I Got a working docker-compose setup for SQL server unit tests.\r\n\r\nNow I have to add the test case and discuss with Laravel team how/where to put my files.\r\n\r\nIt got:\r\n- dockerfile to make php with SQL server drivers\r\n- compose file\r\n- docker entry point file to wait for host & port\r\n- PHP script to create a database in SQL server (it starts without database)\r\n\r\n\r\nWhere do I put these files?\r\nWhat do I do with phpunit tests that should only be executed in this container?", "created_at": "2020-05-20T21:20:44Z" }, { "body": "update: I've got a working unit test, working on fix this week.", "created_at": "2020-05-21T09:15:17Z" }, { "body": "Got a fix working on finalizing PR.", "created_at": "2020-05-21T09:27:27Z" }, { "body": "THX.\r\nWhen you finalizing PR, i will test on my project", "created_at": "2020-05-22T20:30:33Z" }, { "body": "@kadevland fixed it on master, lets see what they say :) you can upvote the PR if you like.", "created_at": "2020-05-25T18:50:57Z" }, { "body": "https://github.com/laravel/framework/pull/32957 was closed pending inactivity but we welcome any help with resurrecting it.", "created_at": "2020-06-25T14:25:10Z" }, { "body": "Fixed by @rodrigopedra in https://github.com/laravel/framework/pull/33430\r\n\r\nThanks!", "created_at": "2020-07-04T16:24:19Z" }, { "body": "thx @rodrigopedra ", "created_at": "2020-07-04T23:18:58Z" }, { "body": "You're welcome!", "created_at": "2020-07-05T00:40:11Z" }, { "body": "Re-opened because we had to revert the fix. It caused failures on certain drivers. See https://github.com/laravel/framework/pull/33496", "created_at": "2020-07-10T11:34:21Z" }, { "body": "When doing a new attempt we should keep in mind https://github.com/laravel/framework/issues/33485", "created_at": "2020-07-10T11:36:57Z" }, { "body": "I've dealt with this in my own production environment, and it was an issue caused by inserting another record during an `INSERT` trigger, since `SCOPE_IDENTITY` will return the lastly inserted ID in execution the scope.\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-429909285\r\n\r\nResource:\r\n\r\nhttps://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-2017\r\n\r\nThe fix was to reset the `SCOPE_IDENTITY` on the `INSERT` trigger, which can be done like so:\r\n\r\n```sql\r\n-- The trigger\r\nALTER TRIGGER [Inventory].[OnInsertTriggerHistory] ON [Inventory].[Inventory] \r\nFOR INSERT AS\r\n\r\nSET NOCOUNT ON\r\n\r\n-- The child table insert\r\nINSERT INTO [Inventory].[InventoryHistory] (...) VALUES (...)\r\n\r\n-- Reset the `SCOPE_IDENTITY()` by performing an insert into a temp table.\r\nIF (SELECT COUNT(1) from inserted) = 1 BEGIN \r\n CREATE TABLE #TempIdTable (ResetIdentity int identity(1, 1))\r\n \r\n SET identity_insert #TempIdTable ON\r\n INSERT INTO #TempIdTable (ResetIdentity)\r\n SELECT InventoryId FROM inserted SET identity_insert #TempIdTable OFF\r\nEND\r\n\r\n-- Drop the temp table if it exists.\r\nIF OBJECT_ID('tempdb..#TempIdTable') IS NOT NULL DROP TABLE #TempIdTable\r\n```\r\n\r\nI'm skeptical on calling this an Laravel issue...", "created_at": "2020-07-13T21:07:13Z" }, { "body": "For some projects the application developer does not have accesses to change database triggers. \r\n\r\nAs noted by another comment on the thread @stevebauman linked, adding the `SET NO COUNT` before the `INSERT`, and adding the `SELECT SCOPE_IDENTITY` to the same clause makes PDO to return the expected last inserted ID:\r\n\r\nReferences:\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-352672920\r\nAnd https://github.com/microsoft/msphpsql/issues/288#issuecomment-352814829\r\n\r\nI agree with @stevebauman that this is not primarily a Laravel issue. But as this can be *\"workaround-ed\"* I would add it to Laravel.\r\n\r\nIssue is allowing any driver like the freeTDS one. If we restrict SQL Server drivers to the official one from Microsoft, fixes introduced by PR #33430 would work.\r\n\r\nReason I reverted that PR is because it was targeted to v6.x (LTS) and v7.x that broke some apps that used the unofficial freeTDS driver. \r\n\r\nBut I guess that for a newer version (8 maybe) we can add a requirement to only support Microsoft official drivers. \r\n", "created_at": "2020-07-15T11:01:21Z" }, { "body": "Amazing work on that PR @rodrigopedra! 🙌\r\n\r\nIs there any possibility we could have a flag inside the developers `sqlsrv` configuration that enables / swaps compatibility with FreeTDS, while the MSSQL driver is supported by default?\r\n\r\nWe would of course have to create separate grammars or grammar methods to compile the insert statement. But then instead of dropping support completely, users can set the flag to true (maybe `'freetds' => true`).\r\n\r\nWhat are your thoughts?\r\n\r\nSince we have access to the configuration in the `SqlServerConnection` we could, we could retrieve this option and apply it to the `Grammar` instance:\r\n\r\nhttps://github.com/laravel/framework/blob/d3d36f059ef1c56e17d8e434e9fd3dfd6cbe6e53/src/Illuminate/Database/SqlServerConnection.php#L55-L63\r\n\r\n**Example:**\r\n```php\r\n/**\r\n * Get the default query grammar instance.\r\n *\r\n * @return \\Illuminate\\Database\\Query\\Grammars\\SqlServerGrammar\r\n */\r\nprotected function getDefaultQueryGrammar()\r\n{\r\n $grammar = new QueryGrammar;\r\n \r\n if ($this->getConfig('freetds') === true) {\r\n $grammar->usingFreeTds();\r\n }\r\n \r\n return $this->withTablePrefix($grammar);\r\n}\r\n```\r\n\r\nOr, even better, if we have the ability to detect which Sqlsrv driver is being used, then can enable the `Grammar` option without breaking backwards compatibility. Not sure if this is doable though...", "created_at": "2020-07-15T12:24:20Z" }, { "body": "Thanks @stevebauman !\r\n\r\nOne of the suggestions I made in here:\r\n\r\nhttps://github.com/laravel/framework/pull/33430#commitcomment-40493561\r\n\r\nWas having some feature detection in place for that.\r\n\r\nLaravel already does that for the ODBC driver:\r\n\r\nhttps://github.com/laravel/framework/blob/97c8d87991672604e22f2a7c05e717ea2743aa0b/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php#L26-L30\r\n\r\nBut I fear adding more branches to that `if` should be a reason to drop SQL Server support altogether.\r\n\r\nI still think that adding the requirement to use the official driver is a better way to go, as it would simplify code and make maintenance easier. Support for alternative drivers could be added by third-party packages.\r\n", "created_at": "2020-07-15T16:06:37Z" }, { "body": "How much drivers are there for SQL Server and how popular are they?", "created_at": "2020-07-16T15:41:37Z" }, { "body": "@driesvints All I know of is the [official SQL Server drivers](https://github.com/microsoft/msphpsql/releases) and [FreeTDS](http://www.freetds.org), but I haven't touched FreeTDS since PHP 5.4. Unsure why anyone would use FreeTDS over the official drivers to be honest, maybe for legacy Ubuntu servers?\r\n\r\n@rodrigopedra You're right, if it gets too complicated then it's probably best to support only the official SQL Server driver from Microsoft. However, if it's only one additional `if` statement to offer a fix **and** backwards compatibility, I'm not sure if that's a large maintenance overhead (imho).", "created_at": "2020-07-16T15:58:11Z" }, { "body": "@stevebauman well, if it's really one if statement I suspect we would have resolved this issue much sooner. I also don't think it's reasonable to support every driver out there. But I want to figure out how much there are and how popular they are first.", "created_at": "2020-07-16T16:01:02Z" }, { "body": "Apologies @driesvints, I wasn't intending to oversimplify the issue. I was referring to the need to extract both the PR's logic, and the in-place working logic (that is already working with FreeTDS) into two separate method calls and adding an `if` to simply check if the server is using the FreeTDS driver, or the Microsoft SQL Driver -- then execute the compatible insert.", "created_at": "2020-07-16T16:21:56Z" }, { "body": "No need to apologize :)", "created_at": "2020-07-16T16:55:01Z" }, { "body": "Since this issue has only been raised by a single person and @stevebauman has since posted a fix in the trigger itself (no response from OP) I'm going to close this.", "created_at": "2020-09-23T20:01:21Z" }, { "body": "This is still an issue in 2021\r\n\r\n`$post = Post::create([\r\n 'author_id' => $request->author,\r\n 'series_id' => $request->series,\r\n 'content' => $request->content,\r\n ]);\r\n`\r\nAfter calling create method, `$post->id` will have a wrong value.", "created_at": "2021-09-10T13:13:11Z" }, { "body": "Hi @peter-olom, do you have any `insert` SQL triggers tied to your `posts` DB table? \r\n\r\nIf you're going to say this is still an issue, then you have to create a programmatic test illustrating such. Saying it's still an issue provides maintainers nothing to work with.\r\n\r\nYou can utilize Azure SQL Server for free in GitHub actions if you'd like to take on the task: https://docs.microsoft.com/en-us/azure/azure-sql/database/connect-github-actions-sql-db", "created_at": "2021-09-10T13:22:08Z" }, { "body": "> This is still an issue in 2021\r\n\r\nOf course it is, the fix was reverted to avoid breaking apps that were using different drivers, as described in the thread above.\r\n\r\nIf you read all the thread you will see no changes were made, as there is a workaround one can make to their own database server to circumvent this.\r\n\r\nBy the way, have you tried adding the trigger workaround by @stevebauman above?\r\n\r\nIf you think the framework should drop support for other SQL Servers drivers that didn't work out with the fix sent in 2020, without requiring developers to use the trigger workaround available in this thread, I would suggest you to:\r\n\r\n- send a PR re-submitting the fix, or better yet with an improved fix that might work with users using the FreeTDS driver\r\n- If a fix cannot accommodate FreeTDS applications, discuss with the maintainers if only the drivers from Microsoft should be supported\r\n- If they agree, send a PR to the docs clarifying this new requirement and noting it in the upgrade docs\r\n\r\nUntil an alternative fix that works for both Microsoft drivers and FreeTDS drivers, or an agreement on only supporting Microsoft official drivers and using the then proposed fix sent in 2020, or an improved one, please try using the trigger workaround as discussed in the thread.\r\n ", "created_at": "2021-09-10T13:24:43Z" } ], "number": 32883, "title": "Create method on model returning wrong primary key value (SQLSRV)" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nThis PR addresses issue #32883 \r\n\r\nIt adds the method `SqlServerGrammar@compileInsertGetId`, and if it gets merged this method will change \r\nan `INSERT` statement from this:\r\n\r\n~~~sql\r\ninsert into [users] ([email]) values (?)\r\n~~~\r\n\r\nInto this:\r\n\r\n~~~sql\r\nset nocount on;\r\ninsert into [users] ([email]) values (?);\r\nselect scope_identity() as [id]\r\n~~~\r\n\r\n*line breaks added for readability*\r\n\r\nThere are other features in SQL Server that allows retrieving the last inserted ID, but from my research, \r\nfor a `INSERT` statement that inserts a single row, `SCOPE_IDENTITY` seems to be the more reliable.\r\n\r\nThe alternative methods are:\r\n\r\n- **`OUTPUT` clause**: can yield wrong results when target table has an `INSTEAD OF INSERT` trigger.\r\n \r\n > For INSTEAD OF triggers, the returned results are generated as if the INSERT, UPDATE, or DELETE \r\n **had actually occurred**, even if no modifications take place as the result of the trigger operation.\r\n \r\n reference: https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql\r\n\r\n- **`IDENT_CURRENT()` function**: not transaction safe. \r\n \r\n > IDENT_CURRENT returns the last identity value generated for a specific table in **any session** and **any scope**\r\n \r\n reference: https://docs.microsoft.com/en-us/sql/t-sql/functions/ident-current-transact-sql\r\n\r\n- **`@@IDENTITY` system function**: not trigger safe. \r\n \r\n > If the statement fires one or more triggers that perform inserts that generate identity values, \r\n calling @@IDENTITY immediately after the statement returns the last identity value generated by the triggers.\r\n \r\n reference: https://docs.microsoft.com/en-us/sql/t-sql/functions/identity-transact-sql\r\n\r\nI first tried using the `OUTPUT` clause as from my previous knowledge was a recommended solution \r\nfrom Microsoft due to some bugs with `SCOPE_IDENTITY` and `@@IDENTITY`\r\n\r\nreference: https://support.microsoft.com/en-us/help/2019779/you-may-receive-incorrect-values-when-using-scope-identity-and-identit\r\n\r\nBut according to the same reference above the bug was fixed in SQL Server 2005, which is not supported anymore\r\nneither by Microsoft nor by Laravel.\r\n\r\nAlso using the `OUTPUT` clause incurred in using a temporary `TABLE` variable to address triggers usage. \r\nAnd as noted on the list above the `OUTPUT` clause can yield incorrect results if the target table \r\nhas an `INSTEAD OF INSERT` trigger.\r\n\r\nSo the most reliable way seems to use `SCOPE_IDENTITY()`.\r\n\r\nNote that I added `SCOPE_IDENTITY()` in the same SQL generated by `compileInsertGetId`, so it is guaranteed to be \r\nrun in the same session as the `INSERT` statement.\r\n\r\nThis is necessary as per docs (and my local testing), `SCOPE_IDENTITY()` is safe on the \r\nsame scope (e.g. triggers won't affect it) and session (connection, transaction, etc).\r\n\r\n> Returns the last identity value inserted into an identity column in the same scope. A scope is \r\n a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in \r\n the same stored procedure, function, or batch, they are in the same scope.\r\n\r\nreference: https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql\r\n\r\nI also removed the ODBC part from the `SqlServerProcessor` as it run the query on separate database call.\r\nIn my local testing, when the target table of a `INSERT` statement has a trigger which inserts a row \r\non another table, using `SCOPE_IDENTITY` on separate database call returns an incorrect result \r\n(the auto generated id from the row inserted by trigger).\r\n\r\n## How this PR differs from previous attempts\r\n\r\nI found two other previous attempts to solve this:\r\n\r\n1. PR #32957\r\n\r\n This PR ended having a very similar code to that PR (difference being the column name used in the `SqlServerGrammar@compileInsertGetId`)\r\n \r\n As mentioned above, I first tried using the `OUTPUT` clause, as from my previous knowledge seemed to be \r\n a better solution, but after some research on MSDN and other sources I ended up using `SCOPE_IDENTITY()` as\r\n PR #32957.\r\n \r\n Difference is this PR only addressees the last insert id reported on issue #32883, whereas PR #32957 addresses\r\n other SQL Server related issues.\r\n \r\n I would close this PR in favor of PR #32957 if that is preferred, as it is more feature complete.\r\n \r\n2. Branch `sqlsrv-insert-id` from @staudenmeir fork\r\n\r\n Issue #32883 OP (@kadevland) mentions that fork. The only difference is that this PR does not fallback\r\n to `@@IDENTITY`, as per `SCOPE_IDENTITY()` docs (linked above):\r\n \r\n > The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements \r\n into an identity column occur in the scope.\r\n \r\n Which is not the case as the `SELECT SCOPE_IDENTITY()` is added in the same SQL code as the `INSERT` statement.\r\n Also as noted above `@@IDENTITY` can return the wrong value if the target table of the `INSERT` statement has\r\n an associated trigger.\r\n \r\n Also @staudenmeir did not make a PR from his fork. I consider him to have more knowledge regarding databases and\r\n Laravel's Eloquent/Query Builder than me. If he knows any issues that prevented him to make a PR from his fork - \r\n maybe he is researching or know a better solution to this problem - I would bet on his attempt and close this PR. \r\n\r\n## Implementation notes\r\n\r\n### `SqlServerProcessor`\r\n\r\nThe changed code in the `SqlServerProcessor` class was copied from the same method in the `PostgresProcessor` class.\r\n\r\nAlso as already mentioned above, I removed the ODBC special handling to avoid executing `SCOPE_IDENTITY()` \r\nin a separate query.\r\n\r\n### `SET NOCOUNT ON`\r\n\r\n`set nocount on` is needed so SQL Server returns the `SELECT` results instead of the affected rows count.\r\n\r\n### Testing\r\n\r\nI updated an existing test and added a new one to test the code changed by this PR.\r\n\r\n## Real usage testing\r\n\r\nI setup a local application with SQL Server 2017 running in a docker instance (I run Linux) and did some local \r\ntests with sample application code. SQL Server version 2017 was used because I already had this docker image installed \r\nfor some other projects I need it.\r\n\r\nEverything worked as expected. I tested both inserts in a table with no triggers and in a table with a `INSERT` trigger.\r\n\r\nIf someone has any suggestions or spot any errors please let me know and I'll make any improvements needed. \r\n", "number": 33430, "review_comments": [], "title": "[7.x] Improve SQL Server last insert id retrieval" }
{ "commits": [ { "message": "improve SQL Server last insert id retrieval" } ], "files": [ { "diff": "@@ -323,6 +323,21 @@ public function compileExists(Builder $query)\n return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1));\n }\n \n+ /**\n+ * Compile an insert and get ID statement into SQL.\n+ *\n+ * @param \\Illuminate\\Database\\Query\\Builder $query\n+ * @param array $values\n+ * @param string $sequence\n+ * @return string\n+ */\n+ public function compileInsertGetId(Builder $query, $values, $sequence)\n+ {\n+ $sql = $this->compileInsert($query, $values);\n+\n+ return 'set nocount on;'.$sql.';select scope_identity() as '.$this->wrap($sequence ?: 'id');\n+ }\n+\n /**\n * Compile an update statement with joins into SQL.\n *", "filename": "src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -2,8 +2,6 @@\n \n namespace Illuminate\\Database\\Query\\Processors;\n \n-use Exception;\n-use Illuminate\\Database\\Connection;\n use Illuminate\\Database\\Query\\Builder;\n \n class SqlServerProcessor extends Processor\n@@ -21,38 +19,15 @@ public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu\n {\n $connection = $query->getConnection();\n \n- $connection->insert($sql, $values);\n+ $connection->recordsHaveBeenModified();\n \n- if ($connection->getConfig('odbc') === true) {\n- $id = $this->processInsertGetIdForOdbc($connection);\n- } else {\n- $id = $connection->getPdo()->lastInsertId();\n- }\n+ $result = $connection->selectFromWriteConnection($sql, $values)[0];\n \n- return is_numeric($id) ? (int) $id : $id;\n- }\n+ $sequence = $sequence ?: 'id';\n \n- /**\n- * Process an \"insert get ID\" query for ODBC.\n- *\n- * @param \\Illuminate\\Database\\Connection $connection\n- * @return int\n- *\n- * @throws \\Exception\n- */\n- protected function processInsertGetIdForOdbc(Connection $connection)\n- {\n- $result = $connection->selectFromWriteConnection(\n- 'SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'\n- );\n-\n- if (! $result) {\n- throw new Exception('Unable to retrieve lastInsertID for ODBC.');\n- }\n+ $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\n \n- $row = $result[0];\n-\n- return is_object($row) ? $row->insertid : $row['insertid'];\n+ return is_numeric($id) ? (int) $id : $id;\n }\n \n /**", "filename": "src/Illuminate/Database/Query/Processors/SqlServerProcessor.php", "status": "modified" }, { "diff": "@@ -2130,7 +2130,7 @@ public function testInsertGetIdWithEmptyValues()\n $builder->from('users')->insertGetId([]);\n \n $builder = $this->getSqlServerBuilder();\n- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'insert into [users] default values', [], null);\n+ $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'set nocount on;insert into [users] default values;select scope_identity() as [id]', [], null);\n $builder->from('users')->insertGetId([]);\n }\n \n@@ -2474,6 +2474,14 @@ public function testPostgresInsertGetId()\n $this->assertEquals(1, $result);\n }\n \n+ public function testSqlServerInsertGetId()\n+ {\n+ $builder = $this->getSqlServerBuilder();\n+ $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'set nocount on;insert into [users] ([email]) values (?);select scope_identity() as [id]', ['foo'], 'id')->andReturn(1);\n+ $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id');\n+ $this->assertEquals(1, $result);\n+ }\n+\n public function testMySqlWrapping()\n {\n $builder = $this->getMySqlBuilder();", "filename": "tests/Database/DatabaseQueryBuilderTest.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7\r\n- PHP Version: 7.4\r\n- Database Driver & Version: PDP_SQLSRV\r\n\r\n### Description:\r\nWhen creating records of a model using create the returned record will have a wrong value for primary key if the table has a trigger on it which itself creates (inserts) a record in another table.\r\n\r\n### Steps To Reproduce:\r\n\r\nCreate a table (with an auto incrementing primary key) and add a trigger to it which inserts another record in another table). Then calling the create method on the model will return the just created record with the wrong value for the primary key field.\r\n\r\n### Note\r\n\r\nit is the same issue as #27452, close for lack of activity but the problem is still valid\r\n\r\nThe fix [staudenmeir@b4a8f81](https://github.com/staudenmeir/framework/commit/b4a8f81c35c27e65c3fbc92c38afb84bbffcec44) solves the problem but is not integrated into Laravel.", "comments": [ { "body": "@kadevland i dont think this is a laravel bug.\r\n\r\nit seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n\r\n\r\nIts php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n\r\nsee class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`", "created_at": "2020-05-19T09:54:57Z" }, { "body": "@kadevland I would advise using Laravel Eloquent events instead of database triggers for your logic.", "created_at": "2020-05-19T09:56:17Z" }, { "body": "> @kadevland i dont think this is a laravel bug.\r\n> \r\n> it seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity\r\n> \r\n> Its php Doctrine package that adds: `;SELECT SCOPE_IDENTITY() AS LastInsertId;` to the query for SqlServer when query starts with `'INSERT INTO '`\r\n> \r\n> see class: `Doctrine\\DBAL\\Driver\\SQLSrv\\SQLSrvStatement`\r\n\r\n\r\nYou see Doctrine fix by append but laravel not append so that my purpose of issu.\r\nIt's Bug of Eloquent can not return write value of ID ( doctrine can, and if do the same in eleoquent )\r\n\r\nYou can't not replace trigger logical by php.\r\n\r\nIt possible to integrete same logical witch use in doctrice and all ready use un driver pgsql in laravel\r\n\r\nfor exemple :\r\n\r\nIlluminate\\Database\\Query\\Grammars\\PostgresGrammar \r\n``` \r\n public function compileInsertGetId(Builder $query, $values, $sequence)\r\n {\r\n return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id');\r\n }\r\n``` \r\nIlluminate\\Database\\Query\\Processors\\PostgresProcessor\r\n``` \r\n public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)\r\n {\r\n $result = $query->getConnection()->selectFromWriteConnection($sql, $values)[0];\r\n\r\n $sequence = $sequence ?: 'id';\r\n\r\n $id = is_object($result) ? $result->{$sequence} : $result[$sequence];\r\n\r\n return is_numeric($id) ? (int) $id : $id;\r\n }\r\n``` \r\n\r\n\r\n\r\n\r\n\r\n\r\n", "created_at": "2020-05-19T10:28:59Z" }, { "body": "Anyone is welcome to PR a fix. I do not use SQL Server nor can I test it easily.", "created_at": "2020-05-19T14:21:52Z" }, { "body": "@taylorotwell Can i add a docker-compose file to test sql-server (Unit)Tests and can this be integrated in the CI build process or not possible?", "created_at": "2020-05-19T15:04:51Z" }, { "body": "@joelharkes i can post DDL table and trigger, make the fixe on sqlsrvGrammar and procces\r\nbut for CI/test i'm not good at all", "created_at": "2020-05-19T19:03:18Z" }, { "body": "I Got a working docker-compose setup for SQL server unit tests.\r\n\r\nNow I have to add the test case and discuss with Laravel team how/where to put my files.\r\n\r\nIt got:\r\n- dockerfile to make php with SQL server drivers\r\n- compose file\r\n- docker entry point file to wait for host & port\r\n- PHP script to create a database in SQL server (it starts without database)\r\n\r\n\r\nWhere do I put these files?\r\nWhat do I do with phpunit tests that should only be executed in this container?", "created_at": "2020-05-20T21:20:44Z" }, { "body": "update: I've got a working unit test, working on fix this week.", "created_at": "2020-05-21T09:15:17Z" }, { "body": "Got a fix working on finalizing PR.", "created_at": "2020-05-21T09:27:27Z" }, { "body": "THX.\r\nWhen you finalizing PR, i will test on my project", "created_at": "2020-05-22T20:30:33Z" }, { "body": "@kadevland fixed it on master, lets see what they say :) you can upvote the PR if you like.", "created_at": "2020-05-25T18:50:57Z" }, { "body": "https://github.com/laravel/framework/pull/32957 was closed pending inactivity but we welcome any help with resurrecting it.", "created_at": "2020-06-25T14:25:10Z" }, { "body": "Fixed by @rodrigopedra in https://github.com/laravel/framework/pull/33430\r\n\r\nThanks!", "created_at": "2020-07-04T16:24:19Z" }, { "body": "thx @rodrigopedra ", "created_at": "2020-07-04T23:18:58Z" }, { "body": "You're welcome!", "created_at": "2020-07-05T00:40:11Z" }, { "body": "Re-opened because we had to revert the fix. It caused failures on certain drivers. See https://github.com/laravel/framework/pull/33496", "created_at": "2020-07-10T11:34:21Z" }, { "body": "When doing a new attempt we should keep in mind https://github.com/laravel/framework/issues/33485", "created_at": "2020-07-10T11:36:57Z" }, { "body": "I've dealt with this in my own production environment, and it was an issue caused by inserting another record during an `INSERT` trigger, since `SCOPE_IDENTITY` will return the lastly inserted ID in execution the scope.\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-429909285\r\n\r\nResource:\r\n\r\nhttps://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-2017\r\n\r\nThe fix was to reset the `SCOPE_IDENTITY` on the `INSERT` trigger, which can be done like so:\r\n\r\n```sql\r\n-- The trigger\r\nALTER TRIGGER [Inventory].[OnInsertTriggerHistory] ON [Inventory].[Inventory] \r\nFOR INSERT AS\r\n\r\nSET NOCOUNT ON\r\n\r\n-- The child table insert\r\nINSERT INTO [Inventory].[InventoryHistory] (...) VALUES (...)\r\n\r\n-- Reset the `SCOPE_IDENTITY()` by performing an insert into a temp table.\r\nIF (SELECT COUNT(1) from inserted) = 1 BEGIN \r\n CREATE TABLE #TempIdTable (ResetIdentity int identity(1, 1))\r\n \r\n SET identity_insert #TempIdTable ON\r\n INSERT INTO #TempIdTable (ResetIdentity)\r\n SELECT InventoryId FROM inserted SET identity_insert #TempIdTable OFF\r\nEND\r\n\r\n-- Drop the temp table if it exists.\r\nIF OBJECT_ID('tempdb..#TempIdTable') IS NOT NULL DROP TABLE #TempIdTable\r\n```\r\n\r\nI'm skeptical on calling this an Laravel issue...", "created_at": "2020-07-13T21:07:13Z" }, { "body": "For some projects the application developer does not have accesses to change database triggers. \r\n\r\nAs noted by another comment on the thread @stevebauman linked, adding the `SET NO COUNT` before the `INSERT`, and adding the `SELECT SCOPE_IDENTITY` to the same clause makes PDO to return the expected last inserted ID:\r\n\r\nReferences:\r\n\r\nhttps://github.com/microsoft/msphpsql/issues/288#issuecomment-352672920\r\nAnd https://github.com/microsoft/msphpsql/issues/288#issuecomment-352814829\r\n\r\nI agree with @stevebauman that this is not primarily a Laravel issue. But as this can be *\"workaround-ed\"* I would add it to Laravel.\r\n\r\nIssue is allowing any driver like the freeTDS one. If we restrict SQL Server drivers to the official one from Microsoft, fixes introduced by PR #33430 would work.\r\n\r\nReason I reverted that PR is because it was targeted to v6.x (LTS) and v7.x that broke some apps that used the unofficial freeTDS driver. \r\n\r\nBut I guess that for a newer version (8 maybe) we can add a requirement to only support Microsoft official drivers. \r\n", "created_at": "2020-07-15T11:01:21Z" }, { "body": "Amazing work on that PR @rodrigopedra! 🙌\r\n\r\nIs there any possibility we could have a flag inside the developers `sqlsrv` configuration that enables / swaps compatibility with FreeTDS, while the MSSQL driver is supported by default?\r\n\r\nWe would of course have to create separate grammars or grammar methods to compile the insert statement. But then instead of dropping support completely, users can set the flag to true (maybe `'freetds' => true`).\r\n\r\nWhat are your thoughts?\r\n\r\nSince we have access to the configuration in the `SqlServerConnection` we could, we could retrieve this option and apply it to the `Grammar` instance:\r\n\r\nhttps://github.com/laravel/framework/blob/d3d36f059ef1c56e17d8e434e9fd3dfd6cbe6e53/src/Illuminate/Database/SqlServerConnection.php#L55-L63\r\n\r\n**Example:**\r\n```php\r\n/**\r\n * Get the default query grammar instance.\r\n *\r\n * @return \\Illuminate\\Database\\Query\\Grammars\\SqlServerGrammar\r\n */\r\nprotected function getDefaultQueryGrammar()\r\n{\r\n $grammar = new QueryGrammar;\r\n \r\n if ($this->getConfig('freetds') === true) {\r\n $grammar->usingFreeTds();\r\n }\r\n \r\n return $this->withTablePrefix($grammar);\r\n}\r\n```\r\n\r\nOr, even better, if we have the ability to detect which Sqlsrv driver is being used, then can enable the `Grammar` option without breaking backwards compatibility. Not sure if this is doable though...", "created_at": "2020-07-15T12:24:20Z" }, { "body": "Thanks @stevebauman !\r\n\r\nOne of the suggestions I made in here:\r\n\r\nhttps://github.com/laravel/framework/pull/33430#commitcomment-40493561\r\n\r\nWas having some feature detection in place for that.\r\n\r\nLaravel already does that for the ODBC driver:\r\n\r\nhttps://github.com/laravel/framework/blob/97c8d87991672604e22f2a7c05e717ea2743aa0b/src/Illuminate/Database/Query/Processors/SqlServerProcessor.php#L26-L30\r\n\r\nBut I fear adding more branches to that `if` should be a reason to drop SQL Server support altogether.\r\n\r\nI still think that adding the requirement to use the official driver is a better way to go, as it would simplify code and make maintenance easier. Support for alternative drivers could be added by third-party packages.\r\n", "created_at": "2020-07-15T16:06:37Z" }, { "body": "How much drivers are there for SQL Server and how popular are they?", "created_at": "2020-07-16T15:41:37Z" }, { "body": "@driesvints All I know of is the [official SQL Server drivers](https://github.com/microsoft/msphpsql/releases) and [FreeTDS](http://www.freetds.org), but I haven't touched FreeTDS since PHP 5.4. Unsure why anyone would use FreeTDS over the official drivers to be honest, maybe for legacy Ubuntu servers?\r\n\r\n@rodrigopedra You're right, if it gets too complicated then it's probably best to support only the official SQL Server driver from Microsoft. However, if it's only one additional `if` statement to offer a fix **and** backwards compatibility, I'm not sure if that's a large maintenance overhead (imho).", "created_at": "2020-07-16T15:58:11Z" }, { "body": "@stevebauman well, if it's really one if statement I suspect we would have resolved this issue much sooner. I also don't think it's reasonable to support every driver out there. But I want to figure out how much there are and how popular they are first.", "created_at": "2020-07-16T16:01:02Z" }, { "body": "Apologies @driesvints, I wasn't intending to oversimplify the issue. I was referring to the need to extract both the PR's logic, and the in-place working logic (that is already working with FreeTDS) into two separate method calls and adding an `if` to simply check if the server is using the FreeTDS driver, or the Microsoft SQL Driver -- then execute the compatible insert.", "created_at": "2020-07-16T16:21:56Z" }, { "body": "No need to apologize :)", "created_at": "2020-07-16T16:55:01Z" }, { "body": "Since this issue has only been raised by a single person and @stevebauman has since posted a fix in the trigger itself (no response from OP) I'm going to close this.", "created_at": "2020-09-23T20:01:21Z" }, { "body": "This is still an issue in 2021\r\n\r\n`$post = Post::create([\r\n 'author_id' => $request->author,\r\n 'series_id' => $request->series,\r\n 'content' => $request->content,\r\n ]);\r\n`\r\nAfter calling create method, `$post->id` will have a wrong value.", "created_at": "2021-09-10T13:13:11Z" }, { "body": "Hi @peter-olom, do you have any `insert` SQL triggers tied to your `posts` DB table? \r\n\r\nIf you're going to say this is still an issue, then you have to create a programmatic test illustrating such. Saying it's still an issue provides maintainers nothing to work with.\r\n\r\nYou can utilize Azure SQL Server for free in GitHub actions if you'd like to take on the task: https://docs.microsoft.com/en-us/azure/azure-sql/database/connect-github-actions-sql-db", "created_at": "2021-09-10T13:22:08Z" }, { "body": "> This is still an issue in 2021\r\n\r\nOf course it is, the fix was reverted to avoid breaking apps that were using different drivers, as described in the thread above.\r\n\r\nIf you read all the thread you will see no changes were made, as there is a workaround one can make to their own database server to circumvent this.\r\n\r\nBy the way, have you tried adding the trigger workaround by @stevebauman above?\r\n\r\nIf you think the framework should drop support for other SQL Servers drivers that didn't work out with the fix sent in 2020, without requiring developers to use the trigger workaround available in this thread, I would suggest you to:\r\n\r\n- send a PR re-submitting the fix, or better yet with an improved fix that might work with users using the FreeTDS driver\r\n- If a fix cannot accommodate FreeTDS applications, discuss with the maintainers if only the drivers from Microsoft should be supported\r\n- If they agree, send a PR to the docs clarifying this new requirement and noting it in the upgrade docs\r\n\r\nUntil an alternative fix that works for both Microsoft drivers and FreeTDS drivers, or an agreement on only supporting Microsoft official drivers and using the then proposed fix sent in 2020, or an improved one, please try using the trigger workaround as discussed in the thread.\r\n ", "created_at": "2021-09-10T13:24:43Z" } ], "number": 32883, "title": "Create method on model returning wrong primary key value (SQLSRV)" }
{ "body": "Fixes #32883 #31229\r\n\r\n# summary\r\n\r\n- adds unit testing based on docker-compose file\r\n- fixes using schema's in migrations and table prefix\r\n- fixes user default schema issues.\r\n\r\nRun sql server based unit integration tests (only docker required), can be added to CI easily:\r\n\r\n```\r\ndocker-compose -f sqlsrv.docker-compose.yml up --exit-code-from laravel --abort-on-container-exit\r\n```\r\n\r\nopen questions:\r\n\r\n- where do you want me to put the dockerfile and compose file, is root ok?\r\n- any missing tests?\r\n- is skip tests like i do ok?", "number": 32957, "review_comments": [ { "body": "This method is now no longer needed? This doesn't break anything?", "created_at": "2020-05-29T14:37:29Z" }, { "body": "What does this comment mean? Where does this happen?", "created_at": "2020-05-29T14:37:46Z" }, { "body": "Why would there be an infinite loop?", "created_at": "2020-05-29T14:38:16Z" }, { "body": "What does this comment mean? \"dbo\" appears nowhere near this code.", "created_at": "2020-05-29T14:38:39Z" }, { "body": "We can also do \r\n```php\r\n$id = $result->lastInsertedId ?? $result['lastInsertedId'];\r\n```", "created_at": "2020-05-30T14:22:55Z" }, { "body": "if call $result->lastInsertedId may be having error on call on none object.\r\nI think left\r\n $id = is_array($result) ? $result['lastInsertedId'] : $result->lastInsertedId;\r\n", "created_at": "2020-05-30T15:59:46Z" }, { "body": "The current code is fine.", "created_at": "2020-05-30T18:57:32Z" }, { "body": "In the processor. found not better way todo this since if default schema should be used parameter is not possble (needs to user sql method)", "created_at": "2020-06-02T10:01:36Z" }, { "body": "I had infinte loop while unit testing.\r\nevery time it concatenates the `schema.` prefix \r\nand then in wrapSegment() it splits on the dot. if it has 2 or more segments it will call wrapTable() method and thus the loop starts over again. => you can test by removing this line and running docker compose", "created_at": "2020-06-02T10:03:27Z" }, { "body": "yes sorry, comment should be removed. it is outdated from older code where it depended on dbo as default schema", "created_at": "2020-06-02T10:03:56Z" }, { "body": "yea i was not sure here if i should always expect and object or array.\r\ncode was first based on array but it failed because i got an object.", "created_at": "2020-06-02T10:04:54Z" }, { "body": "Yea i'm pretty sure my solution will work for ODBC too but i havent tested it.", "created_at": "2020-06-02T10:05:53Z" }, { "body": "if no schema is provided SCHEMA_NAME() constant/sql server method is used, this cannot be parameterized.\r\n\r\nwould be nice if this compile method could just return a string + array of bindings but that is not how the interface is setup.", "created_at": "2020-06-02T10:06:46Z" }, { "body": "Is there someone who can test this?\r\n", "created_at": "2020-06-02T13:20:30Z" }, { "body": "example exception my tests threw before adding this part:\r\n```\r\nError : Maximum function nesting level of '256' reached, aborting!\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:173\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:38\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\Grammar.php:216\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\SqlServerGrammar.php:891\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:99\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Collections\\Collection.php:656\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:101\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:65\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\Grammar.php:230\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:39\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\Grammar.php:216\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\SqlServerGrammar.php:891\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:99\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Collections\\Collection.php:656\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:101\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:65\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\Grammar.php:230\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:39\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\Grammar.php:216\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Schema\\Grammars\\SqlServerGrammar.php:891\r\n E:\\git\\laravel-framework\\src\\Illuminate\\Database\\Grammar.php:99\r\n```", "created_at": "2020-06-02T13:27:52Z" }, { "body": "current setup does not allow `x.` prefix it will fall in `wrapSegments()` funciton thinking the first part is the table second part is column. the first table part will 'again' be prefixed and thus the loop.", "created_at": "2020-06-02T13:29:21Z" }, { "body": "Where in the processor? What file and line number? Please be VERY specific and detailed.", "created_at": "2020-06-11T15:32:30Z" }, { "body": "I still have no idea what we are talking about to be honest. It feels like we are hacking around some deeper issue. Please try explain why this happens very clearly with a walk through of the code with screenshots.", "created_at": "2020-06-11T15:42:31Z" }, { "body": "Remove double space here after `$table`", "created_at": "2020-06-18T15:44:28Z" } ], "title": "[8.x] SqlServer schema fixes" }
{ "commits": [ { "message": "Fix auto incrementing key returning the right entity ID." }, { "message": "Fix sql server schema issuse when using schema's\n\n- fix hasTable and hasColumn uses schema or uses user default schema (just like sql would)\n- fix dropping default constraints only on table in right schema." }, { "message": "Add sql server unit tests (integration)" }, { "message": "Fix unit tests" }, { "message": "Cleanup code" } ], "files": [ { "diff": "@@ -0,0 +1,27 @@\n+FROM php:7.4.4-fpm-alpine as base\n+\n+COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/bin/\n+\n+RUN install-php-extensions sqlsrv pdo_sqlsrv\n+\n+# Sql server necessary additions\n+RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.5.1.1-1_amd64.apk \\\n+ && curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.5.1.2-1_amd64.apk \\\n+ && apk add --allow-untrusted msodbcsql17_17.5.1.1-1_amd64.apk \\\n+ && apk add --allow-untrusted mssql-tools_17.5.1.2-1_amd64.apk\n+# Fix for sql server\n+ENV LC_ALL=C\n+\n+#install composer globally\n+#RUN curl -sSL https://getcomposer.org/installer | php \\\n+# && mv composer.phar /usr/local/bin/composer\n+#ENV COMPOSER_ALLOW_SUPERUSER 1\n+#RUN composer global require hirak/prestissimo --no-plugins --no-scripts\n+\n+ARG TYPE_ENV=development\n+\n+RUN mv \"$PHP_INI_DIR/php.ini-${TYPE_ENV}\" \"$PHP_INI_DIR/php.ini\" \\\n+ && sed -e 's/max_execution_time = 30/max_execution_time = 600/' -i \"$PHP_INI_DIR/php.ini\" \\\n+ && echo 'memory_limit = -1' > /usr/local/etc/php/conf.d/docker-php-memlimit.ini;\n+\n+WORKDIR /var/www/html", "filename": "php-sqlsrv.dockerfile", "status": "added" }, { "diff": "@@ -0,0 +1,46 @@\n+# run for CI: docker-compose -f sqlsrv.docker-compose.yml up --exit-code-from laravel --abort-on-container-exit\n+# for manual/debug testing:\n+# 1. docker-compose -f sqlsrv.docker-compose.yml up (spins up db and runs unit tests once, but leaves db running).\n+# 2. add environment variables below to phpunit.xml:\n+# <env name=\"DB_CONNECTION\" value=\"sqlsrv\"/>\n+# <env name=\"DB_USERNAME\" value=\"SA\"/>\n+# <env name=\"DB_PASSWORD\" value=\"p83bpNZTCf3sPsWt\"/>\n+# <env name=\"APP_DEBUG\" value=\"true\"/>\n+version: '3'\n+services:\n+ sqlsrv:\n+ container_name: sqlsrv\n+ image: mcr.microsoft.com/mssql/server:2019-latest\n+ ports:\n+ - \"1433:1433\"\n+ environment:\n+ SA_PASSWORD: \"p83bpNZTCf3sPsWt\"\n+ ACCEPT_EULA: \"Y\"\n+ networks:\n+ - db\n+ logging:\n+ driver: none # hide logging, only distracting.\n+ laravel:\n+ depends_on:\n+ - sqlsrv\n+ container_name: laravel\n+ build:\n+ context: .\n+ dockerfile: php-sqlsrv.dockerfile\n+ command: [\"vendor/bin/phpunit\", \"tests/Integration/Database/SqlServer/\"]\n+ volumes:\n+ - ./src/:/var/www/html/src/\n+ - ./tests/:/var/www/html/tests/\n+ - ./vendor/:/var/www/html/vendor/\n+ networks:\n+ - db\n+ environment:\n+ DB_CONNECTION: 'sqlsrv'\n+ DB_HOST: sqlsrv\n+ DB_PORT: 1433\n+ DB_DATABASE: forge\n+ DB_USERNAME: SA\n+ DB_PASSWORD: 'p83bpNZTCf3sPsWt'\n+ APP_DEBUG: 'true'\n+networks:\n+ db:", "filename": "sqlsrv.docker-compose.yml", "status": "added" }, { "diff": "@@ -21,40 +21,12 @@ public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu\n {\n $connection = $query->getConnection();\n \n- $connection->insert($sql, $values);\n-\n- if ($connection->getConfig('odbc') === true) {\n- $id = $this->processInsertGetIdForOdbc($connection);\n- } else {\n- $id = $connection->getPdo()->lastInsertId();\n- }\n+ $result = $connection->selectOne('SET NOCOUNT ON;'.$sql.';SELECT SCOPE_IDENTITY() AS lastInsertedId;', $values, false);\n+ $id = is_array($result) ? $result['lastInsertedId'] : $result->lastInsertedId;\n \n return is_numeric($id) ? (int) $id : $id;\n }\n \n- /**\n- * Process an \"insert get ID\" query for ODBC.\n- *\n- * @param \\Illuminate\\Database\\Connection $connection\n- * @return int\n- *\n- * @throws \\Exception\n- */\n- protected function processInsertGetIdForOdbc(Connection $connection)\n- {\n- $result = $connection->selectFromWriteConnection(\n- 'SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'\n- );\n-\n- if (! $result) {\n- throw new Exception('Unable to retrieve lastInsertID for ODBC.');\n- }\n-\n- $row = $result[0];\n-\n- return is_object($row) ? $row->insertid : $row['insertid'];\n- }\n-\n /**\n * Process the results of a column listing query.\n *", "filename": "src/Illuminate/Database/Query/Processors/SqlServerProcessor.php", "status": "modified" }, { "diff": "@@ -35,7 +35,12 @@ class SqlServerGrammar extends Grammar\n */\n public function compileTableExists()\n {\n- return \"select * from sysobjects where type = 'U' and name = ?\";\n+ return \"select obj.* from sys.objects as obj\n+ join sys.schemas as schem\n+ on obj.schema_id = schem.schema_id\n+ where obj.type = 'U'\n+ and obj.name = ?\n+ and schem.name = \"; // schema concatenated by builder.\n }\n \n /**\n@@ -46,9 +51,12 @@ public function compileTableExists()\n */\n public function compileColumnListing($table)\n {\n+ [$schema, $table] = $this->parseSchemaAndTable($table);\n+ $schemaName = $schema ? \"'$schema'\" : 'SCHEMA_NAME()';\n return \"select col.name from sys.columns as col\n join sys.objects as obj on col.object_id = obj.object_id\n- where obj.type = 'U' and obj.name = '$table'\";\n+ join sys.schemas as schem on obj.schema_id = schem.schema_id\n+ where obj.type = 'U' and obj.name = '$table' and schem.name = $schemaName\";\n }\n \n /**\n@@ -191,29 +199,29 @@ public function compileDropAllTables()\n public function compileDropColumn(Blueprint $blueprint, Fluent $command)\n {\n $columns = $this->wrapArray($command->columns);\n+ $tableName = $this->wrapTable($blueprint);\n+ $dropExistingConstraintsSql = $this->compileDropDefaultConstraint($tableName, $command);\n \n- $dropExistingConstraintsSql = $this->compileDropDefaultConstraint($blueprint, $command).';';\n-\n- return $dropExistingConstraintsSql.'alter table '.$this->wrapTable($blueprint).' drop column '.implode(', ', $columns);\n+ $columnInString = implode(', ', $columns);\n+ return \"{$dropExistingConstraintsSql};alter table {$tableName} drop column {$columnInString}\";\n }\n \n /**\n * Compile a drop default constraint command.\n *\n- * @param \\Illuminate\\Database\\Schema\\Blueprint $blueprint\n+ * @param string $table\n * @param \\Illuminate\\Support\\Fluent $command\n * @return string\n */\n- public function compileDropDefaultConstraint(Blueprint $blueprint, Fluent $command)\n+ public function compileDropDefaultConstraint($table, Fluent $command)\n {\n $columns = \"'\".implode(\"','\", $command->columns).\"'\";\n-\n- $tableName = $this->getTablePrefix().$blueprint->getTable();\n-\n+ [$schema, $tableName] =$this->parseSchemaAndTable($table);\n+ $schemaName = $schema ? \"'$schema'\" : 'SCHEMA_NAME()';\n $sql = \"DECLARE @sql NVARCHAR(MAX) = '';\";\n- $sql .= \"SELECT @sql += 'ALTER TABLE [dbo].[{$tableName}] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' \";\n+ $sql .= \"SELECT @sql += 'ALTER TABLE $table DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' \";\n $sql .= 'FROM SYS.COLUMNS ';\n- $sql .= \"WHERE [object_id] = OBJECT_ID('[dbo].[{$tableName}]') AND [name] in ({$columns}) AND [default_object_id] <> 0;\";\n+ $sql .= \"WHERE [object_id] = OBJECT_ID($schemaName + '.{$tableName}') AND [name] in ({$columns}) AND [default_object_id] <> 0;\";\n $sql .= 'EXEC(@sql)';\n \n return $sql;\n@@ -875,6 +883,10 @@ public function wrapTable($table)\n if ($table instanceof Blueprint && $table->temporary) {\n $this->setTablePrefix('#');\n }\n+ if(!$table instanceof Blueprint){\n+ // fix infinite loop when $tablePrefix = 'schema.';\n+ return $this->wrapValue($table);\n+ }\n \n return parent::wrapTable($table);\n }\n@@ -893,4 +905,17 @@ public function quoteString($value)\n \n return \"N'$value'\";\n }\n+\n+ /**\n+ * parse given table name to get schema and table name.\n+ * @param string $table\n+ * @return array|string[]\n+ */\n+ public function parseSchemaAndTable($table){\n+ $parts = explode(\".\", $table);\n+ if(count($parts) == 1){\n+ return [null, $parts[0]];\n+ }\n+ return $parts;\n+ }\n }", "filename": "src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php", "status": "modified" }, { "diff": "@@ -2,6 +2,8 @@\n \n namespace Illuminate\\Database\\Schema;\n \n+use Illuminate\\Database\\Schema\\Grammars\\SqlServerGrammar;\n+\n class SqlServerBuilder extends Builder\n {\n /**\n@@ -25,4 +27,23 @@ public function dropAllViews()\n {\n $this->connection->statement($this->grammar->compileDropAllViews());\n }\n+\n+ /**\n+ * Determine if the given table exists.\n+ *\n+ * @param string $table\n+ * @return bool\n+ */\n+ public function hasTable($table)\n+ {\n+ /** @var SqlServerGrammar $grammar */\n+ $grammar = $this->grammar;\n+ $table = $this->connection->getTablePrefix().$table;\n+ [$schema, $tableName] = $grammar->parseSchemaAndTable($table);\n+\n+ $result = $this->connection->selectFromWriteConnection(\n+ $grammar->compileTableExists(). ($schema ? \"'$schema'\" : 'SCHEMA_NAME()') , [$tableName]\n+ );\n+ return count($result) > 0;\n+ }\n }", "filename": "src/Illuminate/Database/Schema/SqlServerBuilder.php", "status": "modified" }, { "diff": "@@ -123,7 +123,7 @@ public function testDropColumnDropsCreatesSqlToDropDefaultConstraints()\n $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n \n $this->assertCount(1, $statements);\n- $this->assertSame(\"DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE [dbo].[foo] DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID('[dbo].[foo]') AND [name] in ('bar') AND [default_object_id] <> 0;EXEC(@sql);alter table \\\"foo\\\" drop column \\\"bar\\\"\", $statements[0]);\n+ $this->assertSame(\"DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE \\\"foo\\\" DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID(SCHEMA_NAME() + '.\\\"foo\\\"') AND [name] in ('bar') AND [default_object_id] <> 0;EXEC(@sql);alter table \\\"foo\\\" drop column \\\"bar\\\"\", $statements[0]);\n }\n \n public function testDropPrimary()", "filename": "tests/Database/DatabaseSqlServerSchemaGrammarTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,40 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Support\\Facades\\Schema;\n+\n+class DatabaseSqlServerDatabasePrefixTest extends DatabaseSqlServerTestCase\n+{\n+ protected function getEnvironmentSetUp($app)\n+ {\n+ $app['config']->set('database.connections.sqlsrv.prefix', 'test_');\n+ parent::getEnvironmentSetUp($app);\n+ }\n+\n+ public function testCreateTableUsesPrefix()\n+ {\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->string('name');\n+ });\n+ $this->assertTrue(Schema::hasTable('users'));\n+\n+ $this->assertTrue(Schema::hasColumn('users', 'name'));\n+ }\n+\n+\n+ public function testDropColumnUsesPrefix()\n+ {\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->string('name');\n+ $table->string('toDrop')->default('test');\n+ });\n+ $this->assertTrue(Schema::hasColumn('users', 'toDrop'));\n+\n+ Schema::table('users', function (Blueprint $table){\n+ $table->dropColumn('toDrop');\n+ });\n+ $this->assertFalse(Schema::hasColumn('users', 'toDrop'));\n+ }\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerDatabasePrefixTest.php", "status": "added" }, { "diff": "@@ -0,0 +1,52 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Support\\Facades\\DB;\n+use Illuminate\\Support\\Facades\\Schema;\n+\n+class DatabaseSqlServerIdentityInsertTest extends DatabaseSqlServerTestCase\n+{\n+ public function testIdentityInsertsGetsId()\n+ {\n+ Schema::create('increment_test', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('bar')->nullable();\n+ });\n+\n+ $model = new Model1(['bar'=> 'test']);\n+ $model->save();\n+ $this->assertEquals(1, $model->id);\n+ }\n+\n+ public function testIdentityInsertReturnsRightIdWhenTriggered()\n+ {\n+ Schema::create('increment_test', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('bar')->nullable();\n+ });\n+ Schema::create('trigger_store', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('bar')->nullable();\n+ });\n+ DB::statement('CREATE TRIGGER test ON increment_test AFTER INSERT AS insert into trigger_store (bar) values (\\'dummy\\')');\n+\n+ $store = new Model1(['bar'=> 'test']);\n+ $store->table ='trigger_store';\n+ $store->save();\n+\n+ $model = new Model1(['bar'=> 'test']);\n+ $model->save();\n+ $this->assertEquals(1, $model->id);\n+ }\n+}\n+\n+\n+class Model1 extends Model\n+{\n+ public $table = 'increment_test';\n+ public $timestamps = false;\n+ protected $fillable = ['bar'];\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerIdentityInsertTest.php", "status": "added" }, { "diff": "@@ -0,0 +1,43 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Support\\Facades\\Schema;\n+\n+class DatabaseSqlServerMigrationTest extends DatabaseSqlServerTestCase\n+{\n+ public function testSimpleCreateTableMigration()\n+ {\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->string('name');\n+ });\n+ $this->assertTrue(Schema::hasColumn('users', 'name'));\n+ $this->assertFalse(Schema::hasColumn('users', 'not_existing'));\n+ }\n+\n+\n+ public function testDropColumnWithDefaultAlsoDropsConstraint()\n+ {\n+ // tests: SqlServerGrammar::compileDropDefaultConstraint()\n+ Schema::create('foo', function ($table) {\n+ $table->string('test');\n+ $table->boolean('bar')->default(false);\n+ });\n+ Schema::table('foo', function ($table) {\n+ $table->dropColumn('bar');\n+ });\n+ $this->assertTrue(Schema::hasColumn('foo', 'test'));\n+ }\n+\n+ public function testAddingColumnToTable()\n+ {\n+ Schema::create('to_add', function (Blueprint $table) {\n+ $table->string('name');\n+ });\n+ Schema::table('to_add', function ($table) {\n+ $table->string('extra_field');\n+ });\n+ $this->assertTrue(Schema::hasColumn('to_add', 'extra_field'));\n+ }\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerMigrationTest.php", "status": "added" }, { "diff": "@@ -0,0 +1,31 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Support\\Facades\\DB;\n+\n+class DatabaseSqlServerMigrationsWithAlternativeDefaultSchema extends DatabaseSqlServerMigrationTest\n+{\n+ public function recreateDatabase()\n+ {\n+ parent::recreateDatabase(); // TODO: Change the autogenerated stub\n+ $user = \"testuser\";\n+ $schema = \"test\";\n+ $pw = 'asdf435fdgk3@asdf';\n+\n+ DB::unprepared(\"DROP USER IF EXISTS $user;\n+ IF SUSER_ID('$user') IS NOT NULL DROP LOGIN $user;\");\n+\n+ DB::unprepared(\"CREATE SCHEMA $schema;\");\n+ DB::unprepared(\"CREATE LOGIN $user WITH PASSWORD = '$pw';\n+ CREATE USER $user FOR LOGIN $user WITH DEFAULT_SCHEMA=$schema;\n+ EXEC sp_addrolemember N'db_owner', N'$user'\n+ \");\n+ DB::purge();\n+ $config = array_merge([], config('database.connections.sqlsrv'));\n+ $config['username'] = 'testuser';\n+ $config['password'] = $pw;\n+ config()->set('database.connections.sqlsrv2', $config);\n+ config()->set('database.default', 'sqlsrv2');\n+ }\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerMigrationsWithAlternativeDefaultSchema.php", "status": "added" }, { "diff": "@@ -0,0 +1,35 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Database\\Connection;\n+use Illuminate\\Support\\Facades\\DB;\n+\n+class DatabaseSqlServerMigrationsWithPrefixSchema extends DatabaseSqlServerMigrationTest\n+{\n+\n+ public function recreateDatabase()\n+ {\n+ parent::recreateDatabase();\n+ DB::statement('CREATE SCHEMA test;');\n+ }\n+\n+ protected function getEnvironmentSetUp($app)\n+ {\n+ parent::getEnvironmentSetUp($app);\n+ config()->set('database.connections.sqlsrv.prefix', 'test.');\n+ }\n+\n+ public function testSimpleCreateTableMigration()\n+ {\n+ parent::testSimpleCreateTableMigration();\n+ /** @var Connection $con */\n+ $con = DB::connection();\n+ $con->setTablePrefix('');\n+ $con->getSchemaGrammar()->setTablePrefix('');\n+ $builder = $con->getSchemaBuilder();\n+ $this->assertTrue($builder->hasTable('test.users'));\n+ $this->assertFalse($builder->hasTable('users'));\n+ $this->assertFalse($builder->hasTable('dbo.users'));\n+ }\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerMigrationsWithPrefixSchema.php", "status": "added" }, { "diff": "@@ -0,0 +1,35 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Database\\DatabaseManager;\n+use Illuminate\\Support\\Facades\\DB;\n+use Illuminate\\Support\\Facades\\Schema;\n+\n+class DatabaseSqlServerSchemaTest extends DatabaseSqlServerTestCase\n+{\n+ protected function getEnvironmentSetUp($app)\n+ {\n+// config()->set('database.sqlsrv.schema', 'test');\n+ parent::getEnvironmentSetUp($app);\n+ }\n+\n+\n+ public function testDropColumnWithDefaultAlsoDropsConstraintOnOtherSchema()\n+ {\n+\n+ DB::statement('CREATE SCHEMA test;');\n+ /** @var DatabaseManager $db */\n+ // tests: SqlServerGrammar::compileDropDefaultConstraint()\n+ Schema::create('test.foo', function ($table) {\n+ $table->string('test');\n+ $table->boolean('bar')->default(false);\n+ });\n+ Schema::table('test.foo', function ($table) {\n+ $table->dropColumn('bar'); // Don't works!\n+ });\n+ $this->assertTrue(Schema::hasColumn('test.foo', 'test'));\n+ $this->assertFalse(Schema::hasColumn('test.foo', 'bar'));\n+ }\n+\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerSchemaTest.php", "status": "added" }, { "diff": "@@ -0,0 +1,57 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database\\SqlServer;\n+\n+use Illuminate\\Database\\DatabaseManager;\n+use Orchestra\\Testbench\\TestCase;\n+\n+abstract class DatabaseSqlServerTestCase extends TestCase\n+{\n+ protected function setUp(): void\n+ {\n+ parent::setUp();\n+ if(config('database.default') !== 'sqlsrv'){\n+ $this->markTestSkipped('Sql server only tested when enabled.');\n+ return;\n+ }\n+ $this->recreateDatabase();\n+ }\n+\n+ protected function tearDown(): void\n+ {\n+ /** @var DatabaseManager $db */\n+ $db = app('db');\n+ $db->disconnect();\n+ parent::tearDown();\n+ }\n+\n+ protected function getEnvironmentSetUp($app)\n+ {\n+ $app['config']->set('app.debug', 'true');\n+ }\n+ public function recreateDatabase()\n+ {\n+ $db = config('database.connections.sqlsrv.database', 'forge');\n+ $host = config('database.connections.sqlsrv.host', 'localhost');\n+ $port = config('database.connections.sqlsrv.port', '1433');\n+ $user = config('database.connections.sqlsrv.username');\n+ $pass = config('database.connections.sqlsrv.password');\n+\n+ $serverName = \"tcp:$host,$port\";\n+ $conn = new \\PDO(\"sqlsrv:server=$serverName ;\", $user, $pass);\n+ $conn->setAttribute(\\PDO::ATTR_ERRMODE, \\PDO::ERRMODE_EXCEPTION);\n+\n+ // alter database first to drop all existing connections.\n+ // I cant seem to make laravel/php close all connections before setUp of new test somehow.\n+ $tsql = \" If(db_id(N'$db') IS NOT NULL)\n+ BEGIN\n+ ALTER DATABASE [$db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\n+ DROP DATABASE [$db];\n+ END\n+ CREATE DATABASE [$db];\";\n+\n+ $conn->query($tsql);\n+ $conn = null; // closing connection.\n+ }\n+\n+}", "filename": "tests/Integration/Database/SqlServer/DatabaseSqlServerTestCase.php", "status": "added" } ] }
{ "body": "- Laravel Version: 6.5\r\n- PHP Version: 7.3.11\r\n- Database Driver & Version: MySQL - 5.7.27-0ubuntu0.18.04.1\r\n\r\n### Description:\r\nWhile writing a migration to fix a bad database that had stored a foreign key as a varchar, I wrote the following migration:\r\n```php\r\nSchema::table('jobseeker_qualifications', function (Blueprint $table) {\r\n $table->bigIncrements('id')->change();\r\n $table->unsignedBigInteger('user_id')->change();\r\n $table->unsignedBigInteger('jobseekers_education_id')->change();\r\n $table->foreign('user_id')->references('id')->on('users');\r\n $table->foreign('jobseekers_education_id')->references('id')->on('jobseeker_educations');\r\n});\r\n```\r\nHowever, this above migration generated the following SQL:\r\n```sql\r\nALTER TABLE jobseeker_qualifications\r\nCHANGE id id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL,\r\nCHANGE jobseekers_education_id jobseekers_education_id BIGINT UNSIGNED CHARACTER SET utf8 NOT NULL COLLATE `utf8_unicode_ci`,\r\nCHANGE user_id user_id BIGINT UNSIGNED NOT NULL\r\n```\r\n**Work Around:** Removing the instructions related to the character set and running this query manually was successful.\r\n\r\n### Steps To Reproduce:\r\n1. Create a table containing a VARCHAR field that contains valid id values (only numbers).\r\n2. Run a migration similar to the above, requesting a change the VARCHAR to unsigned BIGINT.", "comments": [ { "body": "What was the error message?", "created_at": "2019-11-08T22:34:26Z" }, { "body": "> What was the error message?\r\n\r\n```SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CHARACTER SET utf8 NOT NULL COLLATE `utf8_unicode_ci`, CHANGE user_id user_id B' at line 3```\r\n\r\nThose character set and collate instructions should not have been there.", "created_at": "2019-11-11T09:01:01Z" }, { "body": "What version of the `doctrine/dbal` package are you using (run `composer show)`?", "created_at": "2019-11-11T09:20:07Z" }, { "body": "> What version of the doctrine/dbal package are you using (run composer show)?\r\n\r\nHere:\r\n`doctrine/dbal v2.10.0`", "created_at": "2019-11-11T09:23:46Z" }, { "body": "Can you try downgrading to `2.9.3`?\r\n\r\nIt looks like this is the same bug: https://github.com/doctrine/dbal/issues/3714", "created_at": "2019-11-11T09:28:47Z" }, { "body": "> Can you try downgrading to 2.9.3?\r\n> It looks like this is the same bug: doctrine/dbal#3714\r\n\r\nIt does indeed look like the same bug, I'll subscribe to that bug tracker to see when it's been fixed and I could update this ticket in turn.\r\n\r\nI don't have the time at the moment to try the downgrade due to work pressures and the manual script work around is functional for the moment, but if I get a chance to I shall look in to it.", "created_at": "2019-11-11T09:39:12Z" }, { "body": "Seems like this is related to DBAL and not Laravel so going to close this one.", "created_at": "2019-11-11T10:50:29Z" }, { "body": "DBAL just closed the issue: see https://github.com/doctrine/dbal/issues/3714#issuecomment-558573089", "created_at": "2019-11-26T11:09:27Z" }, { "body": "Can please folks from Laravel and folks from Doctrine make an agreement and push this issue a bit further? \r\nhttps://github.com/doctrine/dbal/issues/3714#issuecomment-559585932\r\n\r\nLaravel says it's issue on Doctrine's side. Doctrine says it's issue on Laravel side. Meanwhile we are locked on older version of Doctrine when we want to keep our projects up-to-date.\r\nThank you in advance.\r\n\r\nPlease note this happened to us when changing varchar column to integer.", "created_at": "2019-11-28T21:23:35Z" }, { "body": "Hello everyone, I'm one of the core members of the Doctrine team 👋\r\n\r\nAs I mentioned on the issue in DBAL, I completely understand your frustration and am sorry for this inconvenience.\r\n\r\nWe really believe that the issue is related to how Laravel configures the DBAL objects to perform the comparisons and think that it was working previously due to a bug that got fixed. \r\n\r\nI don't know Laravel so much to solve this but feel free to ping me in a PR or on Doctrine's slack channel and I'll do my best to support the resolution of this issue. \r\n\r\n@JohnyProkie thanks for pointing us here and @driesvints and other Laravel maintainers for their hard work on building bridges between the two projects 🤟\r\n", "created_at": "2019-11-28T22:32:04Z" }, { "body": "@lcobucci Thank you a lot for stepping in!", "created_at": "2019-11-29T08:03:26Z" }, { "body": "Let's figure this out. If anyone could help pinpoint where we can implement a fix that'd be great. \r\n\r\n@lcobucci thanks for your hard work on Doctrine as well :)", "created_at": "2019-11-29T12:49:22Z" }, { "body": "@driesvints I haven't debugged anything but https://github.com/laravel/framework/blob/1bbe5528568555d597582fdbec73e31f8a818dbc/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php#L125-L127 might give us a clue.\r\n\r\nLaravel should make sure to not set the charset/collation info on the objects while performing the changes.", "created_at": "2019-11-29T15:09:52Z" }, { "body": "@lcobucci it does seem that only applies to `json` and `binary` columns while the issue here is changing a column type from `varchar` to `bigint` so I'm not sure if that's the actual culprit?\r\n\r\nhttps://github.com/laravel/framework/blob/1bbe5528568555d597582fdbec73e31f8a818dbc/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php#L124-L128", "created_at": "2019-12-02T11:29:11Z" }, { "body": "@driesvints that's the problem. As [@AlterTable explained it](https://github.com/doctrine/dbal/issues/3714#issuecomment-549767693):\r\n\r\n> But when it's original type was varchar/text, there is a implicit change: the charset definition should be removed. Neither Laravel nor Doctrine handled this.\r\n> I think there are two ways to fix this, one is add extra checks in \\Doctrine\\DBAL\\Schema\\Table::changeColumn, another is modify Laravel migrate, add checks after changed attributes are set. I prefer the second one.\r\n\r\nLaravel should define `characterset` and `collation` as `null` to remove that info.\r\n\r\nDoes this help?", "created_at": "2019-12-02T12:37:50Z" }, { "body": "@lcobucci heya, it does. I think this is indeed the correct way to go forward. I currently don't have time to work on this so if anyone is experiencing this issue and wants to move this forward, feel free to send in a PR.", "created_at": "2019-12-06T16:43:37Z" }, { "body": "Hi all, if anyone on Laravel 6.x & doctrine/dbal 2.10 experiencing this issue, the quick fix is to set charset and collation to empty string on column change statement. For example:\r\n\r\n`$table->integer('resource_type')->default(0)->charset('')->collation('')->change();`\r\n\r\nIt does work on my case where previous column type is string (varchar).\r\nLooks like someone has already sent PR to fix this, but I hope solution above still help before the PR merged.", "created_at": "2019-12-09T23:25:01Z" }, { "body": "> Hi all, if anyone on Laravel 6.x & doctrine/dbal 2.10 experiencing this issue, the quick fix is to set charset and collation to empty string on column change statement. For example:\r\n> \r\n> `$table->integer('resource_type')->default(0)->charset('')->collation('')->change();`\r\n> \r\n> It does work on my case where previous column type is string (varchar).\r\n> Looks like someone has already sent PR to fix this, but I hope solution above still help before the PR merged.\r\n\r\nThis unfortunately isn't working for me for some reason. I've tried `null` and `''` for charset and collation and I still get the same error. I'm going from `string` to `bigInteger`:\r\n\r\n```php\r\n$table->bigInteger('number')\r\n ->charset('')\r\n ->collation('')\r\n ->change();\r\n```\r\n\r\nI finally ended up just running the raw query:\r\n\r\n```sql\r\n\\DB::statement('alter table orders modify number bigint not null');\r\n```", "created_at": "2020-02-11T15:39:29Z" }, { "body": "Fixed by https://github.com/laravel/framework/commit/fccdf7c42d5ceb50985b3e8243d7ba650de996d6", "created_at": "2020-04-30T20:10:30Z" }, { "body": "still present in:\r\n\"php\": \"^7.2\",\r\n\"laravel/framework\": \"^6.0\",\r\n\"doctrine/dbal\": \"^2.10\",\r\n\r\nerror while trying to change column from text to blob\r\n\r\nworkaround for me was to make a intermediary migration that runs above the alter and drop the column and recreate it for both fwd and reverse migration\r\n\r\n`Doctrine\\DBAL\\Driver\\PDOException::(\"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARACTER SET utf8mb4 DEFAULT NULL' at line 1\")\r\n /var/www/****/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:66`", "created_at": "2020-06-10T13:15:40Z" }, { "body": "@strtz try to update dependencies", "created_at": "2020-07-02T17:22:46Z" }, { "body": "> Fixed by [fccdf7c](https://github.com/laravel/framework/commit/fccdf7c42d5ceb50985b3e8243d7ba650de996d6)\r\n\r\nIt worked thanks @taylorotwell ", "created_at": "2020-08-11T09:40:10Z" } ], "number": 30539, "title": "Migrating a varchar to a bigint causes invalid charset instructions to appear" }
{ "body": "I was glad to see #30539 got fixed by fccdf7c, but after I updated Laravel to 7.10.3 my issue was still present. I was changing a varchar to a boolean and that one is missing from the list of types that don't need character options. This PR adds it to that list!", "number": 32716, "review_comments": [], "title": "[6.x] Add boolean to types that don't need character options" }
{ "commits": [ { "message": "Add boolean to types that don't need char options" } ], "files": [ { "diff": "@@ -189,6 +189,7 @@ protected static function doesntNeedCharacterOptions($type)\n return in_array($type, [\n 'bigInteger',\n 'binary',\n+ 'boolean',\n 'date',\n 'decimal',\n 'double',", "filename": "src/Illuminate/Database/Schema/Grammars/ChangeColumn.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 7.6.2\r\n- PHP Version: 7.2.25\r\n- Database Driver & Version: MySQL 5.5.5-10.4.10-MariaDB\r\n\r\n### Description: \r\n\r\nUsing `whereHasMorph` and `orWhereHasMorph` when there are records with null values on morph columns, laravel produces this error:\r\n\r\n```\r\nSearch Filter (Ambengers\\QueryFilter\\Tests\\Feature\\SearchFilter)\r\n ✘ It can search through polymorphic relation\r\n ┐\r\n ├ Error: Class name must be a valid object or a string\r\n │\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php:718\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php:179\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:245\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:90\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:247\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:217\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:228\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:266\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:227\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:228\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:229\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:321\r\n```\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\nFor simplicity's sake, let's use the comments example we have on docs:\r\n\r\nhttps://laravel.com/docs/7.x/eloquent-relationships#querying-polymorphic-relationships\r\n\r\n1. Setup a couple comment records in the database. Let couple of records be null on `commentable_type` and `commentable_id` columns.\r\n2. Run the `whereHasMorph` query against comments like so:\r\n\r\n```\r\n$comments = App\\Comment::whereHasMorph('commentable', '*', function (Builder $query) {\r\n $query->where('title', 'like', 'foo%');\r\n})->get();\r\n```", "comments": [ { "body": "I can reproduce this bug.", "created_at": "2020-04-20T08:27:23Z" }, { "body": "Please see https://github.com/laravel/framework/issues/29357", "created_at": "2020-04-20T09:17:07Z" }, { "body": "@driesvints I am also using this for morphTo and it's still not working.", "created_at": "2020-04-20T16:01:17Z" }, { "body": "@driesvints I don't think the solution on #29357 is the same solution for this issue, if that's the reason this issue is being closed.", "created_at": "2020-04-20T23:55:14Z" }, { "body": "@driesvints I can provide a more detailed explanation as this bug occurs specifically when querying morphs of any type (using `*`).\r\n\r\nMigration:\r\n\r\n```php\r\n...\r\n$table->nullableMorphs('service');\r\n...\r\n```\r\n\r\nModel:\r\n\r\n```php\r\npublic function service()\r\n{\r\n return $this->morphTo();\r\n}\r\n```\r\n\r\nWhen there is a `ModelName` record with actually null `service_id` and `service_type` columns, it works like this:\r\n\r\nThis one WORKS:\r\n```php\r\nModelName::whereHasMorph('service', [RelatedOne::class, RelatedTwo::class])\r\n```\r\n\r\nThis one does not:\r\n```php\r\nModelName::whereHasMorph('service', '*')\r\n```\r\n\r\nWhen there are no null morphs in the database, both actually work as expected.\r\n\r\nTherefore, there appears to be a bug in the handling of \"any\" type.", "created_at": "2020-04-21T02:15:27Z" }, { "body": "Okay re-opening.\r\n\r\n@staudenmeir do you might know what's going on here?", "created_at": "2020-04-21T13:05:41Z" }, { "body": "@DSpeichert or @driesvints - is it correct to say that when we use wildcard (\"*\") on `whereHasMorph`, we also expect to get rows with null morph columns?", "created_at": "2020-04-21T14:00:13Z" }, { "body": "I'll submit a fix.", "created_at": "2020-04-21T17:08:45Z" }, { "body": "@ambengers Right now it looks like undefined behavior, but in my opinion, when using `whereHasMorph('morph', '*')`, I have an expectation of NOT getting morphs with NULL values. If they are NULL, we don't actually \"have morph\".\r\n\r\nI'd be curious to see what is the \"desired\" behavior for soft-deleted morphs. I guess that by following Laravel's prior pattern, those would be skipped as well, although that would make it impossible to decide through the Closure (one could do `->whereNull('deleted_at')` in the Closure).", "created_at": "2020-04-23T03:50:03Z" }, { "body": "@DSpeichert The wildcard includes soft-deleted morph types.\r\n\r\nA query like this works correctly even if all comments of a certain type are soft-deleted:\r\n\r\n```php\r\nComment::whereHasMorph('commentable', '*', function (Builder $query) {\r\n $query->where('title', 'like', 'foo%');\r\n})->withTrashed()->get();\r\n```", "created_at": "2020-04-23T12:47:42Z" }, { "body": "Fixed. I don't think when using `whereHasMorph` with `*` you should get back nullable morph column models. They don't have a morph parent and if you want all comments, including null morphs... seems like you can just issue your own custom query for the comments.", "created_at": "2020-04-30T16:35:37Z" }, { "body": "This doesn't consider if all morph records in a table are null and, since we're not even hitting the loop here, will return all records:\r\n\r\nhttps://github.com/laravel/framework/blob/92957206252cd4e40430f6f9eb2560566fa34ba3/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L216\r\n\r\nI would expect something like:\r\n\r\n```\r\nif (count($types) > 0) {\r\n // foreach ($types as $type)...\r\n} else {\r\n $query->whereNotNull(this->query->from.'.'.$relation->getMorphType());\r\n}\r\n```\r\n\r\n...for consistency. Thoughts?", "created_at": "2020-12-15T05:58:48Z" } ], "number": 32458, "title": "Error on `whereHasMorph` when morph columns are null" }
{ "body": "Closes #32458", "number": 32614, "review_comments": [], "title": "[6.x] Filtering null's in hasMorph()" }
{ "commits": [ { "message": "Merge pull request #2 from laravel/6.x\n\nmerge from base" }, { "message": "Merge pull request #3 from laravel/6.x\n\nbase merge" }, { "message": "fix" } ], "files": [ { "diff": "@@ -204,7 +204,7 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole\n $types = (array) $types;\n \n if ($types === ['*']) {\n- $types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())->all();\n+ $types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())->filter()->all();\n \n foreach ($types as &$type) {\n $type = Relation::getMorphedModel($type) ?? $type;", "filename": "src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.7\r\n- PHP Version: 7.2\r\n- Database Driver & Version: Postgres\r\n\r\n### Description:\r\nRelationships that were loaded on a model before serialisation are restored during deserialisation, eg. when using a model in a queued event or job. During deserialisation, an error occurs if a polymorphic relationship was loaded on the model, where one of the polymorphic types has in turn a child relationship loaded that does not exist on one of the other polymorphic types. The issue occurs when the polymorphic child that has the relationship is first in the relationship and the nested relationship is loaded during serialisation.\r\n\r\nI assume this method in Eloquent\\Collection is part of the issue by picking the the first item in the collection to determine which child relationships exist:\r\n\r\n```php\r\n /**\r\n * Get the relationships of the entities being queued.\r\n *\r\n * @return array\r\n */\r\n public function getQueueableRelations()\r\n {\r\n return $this->isNotEmpty() ? $this->first()->getQueueableRelations() : [];\r\n }\r\n```\r\n\r\n### Steps To Reproduce:\r\n#### 1. Have the following model tree:\r\n\r\n```php\r\nclass Parent extends Model\r\n{\r\n public function children()\r\n {\r\n return $this->morphTo();\r\n }\r\n}\r\n\r\nclass ChildTypeOne extends Model\r\n{\r\n public function parent()\r\n {\r\n return $this->morphMany(Parent::class, 'parentable');\r\n }\r\n\r\n public function nestedRelationship()\r\n {\r\n // Note: This relationship does not exist on ChildTypeTwo\r\n $this->hasMany(AnyOtherModel::class);\r\n }\r\n}\r\n\r\nclass ChildTypeTwo extends Model\r\n{\r\n public function parent()\r\n {\r\n return $this->morphMany(Parent::class, 'parentable');\r\n }\r\n}\r\n```\r\n\r\n#### 2. Create some instances\r\n#### 3. `->load('children')` on a `Parent` instance, ensuring that the first loaded item is a `ChildTypeOne`\r\n#### 4. `->load('nestedRelationship')` on the first of the `ChildTypeOne` instanced loaded on the parent\r\n#### 5. Serialize the `Parent` instance, eg. by setting it as a property of a queued job or event\r\n#### 6. Deserialize it by handling the job.", "comments": [ { "body": "I don't see a feasible way to restore the exact eager loading in a case like this.\r\n\r\nWe can fix it in `Collection::getQueueableRelations()` by getting the relationships from all models (instead of only the first one) and then calculating the intersection.", "created_at": "2018-10-15T23:48:42Z" }, { "body": "I had the same polymorphic problem along with infinite recursion when serializing circular relationships.\r\n\r\nSince I don't require event-broadcast payloads (that this feature was added for), I've just disabled queued relationship serialization altogether in a base model class:\r\n\r\n```php\r\nnamespace App;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model as BaseModel;\r\n\r\nclass Model extends BaseModel\r\n{\r\n /**\r\n * Disable SerializesAndRestoresModelIdentifiers@getSerializedPropertyValue().\r\n *\r\n * @return array\r\n */\r\n public function getQueueableRelations()\r\n {\r\n return [];\r\n }\r\n}\r\n```\r\n\r\nAwhile back I had a brief look at actually fixing polymorphic relations but as already mentioned, it's not an easy problem to solve.\r\n\r\nMaybe the framework should instead support a way to disable queuing mixed/polymorphic relationship IDs?", "created_at": "2018-10-17T04:07:54Z" }, { "body": "This change was introduced from 5.5 to 5.6\r\n\r\nI can confirm this is also happening on 5.6 and this is the reason we are still staying on 5.5 for now.\r\n\r\nThe issue occurs when we have a relation which has many in combination with morph\r\nIe:\r\n`booking.points.pointable.X`\r\nWhere `points` is a hasMany relation\r\nWhere `pointable` is a Morph relation\r\nWhere `X` is a hasOne relation\r\n\r\nA booking contains multiple points and when we load `booking.points[0].pointable.X`\r\nUpon deserialization, it also tries to load `pointable.X` on all the other `points.pointable's`, which may not always be there.\r\n\r\nSecondly, I don't think it is clean to pass a different serialization object depending on what happened to the object before it was passed on to the job. IMO it should always be the same as a job should be a stand-alone isolated runnable program. I am very much interested in the reason to include relations in the serialization of job models as it can create different situations depending on what is loaded and what is not\r\n\r\nThe related commit is the following:\r\nhttps://github.com/laravel/framework/commit/230eeef6113bf7a5632578508c3316583ac22534#diff-955cb662f7bf33d1dec2eee598ce800d", "created_at": "2018-11-28T10:51:41Z" }, { "body": "Currently having this problem on a 5.7 project. Does anyone know if it's been resolved since then?", "created_at": "2019-12-04T15:59:11Z" }, { "body": "Fixed by #32613 ", "created_at": "2020-04-30T16:19:14Z" } ], "number": 26126, "title": "Trying to load non-existing relationships on deserialisation of an object with polymorphic children" }
{ "body": "Fixes #26126\r\n\r\nWe only want to restore relationships that are common amongst all models in the collection. Otherwise there will be errors be attempting to restore the collection.\r\n\r\nOne downside to this PR could be potential performance implications of getting the queueable relationships for each model in the collection. I did this in a collection of about 1000 models and it took 0.70ms on my local machine. ", "number": 32613, "review_comments": [], "title": "[6.x] Only restore common relations" }
{ "commits": [ { "message": "only load common relations" }, { "message": "one line" }, { "message": "performance improvement" }, { "message": "add test" } ], "files": [ { "diff": "@@ -557,7 +557,7 @@ public function getQueueableIds()\n */\n public function getQueueableRelations()\n {\n- return $this->isNotEmpty() ? $this->first()->getQueueableRelations() : [];\n+ return $this->isEmpty() ? [] : array_intersect(...$this->map->getQueueableRelations()->all());\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/Collection.php", "status": "modified" }, { "diff": "@@ -422,6 +422,24 @@ public function testQueueableCollectionImplementationThrowsExceptionOnMultipleMo\n $c->getQueueableClass();\n }\n \n+ public function testQueueableRelationshipsReturnsOnlyRelationsCommonToAllModels()\n+ {\n+ // This is needed to prevent loading non-existing relationships on polymorphic model collections (#26126)\n+ $c = new Collection([new class {\n+ public function getQueueableRelations()\n+ {\n+ return ['user'];\n+ }\n+ }, new class {\n+ public function getQueueableRelations()\n+ {\n+ return ['user', 'comments'];\n+ }\n+ }]);\n+\n+ $this->assertEquals(['user'], $c->getQueueableRelations());\n+ }\n+\n public function testEmptyCollectionStayEmptyOnFresh()\n {\n $c = new Collection;", "filename": "tests/Database/DatabaseEloquentCollectionTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 7.6.2\r\n- PHP Version: 7.2.25\r\n- Database Driver & Version: MySQL 5.5.5-10.4.10-MariaDB\r\n\r\n### Description: \r\n\r\nUsing `whereHasMorph` and `orWhereHasMorph` when there are records with null values on morph columns, laravel produces this error:\r\n\r\n```\r\nSearch Filter (Ambengers\\QueryFilter\\Tests\\Feature\\SearchFilter)\r\n ✘ It can search through polymorphic relation\r\n ┐\r\n ├ Error: Class name must be a valid object or a string\r\n │\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php:718\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php:179\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:245\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:90\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:247\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:217\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:228\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:266\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:227\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:228\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:229\r\n ╵ /Users/dignity/codes/query-filter/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:321\r\n```\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\nFor simplicity's sake, let's use the comments example we have on docs:\r\n\r\nhttps://laravel.com/docs/7.x/eloquent-relationships#querying-polymorphic-relationships\r\n\r\n1. Setup a couple comment records in the database. Let couple of records be null on `commentable_type` and `commentable_id` columns.\r\n2. Run the `whereHasMorph` query against comments like so:\r\n\r\n```\r\n$comments = App\\Comment::whereHasMorph('commentable', '*', function (Builder $query) {\r\n $query->where('title', 'like', 'foo%');\r\n})->get();\r\n```", "comments": [ { "body": "I can reproduce this bug.", "created_at": "2020-04-20T08:27:23Z" }, { "body": "Please see https://github.com/laravel/framework/issues/29357", "created_at": "2020-04-20T09:17:07Z" }, { "body": "@driesvints I am also using this for morphTo and it's still not working.", "created_at": "2020-04-20T16:01:17Z" }, { "body": "@driesvints I don't think the solution on #29357 is the same solution for this issue, if that's the reason this issue is being closed.", "created_at": "2020-04-20T23:55:14Z" }, { "body": "@driesvints I can provide a more detailed explanation as this bug occurs specifically when querying morphs of any type (using `*`).\r\n\r\nMigration:\r\n\r\n```php\r\n...\r\n$table->nullableMorphs('service');\r\n...\r\n```\r\n\r\nModel:\r\n\r\n```php\r\npublic function service()\r\n{\r\n return $this->morphTo();\r\n}\r\n```\r\n\r\nWhen there is a `ModelName` record with actually null `service_id` and `service_type` columns, it works like this:\r\n\r\nThis one WORKS:\r\n```php\r\nModelName::whereHasMorph('service', [RelatedOne::class, RelatedTwo::class])\r\n```\r\n\r\nThis one does not:\r\n```php\r\nModelName::whereHasMorph('service', '*')\r\n```\r\n\r\nWhen there are no null morphs in the database, both actually work as expected.\r\n\r\nTherefore, there appears to be a bug in the handling of \"any\" type.", "created_at": "2020-04-21T02:15:27Z" }, { "body": "Okay re-opening.\r\n\r\n@staudenmeir do you might know what's going on here?", "created_at": "2020-04-21T13:05:41Z" }, { "body": "@DSpeichert or @driesvints - is it correct to say that when we use wildcard (\"*\") on `whereHasMorph`, we also expect to get rows with null morph columns?", "created_at": "2020-04-21T14:00:13Z" }, { "body": "I'll submit a fix.", "created_at": "2020-04-21T17:08:45Z" }, { "body": "@ambengers Right now it looks like undefined behavior, but in my opinion, when using `whereHasMorph('morph', '*')`, I have an expectation of NOT getting morphs with NULL values. If they are NULL, we don't actually \"have morph\".\r\n\r\nI'd be curious to see what is the \"desired\" behavior for soft-deleted morphs. I guess that by following Laravel's prior pattern, those would be skipped as well, although that would make it impossible to decide through the Closure (one could do `->whereNull('deleted_at')` in the Closure).", "created_at": "2020-04-23T03:50:03Z" }, { "body": "@DSpeichert The wildcard includes soft-deleted morph types.\r\n\r\nA query like this works correctly even if all comments of a certain type are soft-deleted:\r\n\r\n```php\r\nComment::whereHasMorph('commentable', '*', function (Builder $query) {\r\n $query->where('title', 'like', 'foo%');\r\n})->withTrashed()->get();\r\n```", "created_at": "2020-04-23T12:47:42Z" }, { "body": "Fixed. I don't think when using `whereHasMorph` with `*` you should get back nullable morph column models. They don't have a morph parent and if you want all comments, including null morphs... seems like you can just issue your own custom query for the comments.", "created_at": "2020-04-30T16:35:37Z" }, { "body": "This doesn't consider if all morph records in a table are null and, since we're not even hitting the loop here, will return all records:\r\n\r\nhttps://github.com/laravel/framework/blob/92957206252cd4e40430f6f9eb2560566fa34ba3/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L216\r\n\r\nI would expect something like:\r\n\r\n```\r\nif (count($types) > 0) {\r\n // foreach ($types as $type)...\r\n} else {\r\n $query->whereNotNull(this->query->from.'.'.$relation->getMorphType());\r\n}\r\n```\r\n\r\n...for consistency. Thoughts?", "created_at": "2020-12-15T05:58:48Z" } ], "number": 32458, "title": "Error on `whereHasMorph` when morph columns are null" }
{ "body": "Closes #32458\r\n\r\n<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n", "number": 32612, "review_comments": [], "title": "[7.x] Filtering null's in hasMorph()" }
{ "commits": [ { "message": "Filtering null's in hasMorph()\n\nCloses #32458" } ], "files": [ { "diff": "@@ -204,7 +204,7 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole\n $types = (array) $types;\n \n if ($types === ['*']) {\n- $types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())->all();\n+ $types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())->filter()->all();\n \n foreach ($types as &$type) {\n $type = Relation::getMorphedModel($type) ?? $type;", "filename": "src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.5.33 - 5.6.15\r\n- PHP Version: 7.2\r\n\r\n### Description:\r\n\r\nIt seems like `withoutGlobalScopes()` and `withoutGlobalScope()` is ignored on `HasManyThrough` relations.\r\n\r\nThe query generated by the example below is:\r\n\r\n```sql\r\nSELECT\r\n *\r\nFROM\r\n \"comments\"\r\nINNER JOIN\r\n \"posts\" ON \"post\".\"id\" = \"comments\".\"post_id\"\r\nWHERE\r\n \"posts\".\"deleted_at\" IS NULL\r\n AND \"posts\".\"user_id\" = ?\r\n```\r\n\r\nBut should be:\r\n\r\n```sql\r\nSELECT\r\n *\r\nFROM\r\n \"comments\"\r\nINNER JOIN\r\n \"posts\" ON \"post\".\"id\" = \"comments\".\"post_id\"\r\nWHERE\r\n \"posts\".\"user_id\" = ?\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\nclass User extends Model\r\n{\r\n public function comments()\r\n {\r\n return $this->hasManyThrough(Comment::class, Post::class)\r\n ->withoutGlobalScopes();\r\n }\r\n}\r\n```\r\n", "comments": [ { "body": "Does it work if you run `withoutGlobalScopes` before the relationship?\r\n\r\nThis is why I believe the above will work: https://github.com/laravel/framework/blob/56a58e0fa3d845bb992d7c64ac9bb6d0c24b745a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L251-L263\r\n\r\nBecause of this, I think this is possibly related to #18052 and #21856", "created_at": "2018-02-11T19:49:53Z" }, { "body": "What do you mean by \"run before the relationship\"?", "created_at": "2018-02-11T20:05:54Z" }, { "body": "```php\r\ndd(\r\n $user->comments()->toSql(),\r\n $user->comments()->withoutGlobalScopes()->toSql()\r\n);\r\n```\r\n\r\nBoth build the same query with with:\r\n\r\n```sql\r\n\"posts\".\"deleted_at\" IS NULL\r\n```", "created_at": "2018-02-11T22:07:12Z" }, { "body": "For example, `$user->withoutGlobalScopes()->comments()` possibly?", "created_at": "2018-02-12T22:18:20Z" }, { "body": "`Call to undefined method Illuminate\\Database\\Query\\Builder::comments()`", "created_at": "2018-02-13T16:13:45Z" }, { "body": "Forgot that it's the trait's function returning `$this`. Seems like it could be a legitimate bug.", "created_at": "2018-02-13T19:09:59Z" }, { "body": "Does `withoutGlobalScopes()` apply only current model not the related model?\r\n\r\n```php\r\n$store = Store::with('user')\r\n ->withoutGlobalScopes()\r\n ->where('storename', $storename)\r\n ->first();\r\n```\r\n\r\nalso does not work.\r\n\r\nStore does not have scope but User has. It does not apply for User therefore it returns \r\n\r\n````\r\n[\r\n ...\r\n user: null\r\n]\r\n````\r\n\r\nPlease need some help", "created_at": "2018-03-07T12:19:10Z" }, { "body": "The intermediate model is a complicated case. Just calling the relationship (`$user->comments()`) already adds the `SoftDeletes` constraint to the query. `->withoutGlobalScopes()` would have to remove it retroactively.\r\n\r\nSomewhat related but the opposite problem: Other global scopes on the intermediate model don't get applied at all:\r\n\r\n```php\r\nclass Post extends Model {\r\n protected static function boot() {\r\n parent::boot();\r\n\r\n static::addGlobalScope('test', function ($query) {\r\n $query->where('column', 'value');\r\n });\r\n }\r\n}\r\n```", "created_at": "2018-08-20T02:58:05Z" }, { "body": "Perhaps a better solution for this but this is how I got around this problem by extending the hasManyThrough relationship when I needed to extend the existing soft deletes trait and scope to work with a different database structure that doesnt use deleted_at columns with a timestamp\r\n\r\n```php\r\n<?php\r\n\r\nnamespace App\\Eloquent\\Relations;\r\n\r\nuse Illuminate\\Database\\Eloquent;\r\n\r\nclass HasManyThrough extends Eloquent\\Relations\\HasManyThrough\r\n{\r\n /**\r\n * Set the join clause on the query\r\n * @param \\Illuminate\\Database\\Eloquent\\Builder|null $query\r\n * @return void\r\n */\r\n protected function setJoin(Eloquent\\Builder $query = null)\r\n {\r\n $query = ($query) ?: $this->query;\r\n $strForeignKey = $this->related->getTable().'.'.$this->secondKey;\r\n $query->join($this->parent->getTable(), $this->getQualifiedParentKeyName(), '=', $strForeignKey);\r\n\r\n if ($Scope = $this->parentSoftDeletes()) {\r\n // Eloquent hard codes $query->whereNull($this->parent->getQualifiedDeletedAtColumn())\r\n // on HasManyThrough which breaks everything, so use our instance of SoftDeletingScope instead\r\n $Scope->apply($query, $this->parent);\r\n }\r\n }\r\n\r\n /**\r\n * Determine whether close parent of the relation uses Soft Deletes\r\n * @return Eloquent\\SoftDeletingScope|null\r\n */\r\n public function parentSoftDeletes()\r\n {\r\n $arrRemovedScopes = $this->query->removedScopes();\r\n // Get the instance of SoftDeletingScope on the parent model that requires it\r\n foreach ($this->parent->getGlobalScopes() as $strClassName => $Scope) {\r\n if (\r\n $Scope instanceof Eloquent\\SoftDeletingScope &&\r\n !in_array($strClassName, $arrRemovedScopes)\r\n ) {\r\n return $Scope;\r\n }\r\n }\r\n // Seems unlikely but just in case SoftDeletes is on the model but the scope wasnt applied / failed to boot\r\n if (\r\n !in_array(Eloquent\\SoftDeletingScope::class, $arrRemovedScopes) &&\r\n in_array(Eloquent\\SoftDeletes::class, class_uses_recursive(get_class($this->parent)))\r\n ) {\r\n return new Eloquent\\SoftDeletingScope();\r\n }\r\n return null;\r\n }\r\n}\r\n```\r\n\r\n", "created_at": "2019-02-22T15:41:21Z" }, { "body": "Almost two years later and there is still no way of doing this without using an external package :/ ", "created_at": "2019-11-09T18:43:31Z" }, { "body": "@LonnyX you're free to help out by sending in a PR.", "created_at": "2019-11-11T12:48:35Z" }, { "body": "+1", "created_at": "2020-04-13T20:06:56Z" }, { "body": "Tried to reproduce this in tests to fix it, but it seems it's working correctly now (at least in 6.x).\r\n@tillkruss is it working now? Or my test scenario is not as same as yours?\r\n\r\nhttps://github.com/laravel/framework/commit/74f7b9e9d9a2a766d813228492e484761cad9c64", "created_at": "2020-04-30T10:46:31Z" }, { "body": "@yaim Your test scenario is different, the issue is about global scopes on the _intermediate_ model.", "created_at": "2020-04-30T12:39:45Z" }, { "body": "Fixed by #32609 ", "created_at": "2020-04-30T14:52:37Z" }, { "body": "> Somewhat related but the opposite problem: Other global scopes on the intermediate model don't get applied at all\r\n \r\nI stumbled upon that today @staudenmeir, what a surprise to discover that!\r\n\r\nBefore I deep dive into the code, do you think a PR could be issued for this particular case, or is there something I'm not aware of that prevents from having a global solution?\r\n", "created_at": "2020-05-30T17:02:03Z" }, { "body": "@ChristopheB I looked into it back then when I noticed the issue but didn't see a good solution. It would also be quite a breaking change if we change/fix this now.\r\n\r\nI guess `HasManyThrough` relationships just won't support any other intermediate global scopes besides the native `SoftDeletes`.", "created_at": "2020-05-31T10:20:26Z" }, { "body": "@staudenmeir thanks for your input. We have decided not to use global scopes on our project, so sadly I think I won't have the time to try to fix that. Still I could issue a PR for the docs.", "created_at": "2020-06-02T17:09:08Z" } ], "number": 23039, "title": "withoutGlobalScopes() ignored on HasManyThrough" }
{ "body": "Fixes #23039\r\n\r\nAdds new method to allow removing any soft deleted constraint on the intermediate model of a hasManyThrough relationship.", "number": 32609, "review_comments": [], "title": "[7.x] Allow trashed through parents to be included in has many through queries" }
{ "commits": [ { "message": "allow trashed through parents to be included in has many through queries" } ], "files": [ { "diff": "@@ -115,7 +115,9 @@ protected function performJoin(Builder $query = null)\n $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $farKey);\n \n if ($this->throughParentSoftDeletes()) {\n- $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn());\n+ $query->withGlobalScope('SoftDeletableHasManyThrough', function ($query) {\n+ $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn());\n+ });\n }\n }\n \n@@ -139,6 +141,18 @@ public function throughParentSoftDeletes()\n return in_array(SoftDeletes::class, class_uses_recursive($this->throughParent));\n }\n \n+ /**\n+ * Indicate that trashed \"through\" parents should be included in the query.\n+ *\n+ * @return $this\n+ */\n+ public function withTrashedParents()\n+ {\n+ $this->query->withoutGlobalScope('SoftDeletableHasManyThrough');\n+\n+ return $this;\n+ }\n+\n /**\n * Set the constraints for an eager load of the relation.\n *", "filename": "src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.18.0\r\n- PHP Version: 7.2\r\n- Database Driver & Version: Mysql 5.7\r\n\r\n### Description:\r\n\r\nThis is a regression introduced in #31125 - all custom pivot models that uses [`AsPivot`](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php) trait are broken now due to this line:\r\n\r\nhttps://github.com/laravel/framework/blob/898f24ec56d5a2859a28f4dc0cc98ae967eec456/src/Illuminate/Database/Eloquent/Model.php#L1154\r\n\r\nobviously it should also check if the model uses `AsPivot` trait. Something like:\r\n\r\n```php\r\nreturn $relation instanceof Pivot\r\n || in_array(AsPivot::class, class_uses_recursive($relation), true);\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Create new laravel 6.x app\r\n2. Create `user_users` table\r\n ```sql\r\n CREATE TABLE IF NOT EXISTS `user_users` (\r\n `my_user_id` BIGINT(20) UNSIGNED NOT NULL,\r\n `pivot_my_user_id` BIGINT(20) UNSIGNED NOT NULL\r\n )\r\n ```\r\n3. Run this test\r\n ```php\r\n <?php\r\n \r\n namespace Tests\\Unit;\r\n \r\n use App\\User;\r\n use Illuminate\\Database\\Eloquent\\Model;\r\n use Illuminate\\Database\\Eloquent\\Relations\\Concerns\\AsPivot;\r\n use Tests\\TestCase;\r\n \r\n class ExampleTest extends TestCase {\r\n public function testAsPivotRefresh() {\r\n $user = MyUser::query()->findOrFail(factory(User::class)->create()->getKey());\r\n $child = MyUser::query()->findOrFail(factory(User::class)->create()->getKey());\r\n \r\n $user->users()->attach($child->getKey());\r\n \r\n $this->assertEquals(1, $user->users->count());\r\n \r\n $user->users->first()->refresh();\r\n }\r\n }\r\n \r\n class MyUser extends User {\r\n protected $table = 'users';\r\n \r\n public function users() {\r\n return $this\r\n ->belongsToMany(static::class, (new UserPivot())->getTable(), 'my_user_id', 'pivot_my_user_id')\r\n ->using(UserPivot::class);\r\n }\r\n }\r\n \r\n class UserPivot extends Model {\r\n use AsPivot;\r\n \r\n protected $table = 'user_users';\r\n }\r\n ```", "comments": [ { "body": "> in_array(AsPivot::class, class_uses_recursive($relation), true);\r\n\r\nThis feels kinda hacky. Shouldn't we have an interface for this?", "created_at": "2020-03-09T14:17:27Z" }, { "body": "> This feels kinda hacky. Shouldn't we have an interface for this?\r\n\r\nAgreed, but interface will not fix existing code", "created_at": "2020-03-09T17:08:26Z" }, { "body": "> > in_array(AsPivot::class, class_uses_recursive($relation), true);\r\n> \r\n> This feels kinda hacky. Shouldn't we have an interface for this?\r\n\r\nI'd prefer to use the interface in all honesty, and I'm sure if people run into this problem they will find the information in the docs somewhere.\r\n\r\nI don't believe traits should be used to enforce outside functionality on the edge of your application. The interface approach has already been taken with other checks & rules for model classes.\r\n\r\nHappy to make a PR with the new marker interface.", "created_at": "2020-03-10T09:15:26Z" }, { "body": "Why aren't you extending the `Pivot` class?", "created_at": "2020-03-16T13:16:16Z" }, { "body": "> Why aren't you extending the Pivot class?\r\n\r\n@driesvints for the same reasons as described in initial PR #25851 (\"own abstract Model class\")", "created_at": "2020-03-16T16:13:17Z" }, { "body": "I see. Then an interface won't work here because people would have to implement it manually to solve the problem. We could maybe go for the solution you proposed above. Feel free to send in a PR.", "created_at": "2020-03-17T11:25:20Z" } ], "number": 31811, "title": "refresh(): Call to undefined relationship [pivot] on model" }
{ "body": "The regression was introduced in #31125 - all custom pivot models that uses [`AsPivot`](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php) trait are broken now due to this line:\r\n\r\nhttps://github.com/laravel/framework/blob/898f24ec56d5a2859a28f4dc0cc98ae967eec456/src/Illuminate/Database/Eloquent/Model.php#L1154\r\n\r\nIn other words `$model->refresh()` will throw error \"Call to undefined relationship [pivot] on model\" if `$model` has relations that uses `AsPivot` trait instead extending `Pivot` model.\r\n\r\nThis PR fixes it and closes #31811 (please also see it for more details).", "number": 32420, "review_comments": [], "title": "[6.x] Fix `refresh()` to support `AsPivot` trait" }
{ "commits": [ { "message": "Fixes `refresh()` for `AsPivot` trait." }, { "message": "Code style." } ], "files": [ { "diff": "@@ -10,6 +10,7 @@\n use Illuminate\\Contracts\\Support\\Arrayable;\n use Illuminate\\Contracts\\Support\\Jsonable;\n use Illuminate\\Database\\ConnectionResolverInterface as Resolver;\n+use Illuminate\\Database\\Eloquent\\Relations\\Concerns\\AsPivot;\n use Illuminate\\Database\\Eloquent\\Relations\\Pivot;\n use Illuminate\\Support\\Arr;\n use Illuminate\\Support\\Collection as BaseCollection;\n@@ -1151,7 +1152,8 @@ public function refresh()\n );\n \n $this->load(collect($this->relations)->reject(function ($relation) {\n- return $relation instanceof Pivot;\n+ return $relation instanceof Pivot\n+ || in_array(AsPivot::class, class_uses_recursive($relation), true);\n })->keys()->all());\n \n $this->syncOriginal();", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -3,6 +3,7 @@\n namespace Illuminate\\Tests\\Integration\\Database\\EloquentModelRefreshTest;\n \n use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Eloquent\\Relations\\Concerns\\AsPivot;\n use Illuminate\\Database\\Eloquent\\SoftDeletes;\n use Illuminate\\Database\\Schema\\Blueprint;\n use Illuminate\\Support\\Facades\\Schema;\n@@ -57,6 +58,23 @@ public function testItSyncsOriginalOnRefresh()\n \n $this->assertSame('patrick', $post->getOriginal('title'));\n }\n+\n+ public function testAsPivot()\n+ {\n+ Schema::create('post_posts', function (Blueprint $table) {\n+ $table->bigInteger('foreign_id');\n+ $table->bigInteger('related_id');\n+ });\n+\n+ $post = AsPivotPost::create(['title' => 'parent']);\n+ $child = AsPivotPost::create(['title' => 'child']);\n+\n+ $post->children()->attach($child->getKey());\n+\n+ $this->assertEquals(1, $post->children->count());\n+\n+ $post->children->first()->refresh();\n+ }\n }\n \n class Post extends Model\n@@ -76,3 +94,20 @@ protected static function boot()\n });\n }\n }\n+\n+class AsPivotPost extends Post\n+{\n+ public function children()\n+ {\n+ return $this\n+ ->belongsToMany(static::class, (new AsPivotPostPivot())->getTable(), 'foreign_id', 'related_id')\n+ ->using(AsPivotPostPivot::class);\n+ }\n+}\n+\n+class AsPivotPostPivot extends Model\n+{\n+ use AsPivot;\n+\n+ protected $table = 'post_posts';\n+}", "filename": "tests/Integration/Database/EloquentModelRefreshTest.php", "status": "modified" } ] }
{ "body": "<!-- DO NOT THROW THIS AWAY -->\r\n<!-- Fill out the FULL versions with patch versions -->\r\n\r\n- Laravel Version: 7.4.0 (since 7.0.0)\r\n- PHP Version: 7.3.13\r\n- Database Driver & Version: MySQL 5.7 (MariaDB)\r\n\r\n### Description:\r\nThe `route()` helper doesn't account for the Laravel 7 way of specifying a custom route model binding key inside the route parameter when passing a Model to use implicit binding. It will generate the URL with ID's as parameters instead of the expected column (like a slug).\r\n\r\n### Steps To Reproduce:\r\n1. Create a route like this:\r\n```\r\nRoute::get('/profile/{user:slug}', function (User $user) {\r\n return $user;\r\n})->name('profile');\r\n```\r\n2. Try to generate a URI using the `route()` helper: `route('profile, $user)`\r\n3. Inspect/view the given URI, it should look something like: `https://app.test/profile/1` instead of expected: `https://app.test/profile/@johndoe` (assuming the `slug` is `@johndoe`)", "comments": [ { "body": "I'd also expect that to work. Appreciating a PR if you could send one in.", "created_at": "2020-04-02T13:40:38Z" }, { "body": "@driesvints I tried.. I got it working until I found out that my fix was not compatible with explicitly passing the parameter value (so passing `$user->slug` instead of `$user` as route() argument). I will link my commit, maybe someone can use it as inspiration: https://github.com/elbojoloco/framework/commit/d26bec650aff8242acecf6463d0091f0edf59964\r\n\r\nEdit:\r\nI'll elaborate a bit more on the problem after my fix. \r\n![image](https://user-images.githubusercontent.com/7912315/78261063-0655f300-74ff-11ea-8ecd-fa7defdb69c7.png)\r\nIn this image you can see the first bindingField \"lucas\" being the value that is passed explicitly. The second bindingField is a Post model, because it is passed implicitly. The `formatParameterKeys()` method in my commit only pulls values from the bindingFields array if the respective param is an instance of `UrlRoutable`, which is only true for the Post model. As a result the {post} param will try to use the \"user\" (first bindingField being pulled in this case) key and value \"name\" to find its route binding key, which will fail and result in it not being bound at all.", "created_at": "2020-04-02T14:26:02Z" }, { "body": "you can set it in the model\r\n\r\n```php\r\npublic function getRouteKeyName()\r\n{\r\n return 'slug';\r\n} \r\n```\r\n\r\nor \r\n\r\n```php\r\nroute('profile, ['slug' => $user->slug])\r\n```", "created_at": "2020-04-06T22:38:50Z" } ], "number": 32201, "title": "route() helper doesn't generate correct URI's for routes with a custom binding key" }
{ "body": "fix #32201\r\n\r\nthanks to @abdumu for helping me with this issue", "number": 32264, "review_comments": [ { "body": "It just a suggestion. \r\n```\r\n $bindingFields = $this->bindingFields;\r\n if (is_int($parameter)) {\r\n $bindingFields = array_values($bindingFields);\r\n }\r\n \r\n return $bindingFields[$parameter] ?? null;\r\n```\r\n\r\nOr\r\n\r\n```\r\n $bindingFields = $this->bindingFields;\r\n \r\n return (is_int($parameter) ? array_values($bindingFields)[$parameter] : bindingFields[$parameter]) ?? null;\r\n```", "created_at": "2020-04-07T03:03:00Z" }, { "body": "I did it first like \r\n\r\n```php\r\n $bindingFields = is_int($parameter) ? array_values($this->bindingFields) : $this->bindingFields;\r\n\r\n return $bindingFields[$parameter] ?? null;\r\n```\r\n\r\nbut I wanted the code to be more readable ", "created_at": "2020-04-07T04:01:25Z" } ], "title": "[7.x] Fix route helper with custom binding key" }
{ "commits": [ { "message": "fix route helper with custom binding key" }, { "message": "Update Route.php" }, { "message": "Update Route.php" }, { "message": "Update Route.php" } ], "files": [ { "diff": "@@ -480,12 +480,14 @@ public function signatureParameters($subClass = null)\n /**\n * Get the binding field for the given parameter.\n *\n- * @param string $parameter\n+ * @param string|int $parameter\n * @return string|null\n */\n public function bindingFieldFor($parameter)\n {\n- return $this->bindingFields[$parameter] ?? null;\n+ $fields = is_int($parameter) ? array_values($this->bindingFields) : $this->bindingFields;\n+\n+ return $fields[$parameter] ?? null;\n }\n \n /**", "filename": "src/Illuminate/Routing/Route.php", "status": "modified" }, { "diff": "@@ -369,6 +369,7 @@ public function testRoutableInterfaceRoutingWithCustomBindingField()\n $model->key = 'routable';\n \n $this->assertSame('/foo/test-slug', $url->route('routable', ['bar' => $model], false));\n+ $this->assertSame('/foo/test-slug', $url->route('routable', [$model], false));\n }\n \n public function testRoutableInterfaceRoutingWithSingleParameter()", "filename": "tests/Routing/RoutingUrlGeneratorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.x/7.x\r\n- PHP Version: 7.2. Actual on 7.3, 7.4\r\n- Database Driver & Version: MySQL 5.6/MariaDB 10\r\n\r\n### Description:\r\n\r\nArray casting not working as I'm expecting.\r\nI expect that invalid json string to be converted to an array or an exception to be thrown. But invalid json converts to string.\r\n\r\nInvalid json `string(2) \"\"\"\"` converted to empty string.\r\n\r\nThis happens because json_decode convert some invalid json to ambiguities value. Example:\r\n```php\r\n$string = '\"\"';\r\nvar_dump(json_decode($string, true)); // string(0) \"\"\r\n```\r\n\r\nJson string to array casting uses `json_decode` without any checks.\r\nhttps://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L809\r\n\r\n### Steps To Reproduce:\r\n\r\n* Create some database entity\r\n\r\nMigration:\r\n```php\r\nSchema::create('foo', function (Blueprint $table) {\r\n $table->increments('id');\r\n $table->string('payload');\r\n});\r\n```\r\n\r\nModel:\r\n```php\r\nclass Foo extends Model\r\n{\r\n public $timestamps = false; \r\n\r\n protected $casts = [\r\n 'bar' => 'array'\r\n ];\r\n}\r\n\r\n```\r\n\r\n* Insert new row to database with invalid json:\r\n\r\n```sql\r\nINSERT INTO `foo` (`bar`) VALUES ('\"\"');\r\n```\r\n\r\n* Find element and read bar property\r\n\r\n```\r\n$foo = App\\Foo::find(1);\r\n\r\nvar_dump($foo->bar); // Expects array but given empty string\r\n```\r\n\r\n\r\n", "comments": [ { "body": "I think I agree with you that this is a bug. I've pinged @taylorotwell about this.", "created_at": "2020-03-26T20:18:07Z" }, { "body": "We agree that this seems like a bug. Appreciating a PR if you could make one.", "created_at": "2020-03-26T20:34:07Z" }, { "body": "Okay. I'll try to make PR.\r\n\r\nI want to add that `string(2) \"\"\"\"` is valid json but converted to empty string.\r\nI think that `fromJson` method ([HasAttributes.php#L807](https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L807)) should return only array or object value.\r\n", "created_at": "2020-03-27T08:55:04Z" }, { "body": "I found another example of this strange casts:\r\n```\r\nclass Foo extends Model\r\n{\r\n public $timestamps = false; \r\n\r\n protected $casts = [\r\n 'bar' => 'array'\r\n ];\r\n}\r\n```\r\n\r\n```\r\n$foo = new Foo;\r\n$foo->bar = 'string'; // Something went wrong and for some reason a string got here\r\n$foo->save();\r\n\r\n$foo = Foo::find(1);\r\necho $foo->bar; // string? Why it is string?\r\n```", "created_at": "2020-03-27T21:49:44Z" }, { "body": "Please see Taylor's response on the PR.", "created_at": "2020-03-28T11:08:00Z" }, { "body": "@driesvints at first we said that the bug should be fixed. I spent time on fix and tests, and Taylor closed PR and did not even write any details why it is not bug. I am dissatisfied with this.", "created_at": "2020-03-28T14:59:00Z" }, { "body": "@et-nik Taylor gave an explanation why this isn't a bug.", "created_at": "2020-03-28T15:09:30Z" } ], "number": 32117, "title": "Ambiguities in array eloquent casting" }
{ "body": "This PR fixes #32117 issue\r\n\r\nAlso this issue is actual on 6.x and 8.x vesions", "number": 32134, "review_comments": [ { "body": "invalid syntax", "created_at": "2020-03-27T19:12:20Z" }, { "body": "invalid syntax", "created_at": "2020-03-27T19:12:27Z" } ], "title": "[7.x] Fix array eloquent casting" }
{ "commits": [ { "message": "Fix array casting (https://github.com/laravel/framework/issues/32117)\nAdd invalid json casting test\nFix string casting test" }, { "message": "Fix styles" }, { "message": "Fix styles" }, { "message": "Fix styles" }, { "message": "Docblock syntax fix" }, { "message": "Fix docblock. Remove space" } ], "files": [ { "diff": "@@ -14,6 +14,7 @@\n use Illuminate\\Support\\Facades\\Date;\n use Illuminate\\Support\\Str;\n use LogicException;\n+use stdClass;\n \n trait HasAttributes\n {\n@@ -523,8 +524,9 @@ protected function castAttribute($key, $value)\n case 'boolean':\n return (bool) $value;\n case 'object':\n- return $this->fromJson($value, true);\n+ return $this->fromObjectJson($value);\n case 'array':\n+ return $this->fromArrayJson($value);\n case 'json':\n return $this->fromJson($value);\n case 'collection':\n@@ -798,7 +800,7 @@ protected function asJson($value)\n }\n \n /**\n- * Decode the given JSON back into an array or object.\n+ * Decode the given JSON back.\n *\n * @param string $value\n * @param bool $asObject\n@@ -809,6 +811,32 @@ public function fromJson($value, $asObject = false)\n return json_decode($value, ! $asObject);\n }\n \n+ /**\n+ * Decode the given JSON into an array.\n+ *\n+ * @param string $value\n+ * @return array\n+ */\n+ protected function fromArrayJson($value)\n+ {\n+ $decoded = $this->fromJson($value, false);\n+\n+ return is_array($decoded) ? $decoded : [];\n+ }\n+\n+ /**\n+ * Decode the given JSON into an object.\n+ *\n+ * @param string $value\n+ * @return object\n+ */\n+ protected function fromObjectJson($value)\n+ {\n+ $decoded = $this->fromJson($value, true);\n+\n+ return is_object($decoded) ? $decoded : new stdClass;\n+ }\n+\n /**\n * Decode the given float.\n *", "filename": "src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php", "status": "modified" }, { "diff": "@@ -0,0 +1,141 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database;\n+\n+use Illuminate\\Database\\Capsule\\Manager as DB;\n+use Illuminate\\Database\\Eloquent\\Model as Eloquent;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use PHPUnit\\Framework\\TestCase;\n+use stdClass;\n+\n+class EloquentModelInvalidJsonCastingTest extends TestCase\n+{\n+ protected function setUp(): void\n+ {\n+ $db = new DB;\n+\n+ $db->addConnection([\n+ 'driver' => 'sqlite',\n+ 'database' => ':memory:',\n+ ]);\n+\n+ $db->bootEloquent();\n+ $db->setAsGlobal();\n+\n+ $this->createSchema();\n+ }\n+\n+ /**\n+ * Setup the database schema.\n+ *\n+ * @return void\n+ */\n+ public function createSchema()\n+ {\n+ $this->schema()->create('casting_table', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('array_attribute');\n+ $table->string('object_attribute');\n+ $table->string('json_attribute');\n+ $table->timestamps();\n+ });\n+ }\n+\n+ /**\n+ * Tests...\n+ */\n+ public function testStringJson()\n+ {\n+ $this->connection()->insert(\n+ 'insert into casting_table (id, array_attribute, object_attribute, json_attribute) values (?, ?, ?, ?)',\n+ [1, '\"valid-json-string\"', '\"valid-json-string\"', '\"valid-json-string\"']\n+ );\n+\n+ $model = InvalidJsonCasts::find(1);\n+\n+ $this->assertSame([], $model->getOriginal('array_attribute'));\n+ $this->assertSame([], $model->getAttribute('array_attribute'));\n+\n+ $stdClass = new stdClass;\n+ $this->assertEquals($stdClass, $model->getOriginal('object_attribute'));\n+ $this->assertEquals($stdClass, $model->getAttribute('object_attribute'));\n+\n+ $this->assertSame('valid-json-string', $model->getOriginal('json_attribute'));\n+ $this->assertSame('valid-json-string', $model->getAttribute('json_attribute'));\n+ }\n+\n+ public function testInvalidJson()\n+ {\n+ $this->connection()->insert(\n+ 'insert into casting_table (id, array_attribute, object_attribute, json_attribute) values (?, ?, ?, ?)',\n+ [1, 'invalid json', 'invalid json', 'invalid json']\n+ );\n+\n+ $model = InvalidJsonCasts::find(1);\n+\n+ $this->assertSame([], $model->getOriginal('array_attribute'));\n+ $this->assertSame([], $model->getAttribute('array_attribute'));\n+\n+ $stdClass = new stdClass;\n+ $this->assertEquals($stdClass, $model->getOriginal('object_attribute'));\n+ $this->assertEquals($stdClass, $model->getAttribute('object_attribute'));\n+\n+ $this->assertNull($model->getOriginal('json_attribute'));\n+ $this->assertNull($model->getAttribute('json_attribute'));\n+ }\n+\n+ /**\n+ * Tear down the database schema.\n+ *\n+ * @return void\n+ */\n+ protected function tearDown(): void\n+ {\n+ $this->schema()->drop('casting_table');\n+ }\n+\n+ /**\n+ * Get a database connection instance.\n+ *\n+ * @return \\Illuminate\\Database\\Connection\n+ */\n+ protected function connection()\n+ {\n+ return Eloquent::getConnectionResolver()->connection();\n+ }\n+\n+ /**\n+ * Get a schema builder instance.\n+ *\n+ * @return \\Illuminate\\Database\\Schema\\Builder\n+ */\n+ protected function schema()\n+ {\n+ return $this->connection()->getSchemaBuilder();\n+ }\n+}\n+\n+/**\n+ * Eloquent Models...\n+ */\n+class InvalidJsonCasts extends Eloquent\n+{\n+ /**\n+ * @var string\n+ */\n+ protected $table = 'casting_table';\n+\n+ /**\n+ * @var array\n+ */\n+ protected $guarded = [];\n+\n+ /**\n+ * @var array\n+ */\n+ protected $casts = [\n+ 'array_attribute' => 'array',\n+ 'object_attribute' => 'object',\n+ 'json_attribute' => 'json',\n+ ];\n+}", "filename": "tests/Integration/Database/EloquentModelInvalidJsonCastingTest.php", "status": "added" }, { "diff": "@@ -91,8 +91,9 @@ public function testSavingCastedEmptyAttributesToDatabase()\n $this->assertSame([], $model->getOriginal('json_attributes'));\n $this->assertSame([], $model->getAttribute('json_attributes'));\n \n- $this->assertSame([], $model->getOriginal('object_attributes'));\n- $this->assertSame([], $model->getAttribute('object_attributes'));\n+ $stdClass = new stdClass;\n+ $this->assertEquals($stdClass, $model->getOriginal('object_attributes'));\n+ $this->assertEquals($stdClass, $model->getAttribute('object_attributes'));\n }\n \n /**", "filename": "tests/Integration/Database/EloquentModelStringCastingTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 7.1.0\r\n- PHP Version: 7.4.3\r\n- Database Driver & Version: irrelevant\r\n\r\n### Description:\r\nI have a use case where I need to query an endpoint with multiple occurrences of the same query parameter. Guzzle supports this just fine if the query parameters are passed in the URL. Laravel's HTTP client, however, always extracts the query parameters from the URL and then passes them to Guzzle as an array. This results in the last occurrence overwriting all prior occurrences.\r\n\r\nThe endpoint in question is a Lucene/Solr instance that allows the [`fq` query parameter](https://lucene.apache.org/solr/guide/8_4/common-query-parameters.html#fq-filter-query-parameter) to be specified multiple times. As far as I'm aware there's no standard regarding these query parameters so this should be a valid use case.\r\n\r\nUnfortunately there's no way around this problem. Even with the bracket syntax (to indicate a query parameter with multiple values) Guzzle then turns it into a URL that is not supported by Solr.\r\n\r\n### Steps To Reproduce:\r\nMake a request to an endpoint with multiple occurrences of the same query parameter and you'll see the last occurrence overwrites all previous ones:\r\n```php\r\nHttp::get('https://example.com/?fq=hello&fq=world');\r\n// actual request goes to https://example.com/?fq=world\r\n```\r\n", "comments": [ { "body": "I dont really know how you will deal with array keys not overriding each other, but for this problem you could try using `fq=+hello +world`.", "created_at": "2020-03-12T05:43:16Z" }, { "body": "> I dont really know how you will deal with array keys not overriding each other, but for this problem you could try using `fq=+hello +world`.\r\n\r\nI simplified the example in my first post. My actual use case is a bit more complicated and your suggestion – unfortunately – won't work for me.", "created_at": "2020-03-12T12:45:51Z" }, { "body": "This was fixed I think in the latest release: https://github.com/laravel/framework/pull/31858\r\n\r\nCan you try with the very latest patch version?", "created_at": "2020-03-16T15:27:29Z" }, { "body": "Thanks for responding @driesvints, but unfortunately that fix is unrelated. My use case is impossible with the current implementation, because `PendingRequest` calls `parseQueryParams()`. It then sets the 'query' option on the Guzzle request, which results in Guzzle ignoring any query parameters in the URL.\r\n\r\nA fix would be to remove the call to `parseQueryParams()` entirely, but I'm not sure how breaking that would be.", "created_at": "2020-03-16T15:51:34Z" }, { "body": "Would appreciate a Pr if you could send one in. Thanks!", "created_at": "2020-03-16T15:59:24Z" }, { "body": "Fixed and will be in today's release.", "created_at": "2020-03-17T14:09:38Z" } ], "number": 31918, "title": "HTTP client overrides multiple occurrences of same query parameter" }
{ "body": "This allows multiple query parameters with the same name to be used (see #31918 for a use case). This is currently only possible by specifying the query parameters in the URL, rather than using the query option. If the consumer does not provide query parameters via the options, it assumed there are no additional query parameters to be passed to Guzzle.\r\n\r\nShould tests be required for this, I'd appreciate if someone could help me out. I haven't yet been able to add a working test case, due to the strange inner workings of Guzzle and its PSR7 response object.\r\n\r\nFixes #31918", "number": 31990, "review_comments": [], "title": "[7.x] Only define the query option when query parameters were specified" }
{ "commits": [ { "message": "Only define the query option when query parameters were specified\n\nThis allows multiple query parameters with the same name to be used. This is currently only possible by specifying the query parameters in the URL, rather than using the query option. If the consumer does not provide query parameters via the options, it assumed there are no additional query parameters to be passed to Guzzle." } ], "files": [ { "diff": "@@ -462,13 +462,18 @@ public function send(string $method, string $url, array $options = [])\n );\n }\n \n+ if (! empty($options['query'])) {\n+ $options['query'] = array_merge_recursive(\n+ $options['query'], $this->parseQueryParams($url)\n+ );\n+ }\n+\n $this->pendingFiles = [];\n \n return retry($this->tries ?? 1, function () use ($method, $url, $options) {\n try {\n return tap(new Response($this->buildClient()->request($method, $url, $this->mergeOptions([\n 'laravel_data' => $options[$this->bodyFormat] ?? [],\n- 'query' => $this->parseQueryParams($url),\n 'on_stats' => function ($transferStats) {\n $this->transferStats = $transferStats;\n },", "filename": "src/Illuminate/Http/Client/PendingRequest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.16.0\r\n- PHP Version: 7.2.17\r\n- Database Driver & Version: MySQL 8.0.16\r\n\r\n### Description:\r\nThe SQL statement is built incorrectly when a point column should be added with a SRID and after another column.\r\n\r\nActual SQL:\r\n``alter table `test` add `location` point not null after `id` srid 4326;``\r\nCorrect SQL:\r\n``alter table `test` add `location` point not null srid 4326 after `id`;``\r\n\r\nThe error message:\r\n> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'srid 4326' at line 1 (SQL: alter table `test` add `location` point not null after `id` srid 4326)\r\n\r\n\r\n### Steps To Reproduce:\r\n```\r\nSchema::create('test', function (Blueprint $table) {\r\n $table->bigIncrements('id');\r\n});\r\n \r\nSchema::table('test', function (Blueprint $table) {\r\n $table->point('location', 4326)->after('id');\r\n});", "comments": [ { "body": "This indeed seems problematic. I'm not sure if this is related to DBAL or to our own Schema. Appreciating help with figuring this out.", "created_at": "2020-02-20T12:04:17Z" } ], "number": 31543, "title": "Migration fails when point column gets a SRID and \"after\" is used" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nAs described in #31543 if a migration add a column of type `POINT` using the SRID parameter and also uses the `after` modifier, the generated SQL is invalid.\r\n\r\nSteps to reproduce:\r\n\r\n~~~php\r\nSchema::create('test', function (Blueprint $table) {\r\n $table->bigIncrements('id');\r\n});\r\n \r\nSchema::table('test', function (Blueprint $table) {\r\n $table->point('location', 4326)->after('id');\r\n});\r\n~~~\r\n\r\nExpected SQL:\r\n\r\n~~~sql\r\nalter table `test` add `location` point not null srid 4326 after `id`;\r\n~~~\r\n\r\nActual SQL:\r\n\r\n~~~sql\r\nalter table `test` add `location` point not null after `id` srid 4326;\r\n~~~\r\n\r\nWhen adding modifiers, the `Grammar` base class iterates over the `$modifiers` array and processes them in ~other~ order:\r\n\r\nhttps://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Schema/Grammars/Grammar.php#L144-L161\r\n\r\nThis PR, moves the `'Srid'` modifier sooner in the `MySqlGrammar`'s `$modifier` array, so it is processed before the relevant modifiers.\r\n\r\nI added two tests: \r\n\r\n- one to check syntax using the SRID without the `after` modifier\r\n- one to check syntax using the SRID with the `after` modifier\r\n\r\nThis a submission of PR #31851 to the 6.x branch", "number": 31852, "review_comments": [], "title": "[6.x] Fix mysql schema for srid (point)" }
{ "commits": [ { "message": "fix srid mysql schema" } ], "files": [ { "diff": "@@ -16,7 +16,7 @@ class MySqlGrammar extends Grammar\n */\n protected $modifiers = [\n 'Unsigned', 'Charset', 'Collate', 'VirtualAs', 'StoredAs', 'Nullable',\n- 'Default', 'Increment', 'Comment', 'After', 'First', 'Srid',\n+ 'Srid', 'Default', 'Increment', 'Comment', 'After', 'First',\n ];\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php", "status": "modified" }, { "diff": "@@ -898,6 +898,26 @@ public function testAddingPoint()\n $this->assertSame('alter table `geo` add `coordinates` point not null', $statements[0]);\n }\n \n+ public function testAddingPointWithSrid()\n+ {\n+ $blueprint = new Blueprint('geo');\n+ $blueprint->point('coordinates', 4326);\n+ $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame('alter table `geo` add `coordinates` point not null srid 4326', $statements[0]);\n+ }\n+\n+ public function testAddingPointWithSridColumn()\n+ {\n+ $blueprint = new Blueprint('geo');\n+ $blueprint->point('coordinates', 4326)->after('id');\n+ $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame('alter table `geo` add `coordinates` point not null srid 4326 after `id`', $statements[0]);\n+ }\n+\n public function testAddingLineString()\n {\n $blueprint = new Blueprint('geo');", "filename": "tests/Database/DatabaseMySqlSchemaGrammarTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.16.0\r\n- PHP Version: 7.2.17\r\n- Database Driver & Version: MySQL 8.0.16\r\n\r\n### Description:\r\nThe SQL statement is built incorrectly when a point column should be added with a SRID and after another column.\r\n\r\nActual SQL:\r\n``alter table `test` add `location` point not null after `id` srid 4326;``\r\nCorrect SQL:\r\n``alter table `test` add `location` point not null srid 4326 after `id`;``\r\n\r\nThe error message:\r\n> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'srid 4326' at line 1 (SQL: alter table `test` add `location` point not null after `id` srid 4326)\r\n\r\n\r\n### Steps To Reproduce:\r\n```\r\nSchema::create('test', function (Blueprint $table) {\r\n $table->bigIncrements('id');\r\n});\r\n \r\nSchema::table('test', function (Blueprint $table) {\r\n $table->point('location', 4326)->after('id');\r\n});", "comments": [ { "body": "This indeed seems problematic. I'm not sure if this is related to DBAL or to our own Schema. Appreciating help with figuring this out.", "created_at": "2020-02-20T12:04:17Z" } ], "number": 31543, "title": "Migration fails when point column gets a SRID and \"after\" is used" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nAs described in #31543 if a migration add a column of type `POINT` using the SRID parameter and also uses the `after` modifier, the generated SQL is invalid.\r\n\r\nSteps to reproduce:\r\n\r\n~~~php\r\nSchema::create('test', function (Blueprint $table) {\r\n $table->bigIncrements('id');\r\n});\r\n \r\nSchema::table('test', function (Blueprint $table) {\r\n $table->point('location', 4326)->after('id');\r\n});\r\n~~~\r\n\r\nExpected SQL:\r\n\r\n~~~sql\r\nalter table `test` add `location` point not null srid 4326 after `id`;\r\n~~~\r\n\r\nActual SQL:\r\n\r\n~~~sql\r\nalter table `test` add `location` point not null after `id` srid 4326;\r\n~~~\r\n\r\nWhen adding modifiers, the `Grammar` base class iterates over the `$modifiers` array and processes them in other:\r\n\r\nhttps://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Schema/Grammars/Grammar.php#L144-L161\r\n\r\nThis PR, moves the `'Srid'` modifier sooner in the `MySqlGrammar`'s `$modifier` array, so it is processed before the relevant modifiers.\r\n\r\nI added two tests: \r\n\r\n- one to check syntax using the SRID without the `after` modifier\r\n- one to check syntax using the SRID with the `after` modifier\r\n\r\nAs this is a bugfix and version 6.x is LTS I will send another PR to the 6.x branch", "number": 31851, "review_comments": [], "title": "[7.x] fix mysql schema for srid (point)" }
{ "commits": [ { "message": "fix srid mysql schema" } ], "files": [ { "diff": "@@ -16,7 +16,7 @@ class MySqlGrammar extends Grammar\n */\n protected $modifiers = [\n 'Unsigned', 'Charset', 'Collate', 'VirtualAs', 'StoredAs', 'Nullable',\n- 'Default', 'Increment', 'Comment', 'After', 'First', 'Srid',\n+ 'Srid', 'Default', 'Increment', 'Comment', 'After', 'First',\n ];\n \n /**", "filename": "src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php", "status": "modified" }, { "diff": "@@ -940,6 +940,26 @@ public function testAddingPoint()\n $this->assertSame('alter table `geo` add `coordinates` point not null', $statements[0]);\n }\n \n+ public function testAddingPointWithSrid()\n+ {\n+ $blueprint = new Blueprint('geo');\n+ $blueprint->point('coordinates', 4326);\n+ $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame('alter table `geo` add `coordinates` point not null srid 4326', $statements[0]);\n+ }\n+\n+ public function testAddingPointWithSridColumn()\n+ {\n+ $blueprint = new Blueprint('geo');\n+ $blueprint->point('coordinates', 4326)->after('id');\n+ $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());\n+\n+ $this->assertCount(1, $statements);\n+ $this->assertSame('alter table `geo` add `coordinates` point not null srid 4326 after `id`', $statements[0]);\n+ }\n+\n public function testAddingLineString()\n {\n $blueprint = new Blueprint('geo');", "filename": "tests/Database/DatabaseMySqlSchemaGrammarTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: Any, but tested on 6.x\r\n- PHP Version: any\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n\r\nWhen calling `isset($collection['key'])` I believe the expected behaviour should be the same as that for `isset($array['key'])`. That is, **if the value is null**, `isset` should return `false`. Currently, it returns `true`.\r\n\r\nThis happens because the `offsetExists` implementation on `Collection` uses `array_key_exists` rather than `isset()` (and `isset` itself relies on `offsetExists` for objects that implement `ArrayAccess`).\r\n\r\n**Note:** I only noticed this once on PHP 7.4, which emits a notice when you try to use array access on a non-array value (in this case null).\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$arr = ['a' => null];\r\n$coll = new Illuminate\\Support\\Collection($arr);\r\n\r\ndd(isset($arr['a']), isset($coll['a']));\r\n\r\n// false\r\n// true\r\n```\r\n\r\nThis eval reproduces the behaviour in a minimal environment:\r\n\r\nhttps://3v4l.org/7Um54\r\n\r\n### Additional Notes\r\n\r\nIf the current behaviour is the expected behaviour, we should document this.\r\n\r\nI created this as a bug report first just to make sure that we do in fact want this behaviour to match the regular array behaviour, as this would technically be a **breaking change**. I am happy to submit a PR to fix this once confirmed as a bug, or submit a PR to the docs if it is deemed behaviour as intended.", "comments": [ { "body": "I'd agree that this is a bug. `isset` is meant to return `false` when something \"is set\" but \"is null\".", "created_at": "2020-03-06T12:17:59Z" }, { "body": "Worth to mention that `array_key_exist` is deprecated: https://www.php.net/manual/en/migration74.deprecated.php", "created_at": "2020-03-06T12:19:23Z" }, { "body": "@nunomaduro Not it's not. It's only deprecated on objects. @phroggyy was talking about how that function behaves on the array inside the laravel collection.", "created_at": "2020-03-06T12:20:49Z" }, { "body": "As it seems to be agreed this is a bug, I will submit a PR for this later this afternoon.", "created_at": "2020-03-06T12:23:11Z" }, { "body": "This will be fixed in Laravel 8", "created_at": "2020-04-20T15:11:18Z" } ], "number": 31793, "title": "isset called on a collection where the value is null returns true" }
{ "body": "**I'm reopening this for 7.x for the reason expressed in** https://github.com/laravel/framework/pull/31799#issuecomment-595775191.\r\n\r\nThis PR changes the behaviour of `offsetExists` to be compatible with `isset` (which relies on `offsetExists` for objects implementing `ArrayAccess`). This PR maintains the current behaviour for all other collection functions that previously internally relied on `offsetExists`, replacing it instead with `array_key_exists`.\r\n\r\nResolves #31793 \r\n\r\n@taylorotwell if you disagree with it, I'm happy to target master.", "number": 31800, "review_comments": [], "title": "[8.x] Make offsetExists behave correctly for isset on Collection" }
{ "commits": [ { "message": "Make offsetExists behave correctly for isset on Collection" } ], "files": [ { "diff": "@@ -144,6 +144,10 @@ public static function except($array, $keys)\n */\n public static function exists($array, $key)\n {\n+ if ($array instanceof Enumerable) {\n+ return $array->has($key);\n+ }\n+\n if ($array instanceof ArrayAccess) {\n return $array->offsetExists($key);\n }", "filename": "src/Illuminate/Support/Arr.php", "status": "modified" }, { "diff": "@@ -412,7 +412,7 @@ public function forget($keys)\n */\n public function get($key, $default = null)\n {\n- if ($this->offsetExists($key)) {\n+ if (array_key_exists($key, $this->items)) {\n return $this->items[$key];\n }\n \n@@ -501,7 +501,7 @@ public function has($key)\n $keys = is_array($key) ? $key : func_get_args();\n \n foreach ($keys as $value) {\n- if (! $this->offsetExists($value)) {\n+ if (! array_key_exists($value, $this->items)) {\n return false;\n }\n }\n@@ -1293,7 +1293,7 @@ public function toBase()\n */\n public function offsetExists($key)\n {\n- return array_key_exists($key, $this->items);\n+ return isset($this->items[$key]);\n }\n \n /**", "filename": "src/Illuminate/Support/Collection.php", "status": "modified" }, { "diff": "@@ -327,10 +327,31 @@ public function testOffsetAccess()\n \n public function testArrayAccessOffsetExists()\n {\n- $c = new Collection(['foo', 'bar']);\n+ $c = new Collection(['foo', 'bar', null]);\n $this->assertTrue($c->offsetExists(0));\n $this->assertTrue($c->offsetExists(1));\n- $this->assertFalse($c->offsetExists(1000));\n+ $this->assertFalse($c->offsetExists(2));\n+ }\n+\n+ public function testBehavesLikeAnArrayWithArrayAccess()\n+ {\n+ // indexed array\n+ $input = ['foo', null];\n+ $c = new Collection($input);\n+ $this->assertEquals(isset($input[0]), isset($c[0])); // existing value\n+ $this->assertEquals(isset($input[1]), isset($c[1])); // existing but null value\n+ $this->assertEquals(isset($input[1000]), isset($c[1000])); // non-existing value\n+ $this->assertEquals($input[0], $c[0]);\n+ $this->assertEquals($input[1], $c[1]);\n+\n+ // associative array\n+ $input = ['k1' => 'foo', 'k2' => null];\n+ $c = new Collection($input);\n+ $this->assertEquals(isset($input['k1']), isset($c['k1'])); // existing value\n+ $this->assertEquals(isset($input['k2']), isset($c['k2'])); // existing but null value\n+ $this->assertEquals(isset($input['k3']), isset($c['k3'])); // non-existing value\n+ $this->assertEquals($input['k1'], $c['k1']);\n+ $this->assertEquals($input['k2'], $c['k2']);\n }\n \n public function testArrayAccessOffsetGet()", "filename": "tests/Support/SupportCollectionTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: Any, but tested on 6.x\r\n- PHP Version: any\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n\r\nWhen calling `isset($collection['key'])` I believe the expected behaviour should be the same as that for `isset($array['key'])`. That is, **if the value is null**, `isset` should return `false`. Currently, it returns `true`.\r\n\r\nThis happens because the `offsetExists` implementation on `Collection` uses `array_key_exists` rather than `isset()` (and `isset` itself relies on `offsetExists` for objects that implement `ArrayAccess`).\r\n\r\n**Note:** I only noticed this once on PHP 7.4, which emits a notice when you try to use array access on a non-array value (in this case null).\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$arr = ['a' => null];\r\n$coll = new Illuminate\\Support\\Collection($arr);\r\n\r\ndd(isset($arr['a']), isset($coll['a']));\r\n\r\n// false\r\n// true\r\n```\r\n\r\nThis eval reproduces the behaviour in a minimal environment:\r\n\r\nhttps://3v4l.org/7Um54\r\n\r\n### Additional Notes\r\n\r\nIf the current behaviour is the expected behaviour, we should document this.\r\n\r\nI created this as a bug report first just to make sure that we do in fact want this behaviour to match the regular array behaviour, as this would technically be a **breaking change**. I am happy to submit a PR to fix this once confirmed as a bug, or submit a PR to the docs if it is deemed behaviour as intended.", "comments": [ { "body": "I'd agree that this is a bug. `isset` is meant to return `false` when something \"is set\" but \"is null\".", "created_at": "2020-03-06T12:17:59Z" }, { "body": "Worth to mention that `array_key_exist` is deprecated: https://www.php.net/manual/en/migration74.deprecated.php", "created_at": "2020-03-06T12:19:23Z" }, { "body": "@nunomaduro Not it's not. It's only deprecated on objects. @phroggyy was talking about how that function behaves on the array inside the laravel collection.", "created_at": "2020-03-06T12:20:49Z" }, { "body": "As it seems to be agreed this is a bug, I will submit a PR for this later this afternoon.", "created_at": "2020-03-06T12:23:11Z" }, { "body": "This will be fixed in Laravel 8", "created_at": "2020-04-20T15:11:18Z" } ], "number": 31793, "title": "isset called on a collection where the value is null returns true" }
{ "body": "This PR changes the behaviour of `offsetExists` to be compatible with `isset` (which relies on `offsetExists` for objects implementing `ArrayAccess`). This PR maintains the current behaviour for all other collection functions that previously internally relied on `offsetExists`, replacing it instead with `array_key_exists`.\r\n\r\nResolves #31793 ", "number": 31799, "review_comments": [], "title": "[6.x] Make offsetExists behave correctly for isset on Collection" }
{ "commits": [ { "message": "Make offsetExists behave correctly for isset on Collection" } ], "files": [ { "diff": "@@ -144,6 +144,10 @@ public static function except($array, $keys)\n */\n public static function exists($array, $key)\n {\n+ if ($array instanceof Enumerable) {\n+ return $array->has($key);\n+ }\n+\n if ($array instanceof ArrayAccess) {\n return $array->offsetExists($key);\n }", "filename": "src/Illuminate/Support/Arr.php", "status": "modified" }, { "diff": "@@ -412,7 +412,7 @@ public function forget($keys)\n */\n public function get($key, $default = null)\n {\n- if ($this->offsetExists($key)) {\n+ if (array_key_exists($key, $this->items)) {\n return $this->items[$key];\n }\n \n@@ -501,7 +501,7 @@ public function has($key)\n $keys = is_array($key) ? $key : func_get_args();\n \n foreach ($keys as $value) {\n- if (! $this->offsetExists($value)) {\n+ if (! array_key_exists($value, $this->items)) {\n return false;\n }\n }\n@@ -1276,7 +1276,7 @@ public function toBase()\n */\n public function offsetExists($key)\n {\n- return array_key_exists($key, $this->items);\n+ return isset($this->items[$key]);\n }\n \n /**", "filename": "src/Illuminate/Support/Collection.php", "status": "modified" }, { "diff": "@@ -327,10 +327,31 @@ public function testOffsetAccess()\n \n public function testArrayAccessOffsetExists()\n {\n- $c = new Collection(['foo', 'bar']);\n+ $c = new Collection(['foo', 'bar', null]);\n $this->assertTrue($c->offsetExists(0));\n $this->assertTrue($c->offsetExists(1));\n- $this->assertFalse($c->offsetExists(1000));\n+ $this->assertFalse($c->offsetExists(2));\n+ }\n+\n+ public function testBehavesLikeAnArrayWithArrayAccess()\n+ {\n+ // indexed array\n+ $input = ['foo', null];\n+ $c = new Collection($input);\n+ $this->assertEquals(isset($input[0]), isset($c[0])); // existing value\n+ $this->assertEquals(isset($input[1]), isset($c[1])); // existing but null value\n+ $this->assertEquals(isset($input[1000]), isset($c[1000])); // non-existing value\n+ $this->assertEquals($input[0], $c[0]);\n+ $this->assertEquals($input[1], $c[1]);\n+\n+ // associative array\n+ $input = ['k1' => 'foo', 'k2' => null];\n+ $c = new Collection($input);\n+ $this->assertEquals(isset($input['k1']), isset($c['k1'])); // existing value\n+ $this->assertEquals(isset($input['k2']), isset($c['k2'])); // existing but null value\n+ $this->assertEquals(isset($input['k3']), isset($c['k3'])); // non-existing value\n+ $this->assertEquals($input['k1'], $c['k1']);\n+ $this->assertEquals($input['k2'], $c['k2']);\n }\n \n public function testArrayAccessOffsetGet()", "filename": "tests/Support/SupportCollectionTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: Any, but tested on 6.x\r\n- PHP Version: any\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n\r\nWhen calling `isset($collection['key'])` I believe the expected behaviour should be the same as that for `isset($array['key'])`. That is, **if the value is null**, `isset` should return `false`. Currently, it returns `true`.\r\n\r\nThis happens because the `offsetExists` implementation on `Collection` uses `array_key_exists` rather than `isset()` (and `isset` itself relies on `offsetExists` for objects that implement `ArrayAccess`).\r\n\r\n**Note:** I only noticed this once on PHP 7.4, which emits a notice when you try to use array access on a non-array value (in this case null).\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$arr = ['a' => null];\r\n$coll = new Illuminate\\Support\\Collection($arr);\r\n\r\ndd(isset($arr['a']), isset($coll['a']));\r\n\r\n// false\r\n// true\r\n```\r\n\r\nThis eval reproduces the behaviour in a minimal environment:\r\n\r\nhttps://3v4l.org/7Um54\r\n\r\n### Additional Notes\r\n\r\nIf the current behaviour is the expected behaviour, we should document this.\r\n\r\nI created this as a bug report first just to make sure that we do in fact want this behaviour to match the regular array behaviour, as this would technically be a **breaking change**. I am happy to submit a PR to fix this once confirmed as a bug, or submit a PR to the docs if it is deemed behaviour as intended.", "comments": [ { "body": "I'd agree that this is a bug. `isset` is meant to return `false` when something \"is set\" but \"is null\".", "created_at": "2020-03-06T12:17:59Z" }, { "body": "Worth to mention that `array_key_exist` is deprecated: https://www.php.net/manual/en/migration74.deprecated.php", "created_at": "2020-03-06T12:19:23Z" }, { "body": "@nunomaduro Not it's not. It's only deprecated on objects. @phroggyy was talking about how that function behaves on the array inside the laravel collection.", "created_at": "2020-03-06T12:20:49Z" }, { "body": "As it seems to be agreed this is a bug, I will submit a PR for this later this afternoon.", "created_at": "2020-03-06T12:23:11Z" }, { "body": "This will be fixed in Laravel 8", "created_at": "2020-04-20T15:11:18Z" } ], "number": 31793, "title": "isset called on a collection where the value is null returns true" }
{ "body": "This PR changes the behaviour of `offsetExists` to be compatible with `isset` (which relies on `offsetExists` for objects implementing `ArrayAccess`). This PR maintains the current behaviour for all other collection functions that previously internally relied on `offsetExists`, replacing it instead with `array_key_exists`.\r\n\r\nResolves #31793 ", "number": 31797, "review_comments": [], "title": "Make offsetExists behave correctly for isset on Collection" }
{ "commits": [ { "message": "Make offsetExists behave correctly for isset on Collection" } ], "files": [ { "diff": "@@ -412,7 +412,7 @@ public function forget($keys)\n */\n public function get($key, $default = null)\n {\n- if ($this->offsetExists($key)) {\n+ if (array_key_exists($key, $this->items)) {\n return $this->items[$key];\n }\n \n@@ -501,7 +501,7 @@ public function has($key)\n $keys = is_array($key) ? $key : func_get_args();\n \n foreach ($keys as $value) {\n- if (! $this->offsetExists($value)) {\n+ if (! array_key_exists($value, $this->items)) {\n return false;\n }\n }\n@@ -1293,7 +1293,7 @@ public function toBase()\n */\n public function offsetExists($key)\n {\n- return array_key_exists($key, $this->items);\n+ return isset($this->items[$key]);\n }\n \n /**", "filename": "src/Illuminate/Support/Collection.php", "status": "modified" }, { "diff": "@@ -327,10 +327,31 @@ public function testOffsetAccess()\n \n public function testArrayAccessOffsetExists()\n {\n- $c = new Collection(['foo', 'bar']);\n+ $c = new Collection(['foo', 'bar', null]);\n $this->assertTrue($c->offsetExists(0));\n $this->assertTrue($c->offsetExists(1));\n- $this->assertFalse($c->offsetExists(1000));\n+ $this->assertFalse($c->offsetExists(2));\n+ }\n+\n+ public function testBehavesLikeAnArrayWithArrayAccess()\n+ {\n+ // indexed array\n+ $input = ['foo', null];\n+ $c = new Collection($input);\n+ $this->assertEquals(isset($input[0]), isset($c[0])); // existing value\n+ $this->assertEquals(isset($input[1]), isset($c[1])); // existing but null value\n+ $this->assertEquals(isset($input[1000]), isset($c[1000])); // non-existing value\n+ $this->assertEquals($input[0], $c[0]);\n+ $this->assertEquals($input[1], $c[1]);\n+\n+ // associative array\n+ $input = ['k1' => 'foo', 'k2' => null];\n+ $c = new Collection($input);\n+ $this->assertEquals(isset($input['k1']), isset($c['k1'])); // existing value\n+ $this->assertEquals(isset($input['k2']), isset($c['k2'])); // existing but null value\n+ $this->assertEquals(isset($input['k3']), isset($c['k3'])); // non-existing value\n+ $this->assertEquals($input['k1'], $c['k1']);\n+ $this->assertEquals($input['k2'], $c['k2']);\n }\n \n public function testArrayAccessOffsetGet()", "filename": "tests/Support/SupportCollectionTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.16.0\r\n- PHP Version: 7.4\r\n\r\n### Description:\r\n\r\nCurrently models get dirty (`isDirty() == true`) after both force-deletion and soft-deletion. \r\n\r\n#### Force-deletion\r\n\r\nCorrect behavior. After deletion, the model doesn't exist anymore: `$exists = false`. We cannot sync the latest attributes from database.\r\n\r\n#### Soft-deletion\r\n\r\nWrong behavior. After deletion, the model still exists: `$exists = true`. We should be able to retrieve the latest attributes or immediately restore the data. **Currently, immediate `restore()` call just after `delete()` has a broken behavior.** `SoftDeletes` should call `syncOriginal()` after UPDATE query execution.\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$softDeletable->delete();\r\n$softDeletable->restore(); // It does't execute any queries\r\n```\r\n\r\n```php\r\n$softDeletable->delete();\r\n$softDeletable->refresh();\r\n$softDeletable->restore(); // It works\r\n```\r\n", "comments": [ { "body": "I can reproduce this but unsure what's causing this. Tried to dive into the internals but it's not clear why the `deleted_at` column isn't cleared in the database when `restore` is called.", "created_at": "2020-02-20T13:06:40Z" }, { "body": "@driesvints \r\n\r\nWhen we soft-delete models:\r\n\r\n1. `Model::delete()`\r\n2. `SoftDeletes::runSoftDelete()`\r\n3. Model attributes have been set (`Model::isDirty()` returns true)\r\n4. `Builder::update()`\r\n5. **`Model::syncOriginal()` should be called here but we are missing it**\r\n\r\nWhen we restore models:\r\n\r\n```php\r\n /**\r\n * Restore a soft-deleted model instance.\r\n *\r\n * @return bool|null\r\n */\r\n public function restore()\r\n {\r\n /* ... */\r\n\r\n // This revert the model attribute changes\r\n // `Model::isDirty()` returns false!!!!!!\r\n $this->{$this->getDeletedAtColumn()} = null;\r\n\r\n /* ... */\r\n\r\n $result = $this->save();\r\n\r\n /* ... */\r\n }\r\n```\r\n\r\n```php\r\n /**\r\n * Save the model to the database.\r\n *\r\n * @param array $options\r\n * @return bool\r\n */\r\n public function save(array $options = [])\r\n {\r\n /* ... */\r\n\r\n if ($this->exists) {\r\n $saved = $this->isDirty() ?\r\n $this->performUpdate($query) : true; // Model::performUpdate() won't be fired\r\n }\r\n\r\n /* ... */\r\n }\r\n```", "created_at": "2020-02-20T14:14:53Z" }, { "body": "@taylorotwell closed the PR, so I'm bringing the question here. Should we sync the timestamps fields only? See https://github.com/laravel/framework/pull/31631#issuecomment-592534632", "created_at": "2020-02-29T14:06:20Z" }, { "body": "Currently I'm running into issue #31823, due to the changes proposed here.", "created_at": "2020-03-07T11:32:12Z" } ], "number": 31527, "title": "`SoftDeletes` should call `syncOriginal()` after UPDATE query execution" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\nRelates to #31527\r\n\r\nWhen we soft delete a model it becomes dirty, so if we try to restore it after deletion, the deleted_at column is not cleared. We need to sync the model, setting dirty to false, then the restore works.", "number": 31719, "review_comments": [ { "body": "Please remove this.", "created_at": "2020-03-03T23:39:53Z" } ], "title": "[6.x] Fix model restoring right after soft deleting it" }
{ "commits": [ { "message": "fix(eloquent) Fix model restoring after soft deleting it" }, { "message": "Code review - remove comments" } ], "files": [ { "diff": "@@ -92,6 +92,8 @@ protected function runSoftDelete()\n }\n \n $query->update($columns);\n+\n+ $this->syncOriginalAttributes(array_keys($columns));\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/SoftDeletes.php", "status": "modified" }, { "diff": "@@ -269,7 +269,6 @@ public function testUpdateModelAfterSoftDeleting()\n /** @var SoftDeletesTestUser $userModel */\n $userModel = SoftDeletesTestUser::find(2);\n $userModel->delete();\n- $userModel->syncOriginal();\n $this->assertEquals($now->toDateTimeString(), $userModel->getOriginal('deleted_at'));\n $this->assertNull(SoftDeletesTestUser::find(2));\n $this->assertEquals($userModel, SoftDeletesTestUser::withTrashed()->find(2));\n@@ -285,7 +284,6 @@ public function testRestoreAfterSoftDelete()\n /** @var SoftDeletesTestUser $userModel */\n $userModel = SoftDeletesTestUser::find(2);\n $userModel->delete();\n- $userModel->syncOriginal();\n $userModel->restore();\n \n $this->assertEquals($userModel->id, SoftDeletesTestUser::find(2)->id);\n@@ -304,12 +302,25 @@ public function testSoftDeleteAfterRestoring()\n $this->assertEquals($userModel->deleted_at, SoftDeletesTestUser::find(1)->deleted_at);\n $this->assertEquals($userModel->getOriginal('deleted_at'), SoftDeletesTestUser::find(1)->deleted_at);\n $userModel->delete();\n- $userModel->syncOriginal();\n $this->assertNull(SoftDeletesTestUser::find(1));\n $this->assertEquals($userModel->deleted_at, SoftDeletesTestUser::withTrashed()->find(1)->deleted_at);\n $this->assertEquals($userModel->getOriginal('deleted_at'), SoftDeletesTestUser::withTrashed()->find(1)->deleted_at);\n }\n \n+ public function testModifyingBeforeSoftDeletingAndRestoring()\n+ {\n+ $this->createUsers();\n+\n+ /** @var SoftDeletesTestUser $userModel */\n+ $userModel = SoftDeletesTestUser::find(2);\n+ $userModel->email = 'foo@bar.com';\n+ $userModel->delete();\n+ $userModel->restore();\n+\n+ $this->assertEquals($userModel->id, SoftDeletesTestUser::find(2)->id);\n+ $this->assertSame('foo@bar.com', SoftDeletesTestUser::find(2)->email);\n+ }\n+\n public function testUpdateOrCreate()\n {\n $this->createUsers();", "filename": "tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php", "status": "modified" }, { "diff": "@@ -24,6 +24,10 @@ public function testDeleteSetsSoftDeletedColumn()\n 'deleted_at' => 'date-time',\n 'updated_at' => 'date-time',\n ]);\n+ $model->shouldReceive('syncOriginalAttributes')->once()->with([\n+ 'deleted_at',\n+ 'updated_at',\n+ ]);\n $model->delete();\n \n $this->assertInstanceOf(Carbon::class, $model->deleted_at);", "filename": "tests/Database/DatabaseSoftDeletingTraitTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.16.0\r\n- PHP Version: 7.4\r\n\r\n### Description:\r\n\r\nCurrently models get dirty (`isDirty() == true`) after both force-deletion and soft-deletion. \r\n\r\n#### Force-deletion\r\n\r\nCorrect behavior. After deletion, the model doesn't exist anymore: `$exists = false`. We cannot sync the latest attributes from database.\r\n\r\n#### Soft-deletion\r\n\r\nWrong behavior. After deletion, the model still exists: `$exists = true`. We should be able to retrieve the latest attributes or immediately restore the data. **Currently, immediate `restore()` call just after `delete()` has a broken behavior.** `SoftDeletes` should call `syncOriginal()` after UPDATE query execution.\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$softDeletable->delete();\r\n$softDeletable->restore(); // It does't execute any queries\r\n```\r\n\r\n```php\r\n$softDeletable->delete();\r\n$softDeletable->refresh();\r\n$softDeletable->restore(); // It works\r\n```\r\n", "comments": [ { "body": "I can reproduce this but unsure what's causing this. Tried to dive into the internals but it's not clear why the `deleted_at` column isn't cleared in the database when `restore` is called.", "created_at": "2020-02-20T13:06:40Z" }, { "body": "@driesvints \r\n\r\nWhen we soft-delete models:\r\n\r\n1. `Model::delete()`\r\n2. `SoftDeletes::runSoftDelete()`\r\n3. Model attributes have been set (`Model::isDirty()` returns true)\r\n4. `Builder::update()`\r\n5. **`Model::syncOriginal()` should be called here but we are missing it**\r\n\r\nWhen we restore models:\r\n\r\n```php\r\n /**\r\n * Restore a soft-deleted model instance.\r\n *\r\n * @return bool|null\r\n */\r\n public function restore()\r\n {\r\n /* ... */\r\n\r\n // This revert the model attribute changes\r\n // `Model::isDirty()` returns false!!!!!!\r\n $this->{$this->getDeletedAtColumn()} = null;\r\n\r\n /* ... */\r\n\r\n $result = $this->save();\r\n\r\n /* ... */\r\n }\r\n```\r\n\r\n```php\r\n /**\r\n * Save the model to the database.\r\n *\r\n * @param array $options\r\n * @return bool\r\n */\r\n public function save(array $options = [])\r\n {\r\n /* ... */\r\n\r\n if ($this->exists) {\r\n $saved = $this->isDirty() ?\r\n $this->performUpdate($query) : true; // Model::performUpdate() won't be fired\r\n }\r\n\r\n /* ... */\r\n }\r\n```", "created_at": "2020-02-20T14:14:53Z" }, { "body": "@taylorotwell closed the PR, so I'm bringing the question here. Should we sync the timestamps fields only? See https://github.com/laravel/framework/pull/31631#issuecomment-592534632", "created_at": "2020-02-29T14:06:20Z" }, { "body": "Currently I'm running into issue #31823, due to the changes proposed here.", "created_at": "2020-03-07T11:32:12Z" } ], "number": 31527, "title": "`SoftDeletes` should call `syncOriginal()` after UPDATE query execution" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\nRelates to #31527\r\n\r\nWhen we soft delete a model it becomes dirty, so if we try to restore it after deletion, the deleted_at column is not cleared. We need to sync the model, setting dirty to false, then the restore works.\r\n\r\n\r\n", "number": 31631, "review_comments": [], "title": "[6.x] Fix model restoring right after soft deleting it" }
{ "commits": [ { "message": "Enable restoring the model right after deleting it" }, { "message": "Fixing failing tests" } ], "files": [ { "diff": "@@ -92,6 +92,8 @@ protected function runSoftDelete()\n }\n \n $query->update($columns);\n+\n+ $this->syncOriginal();\n }\n \n /**", "filename": "src/Illuminate/Database/Eloquent/SoftDeletes.php", "status": "modified" }, { "diff": "@@ -285,7 +285,6 @@ public function testRestoreAfterSoftDelete()\n /** @var SoftDeletesTestUser $userModel */\n $userModel = SoftDeletesTestUser::find(2);\n $userModel->delete();\n- $userModel->syncOriginal();\n $userModel->restore();\n \n $this->assertEquals($userModel->id, SoftDeletesTestUser::find(2)->id);", "filename": "tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php", "status": "modified" }, { "diff": "@@ -24,6 +24,7 @@ public function testDeleteSetsSoftDeletedColumn()\n 'deleted_at' => 'date-time',\n 'updated_at' => 'date-time',\n ]);\n+ $model->shouldReceive('syncOriginal')->once();\n $model->delete();\n \n $this->assertInstanceOf(Carbon::class, $model->deleted_at);", "filename": "tests/Database/DatabaseSoftDeletingTraitTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.15.1\r\n- PHP Version: 7.3.10\r\n- Database Driver & Version: SQLite 3.28.0\r\n\r\n### Description:\r\nAssume a custom `admin` guard operating on the `admins` table. When you write a test such as \r\n```\r\n$response = $this->actingAs($admin, 'admin')->get(route('test'));\r\n```\r\nand you obtain the user from the request object in your controller, for example\r\n```\r\nrequest()->user()\r\n```\r\nwithin the test, you will get your `$admin` back as expected. However, when you're running your application via the browser for example, you will receive `null` regardless that you have your `$admin` authenticated, unless the route explicitly uses the `auth:admin` middleware.\r\n\r\nFor that reason I believe that the `actingAs($user, $guard)` method within the test _assumes_ the `auth:{$guard}` middleware to be used when running the requests and that might lead to unexpected/ambiguous behaviour.\r\n\r\n> NOTE: I do understand that this happens because the guard not being specified results in using the fallback default and that is indeed the correct behaviour; what I'm trying to say is that the test behaviour is slightly different and it can potentially cause problems.\r\n\r\n### Steps To Reproduce:\r\n1) Clone the repository and install the dependencies\r\n```\r\ngit clone https://github.com/barnabaskecskes/laravel-custom-guard-test-authentication-issue\r\ncd laravel-custom-guard-test-authentication-issue\r\ncomposer install\r\n```\r\n2) Run [the test](https://github.com/barnabaskecskes/laravel-custom-guard-test-authentication-issue/blob/master/tests/Feature/LoggingInThroughTheAdminGuardTest.php#L13-L22) to see it returning the admin user\r\n```\r\nvendor/bin/phpunit --filter LoggingInThroughTheAdminGuardTest\r\n```\r\n3) Serve the app and see the different behaviour in the browser (check [the view](https://github.com/barnabaskecskes/laravel-custom-guard-test-authentication-issue/blob/master/resources/views/welcome.blade.php#L13-L30) and [the routes file](https://github.com/barnabaskecskes/laravel-custom-guard-test-authentication-issue/blob/master/routes/web.php#L7-L16) to see what you should expect)\r\n```\r\nphp artisan serve\r\n```", "comments": [ { "body": "@barnabaskecskes you're correct. I managed to reproduce this. Appreciating any help with looking into this.", "created_at": "2020-02-17T14:10:01Z" }, { "body": "@driesvints I know that if you take [this line](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php#L36) out, it follows the correct behaviour _in this instance_ but I did not have a chance to dig any deeper than that just yet. I'll try to find some time to dissect this a bit more.", "created_at": "2020-02-17T14:34:32Z" }, { "body": "@barnabaskecskes your solution from the pr might not be ideal but maybe we can solve this differently. I'll leave this open so it can be picked up eventually. Maybe someone has another idea.", "created_at": "2020-02-18T14:26:39Z" }, { "body": "@driesvints I appreciate that, thank you.\r\n\r\nI have saved that PR as a _Draft_ - wasn't even sure it was going to appear. All it said that I need to make it _Ready for review_ eventually - that didn't go down well. 😅 \r\n\r\nI'm having a bit of a question here on how to reliably test things without relying on arbitrary tests from another project? (see PR comments) If somebody knows a way, please ping me! ", "created_at": "2020-02-19T18:42:34Z" }, { "body": "I just realized that this indeed isn't a bug. You should indeed set the guard with your `auth` middleware because otherwise it'll pick the default guard. I'll make the docs more clear about this.", "created_at": "2020-04-23T13:11:44Z" }, { "body": "https://github.com/laravel/docs/pull/6007", "created_at": "2020-04-23T13:44:52Z" } ], "number": 31506, "title": "Ambiguous behaviour in tests when using the request user with custom guards" }
{ "body": "This pull request is meant to fix issue #31506 - although it seems pretty concerning to me that the solution was literally _taking a line out_. It feels that I'm missing something, although the tests do not point out any issues in particular.\r\n\r\nI've checked it in my only reference project where I'm using custom guard for admin authentication, and it causes quite some issues across the board, so some more digging is needed. For that reason, this PR stays a draft...", "number": 31511, "review_comments": [], "title": "[6.x] Fix implied middleware when using custom guards in tests (#31506)" }
{ "commits": [ { "message": "Fix implied middleware when using custom guards in tests (#31506)" } ], "files": [ { "diff": "@@ -33,8 +33,6 @@ public function be(UserContract $user, $driver = null)\n \n $this->app['auth']->guard($driver)->setUser($user);\n \n- $this->app['auth']->shouldUse($driver);\n-\n return $this;\n }\n ", "filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php", "status": "modified" }, { "diff": "@@ -22,6 +22,8 @@ protected function getEnvironmentSetUp($app)\n 'database' => ':memory:',\n 'prefix' => '',\n ]);\n+\n+ $app['config']->set('auth.guards.custom', $app['config']->get('auth.guards.web'));\n }\n \n protected function setUp(): void\n@@ -59,6 +61,25 @@ public function testActingAsIsProperlyHandledForSessionAuth()\n ->assertSeeText('Hello taylorotwell');\n }\n \n+ public function testActingAsDoesNotImplyAuthenticatedRouteWhenUsingACustomGuard()\n+ {\n+ Route::get('non-authenticated', function (Request $request) {\n+ return ['user' => $request->user()];\n+ });\n+\n+ Route::get('authenticated', function (Request $request) {\n+ return ['user' => $request->user()];\n+ })->middleware('auth:custom');\n+\n+ $user = AuthenticationTestUser::where('username', '=', 'taylorotwell')->first();\n+\n+ $nonImpliedResponse = $this->actingAs($user, 'custom')->get('/non-authenticated');\n+ $this->assertNull($nonImpliedResponse->json('user'));\n+\n+ $impliedResponse = $this->actingAs($user, 'custom')->get('/authenticated');\n+ $this->assertEquals('taylorotwell', $impliedResponse->json('user.username'));\n+ }\n+\n public function testActingAsIsProperlyHandledForAuthViaRequest()\n {\n Route::get('me', function (Request $request) {", "filename": "tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.11.0\r\n- PHP Version: 7.4\r\n- Database Driver & Version: n/a\r\n\r\n### Description:\r\n\r\nI have configured a cookie not to be encrypted in `App\\Http\\Middleware\\EncryptCookies` middleware. This cookie is used in another middleware, along with other (normally encrypted) cookies. \r\n\r\nWhen I'm testing the middleware, I can't access both types of cookies. Either I can access the unencrypted one (using `disableCookieEncryption`) or the encrypted one. \r\n\r\n### Steps To Reproduce:\r\nConfigure the cookie name `plain` not to be encrypted in `App\\Http\\Middleware\\EncryptCookies`:\r\n```php\r\nclass EncryptCookies extends BaseEncrypter\r\n{\r\n protected $except = [\r\n 'plain',\r\n ];\r\n}\r\n```\r\n\r\nWith this test I can only access `plain` cookie (`encrypted` is `null`):\r\n```php\r\npublic function testCanAccessCookies ()\r\n{\r\n $this->disableCookieEncryption()\r\n ->withCookie('plain', 'plain value')\r\n ->withCookie('encrypted', 'encrypted value')\r\n ->get('/');\r\n}\r\n```\r\n\r\nWith this test I can only access `encrypted` cookie (`plain` is the encrypted string value):\r\n```php\r\npublic function testCanAccessCookies ()\r\n{\r\n $this->withCookie('plain', 'plain value')\r\n ->withCookie('encrypted', 'encrypted value')\r\n ->get('/');\r\n}\r\n```", "comments": [ { "body": "You seem to be correct. The except property isn't taken into account when using this method.", "created_at": "2020-01-30T14:06:20Z" }, { "body": "@driesvints i want to help to solve this problem, so i create a PR about my solution. If there are some suggestions, that would be great.", "created_at": "2020-02-07T04:37:27Z" } ], "number": 31282, "title": "Testing with unencrypted cookies doesn't work" }
{ "body": "This PR provide a way to specify cookies will not be encrypted before sending with the request.\r\n\r\n```php\r\n$this->withCookie('bar', 'qux')\r\n ->withUnencryptedCookie('foo', 'bar')\r\n ->get('/');\r\n```\r\n\r\n```php\r\n$this->withCookies($cookies) // cookies will be encrypted\r\n ->withUnencryptedCookies($unencryptedCookies) // cookies will not be encrypted\r\n ->get('/');\r\n```\r\n\r\nFixes #31282", "number": 31390, "review_comments": [], "title": "[6.x] Fix testing with unencrypted cookies" }
{ "commits": [ { "message": "fix testing with unencrypted cookies" }, { "message": "remove extra blank line" }, { "message": "fix test failed" }, { "message": "make method unencryptedCookie to prevent making breaking change" } ], "files": [ { "diff": "@@ -25,6 +25,13 @@ trait MakesHttpRequests\n */\n protected $defaultCookies = [];\n \n+ /**\n+ * Additional cookies will not be encrypted for the request.\n+ *\n+ * @var array\n+ */\n+ protected $unencryptedCookies = [];\n+\n /**\n * Additional server variables for the request.\n *\n@@ -172,6 +179,33 @@ public function withCookie(string $name, string $value)\n return $this;\n }\n \n+ /**\n+ * Define additional cookies will not be encrypted before sending with the request.\n+ *\n+ * @param array $cookies\n+ * @return $this\n+ */\n+ public function withUnencryptedCookies(array $cookies)\n+ {\n+ $this->unencryptedCookies = array_merge($this->unencryptedCookies, $cookies);\n+\n+ return $this;\n+ }\n+\n+ /**\n+ * Add a cookie will not be encrypted before sending with the request.\n+ *\n+ * @param string $name\n+ * @param string $value\n+ * @return $this\n+ */\n+ public function withUnencryptedCookie(string $name, string $value)\n+ {\n+ $this->unencryptedCookies[$name] = $value;\n+\n+ return $this;\n+ }\n+\n /**\n * Automatically follow any redirects returned from the response.\n *\n@@ -527,12 +561,12 @@ protected function extractFilesFromDataArray(&$data)\n protected function prepareCookiesForRequest()\n {\n if (! $this->encryptCookies) {\n- return $this->defaultCookies;\n+ return array_merge($this->defaultCookies, $this->unencryptedCookies);\n }\n \n return collect($this->defaultCookies)->map(function ($value) {\n return encrypt($value, false);\n- })->all();\n+ })->merge($this->unencryptedCookies)->all();\n }\n \n /**", "filename": "src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php", "status": "modified" }, { "diff": "@@ -73,6 +73,27 @@ public function testWithCookiesSetsCookiesAndOverwritesPreviousValues()\n $this->assertSame('baz', $this->defaultCookies['foo']);\n $this->assertSame('new-value', $this->defaultCookies['new-cookie']);\n }\n+\n+ public function testWithUnencryptedCookieSetCookie()\n+ {\n+ $this->withUnencryptedCookie('foo', 'bar');\n+\n+ $this->assertCount(1, $this->unencryptedCookies);\n+ $this->assertSame('bar', $this->unencryptedCookies['foo']);\n+ }\n+\n+ public function testWithUnencryptedCookiesSetsCookiesAndOverwritesPreviousValues()\n+ {\n+ $this->withUnencryptedCookie('foo', 'bar');\n+ $this->withUnencryptedCookies([\n+ 'foo' => 'baz',\n+ 'new-cookie' => 'new-value',\n+ ]);\n+\n+ $this->assertCount(2, $this->unencryptedCookies);\n+ $this->assertSame('baz', $this->unencryptedCookies['foo']);\n+ $this->assertSame('new-value', $this->unencryptedCookies['new-cookie']);\n+ }\n }\n \n class MyMiddleware", "filename": "tests/Foundation/Testing/Concerns/MakesHttpRequestsTest.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 handleBeginTransactionException method calling pdo property instead of getPdo() method (#31230)\r\n\r\n### Description:\r\n\r\nWhen connection to database is lost and transaction is retried, an exception is thrown.\r\n\r\n```text\r\n[2020-01-24 15:00:16] production.ERROR: Symfony\\Component\\Debug\\Exception\\FatalThrowableError: Call to undefined method Closure::beginTransaction() in /var/www/html/vendor/illuminate/database/Concerns/ManagesTransactions.php:157\r\nStack trace:\r\n#0 /var/www/html/vendor/illuminate/database/Concerns/ManagesTransactions.php(125): Illuminate\\Database\\Connection->handleBeginTransactionException(Object(PDOException))\r\n#1 /var/www/html/vendor/illuminate/database/Concerns/ManagesTransactions.php(105): Illuminate\\Database\\Connection->createTransaction()\r\n#2 /var/www/html/vendor/illuminate/database/Concerns/ManagesTransactions.php(23): Illuminate\\Database\\Connection->beginTransaction()\r\n#3 /var/www/html/vendor/illuminate/database/DatabaseManager.php(349): Illuminate\\Database\\Connection->transaction(Object(Closure))\r\n#4 /var/www/html/vendor/illuminate/support/Facades/Facade.php(261): Illuminate\\Database\\DatabaseManager->__call('transaction', Array)\r\n#5 /var/www/html/app/Services/PriceService.php(55): Illuminate\\Support\\Facades\\Facade::__callStatic('transaction', Array)\r\n```\r\n\r\nThe exception is thrown because of line 157 calling $this->pdo instead of $this->getPdo()\r\n\r\nSame bug was detected in Laravel 5.3 but was not linked to the same file.\r\n\r\nhttps://github.com/laravel/framework/issues/15927\r\n\r\n### Steps To Reproduce:\r\n\r\nLose connection to database during transaction creation (hard to reproduce but easy to fix)", "number": 31233, "review_comments": [], "title": "[6.x] Fix handleBeginTransactionException method calling pdo property instead of getPdo() method" }
{ "commits": [ { "message": "Fix handleBeginTransactionException method calling pdo property instead of getPdo() method (#31230)" }, { "message": "Fix code styling in ManagesTransactions" } ], "files": [ { "diff": "@@ -154,7 +154,7 @@ protected function handleBeginTransactionException($e)\n if ($this->causedByLostConnection($e)) {\n $this->reconnect();\n \n- $this->pdo->beginTransaction();\n+ $this->getPdo()->beginTransaction();\n } else {\n throw $e;\n }", "filename": "src/Illuminate/Database/Concerns/ManagesTransactions.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.5.2\r\n- PHP Version: 7.4.0\r\n\r\n### Description:\r\nThis bug manifested itself when I pointed Laravel Nova's `File` field to a file of 1,04 GB. Nova is unable to download those files. The log shows an out-of-memory error.\r\n\r\nI investigated the problem and I think it lies with `Illuminate\\Filesystem\\FilesystemAdapter`, which uses a `fpasstru()` of the stream. \r\nhttps://github.com/laravel/framework/blob/f3c1f4898552ef7cfd7f422a164c3ed791ff8d29/src/Illuminate/Filesystem/FilesystemAdapter.php#L163-L167\r\n\r\nThis loads the whole file in memory. The following would work:\r\n\r\n\r\n```php\r\n $response->setCallback(function () use ($path) {\r\n $stream = $this->readStream($path);\r\n while (! feof($stream)) {\r\n echo fread($stream, 2048);\r\n }\r\n fclose($stream);\r\n });\r\n\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\nGet yourself a large file and point a tinker session to it:\r\n\r\n`>>> Storage::download('large-file.csv')->send()`\r\n\r\nWith `fpassthru()`, you get a \"Allowed memory size of 134217728 bytes exhausted (tried to allocate 1041674240 bytes)\".\r\nWith the `while` loop it just streams data.\r\n\r\nHappy to PR.\r\n\r\n---\r\n\r\nCredits: https://www.php.net/manual/en/function.fpassthru.php#29162\r\nMore examples on that page too.", "comments": [ { "body": "Feel free to send in a PR. Thanks.", "created_at": "2020-01-17T13:36:27Z" }, { "body": "PR was merged.", "created_at": "2020-01-21T14:28:54Z" }, { "body": "@driesvints how come this change isn't in Laravel 9.x? How do I apply this fix to my vendor files?\r\n\r\nhttps://github.com/laravel/framework/blob/9.x/src/Illuminate/Filesystem/FilesystemAdapter.php#L298", "created_at": "2022-12-14T22:12:13Z" }, { "body": "Because it was reverted, see the PR: https://github.com/laravel/framework/pull/31163#issuecomment-590881417", "created_at": "2022-12-15T08:48:30Z" }, { "body": "This is still an issue....", "created_at": "2023-02-13T12:09:02Z" } ], "number": 31159, "title": "Downloading large files gives out of memory errors" }
{ "body": "Fixes issue #31159", "number": 31163, "review_comments": [ { "body": "Do we know why this \"dark magic hackery\" fixes it 🧙‍♂️ ?", "created_at": "2020-01-18T19:25:48Z" }, { "body": "Seems like output buffering tries chunking data with php free memory size.\r\nIf you will give data upper size than free memory size, output buffering chunking attempts with php free memory size will be failed.\r\nThis `while` giving data with small sizes to output buffer for help to output buffering chunking via php free memory size.\r\n\r\nThis issue was soo interesting for me. :D", "created_at": "2020-01-20T11:44:16Z" }, { "body": "Why not stream_copy_to_stream? Eg https://github.com/symfony/http-foundation/blob/0f977dd6a6ab22789f49cefccdb623734da2ba3c/BinaryFileResponse.php#L297-L303", "created_at": "2020-02-25T09:24:58Z" }, { "body": "> Why not stream_copy_to_stream? Eg https://github.com/symfony/http-foundation/blob/0f977dd6a6ab22789f49cefccdb623734da2ba3c/BinaryFileResponse.php#L297-L303\r\n\r\nActually, functionally same thing. Only having an different point, `while` is chunking data for output buffering.", "created_at": "2020-02-25T10:20:38Z" } ], "title": "[6.x] Fix memory usage on downloading large files" }
{ "commits": [ { "message": "fix memory usage on downloading large files" }, { "message": "Update FilesystemAdapter.php" } ], "files": [ { "diff": "@@ -162,7 +162,11 @@ public function response($path, $name = null, array $headers = [], $disposition\n \n $response->setCallback(function () use ($path) {\n $stream = $this->readStream($path);\n- fpassthru($stream);\n+\n+ while (! feof($stream)) {\n+ echo fread($stream, 2048);\n+ }\n+\n fclose($stream);\n });\n ", "filename": "src/Illuminate/Filesystem/FilesystemAdapter.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.6.1\r\n- PHP Version: 7.3.11\r\n- Database Driver & Version: MySQL 5.7.27\r\n\r\n### Description:\r\nWhen the `TransactionCommitted` event is dispatched, it seems to contain the transaction level _after_ the transaction has been committed, rather than the transaction level the connection was at when the transaction was committed.\r\n\r\nFor example, if I begin a transaction, that dispatches a `TransactionBeginning` event and the transaction level on the connection is incremented to `1`. When that transaction is committed, a `TransactionCommitted` event is dispatched but the transaction level is `0`. I’d expect the transaction level for the corresponding `TransactionCommitted` event to be `1` as well, so I can listen for when a transaction is started and committed.\r\n\r\n### Steps To Reproduce:\r\n1. Start a transaction. Transaction level in `TransactionBeginning` event is `1`.\r\n2. Commit transaction. Transaction level in `TransactionCommitted` event is `0` (one less than transaction level in `TransactionBeginning` event).\r\n\r\n## Test Code\r\n\r\nI created a simple route that writes a row within a transaction, and set up listeners on the `TransactionBeginning` and `TransactionCommitted` events to log the transaction level:\r\n\r\n```php\r\nRoute::get('/', function () {\r\n DB::transaction(function () {\r\n App\\User::create([\r\n 'name' => 'John Doe',\r\n 'email' => sprintf('john.doe+%s@example.com', uniqid()),\r\n 'password' => Hash::make('password'),\r\n ]);\r\n });\r\n\r\n return response('Done.');\r\n});\r\n```\r\n```php\r\n<?php\r\n\r\nnamespace App\\Listeners;\r\n\r\nuse Illuminate\\Database\\Events\\ConnectionEvent;\r\nuse Illuminate\\Support\\Facades\\Log;\r\n\r\nclass LogTransactionLevel\r\n{\r\n public function handle(ConnectionEvent $event)\r\n {\r\n Log::debug(\r\n sprintf('Transaction level for %s event is %d', get_class($event), $event->connection->transactionLevel())\r\n );\r\n }\r\n}\r\n```\r\n\r\nContents of log file after hitting route:\r\n\r\n```\r\n[2019-12-04 13:12:53] local.DEBUG: Transaction level for Illuminate\\Database\\Events\\TransactionBeginning event is 1 \r\n[2019-12-04 13:12:53] local.DEBUG: Transaction level for Illuminate\\Database\\Events\\TransactionCommitted event is 0 \r\n```", "comments": [ { "body": "Hmm I can indeed see that as problematic. Appreciating a PR if you could whip up one. Thanks for reporting.", "created_at": "2019-12-05T14:17:27Z" }, { "body": "@driesvints Thanks for confirming! Will work on a PR 🙂 What branch should I open the PR against?", "created_at": "2019-12-05T16:16:06Z" }, { "body": "Probably master", "created_at": "2019-12-05T16:24:06Z" }, { "body": "> @driesvints Thanks for confirming! Will work on a PR 🙂 What branch should I open the PR against?\r\n\r\nPlease read https://laravel.com/docs/6.x/contributions", "created_at": "2019-12-12T19:14:09Z" }, { "body": "@AReyes-cl Was that really necessary? @driesvints already gave an answer. A week ago.\r\n\r\nI wasn’t sure whether this was a bug fix or a “major new feature”, which is why I asked.", "created_at": "2019-12-12T21:41:19Z" }, { "body": "@martinbean I think it makes sense that `TransactionCommitted` returns `$transactions - 1` since it means that the previous transaction has been resolved or committed ? ", "created_at": "2019-12-14T16:44:04Z" }, { "body": "@martinbean according to the docs [https://laravel.com/docs/6.x/contributions#which-branch](https://laravel.com/docs/6.x/contributions#which-branch):\r\n\r\n> All bug fixes should be sent to the latest stable branch or to the current LTS branch. Bug fixes should never be sent to the master branch unless they fix features that exist only in the upcoming release.", "created_at": "2019-12-18T18:13:55Z" }, { "body": "@denvit an answer was already provided for this and someone already noted this above. \r\n\r\nI'm going to lock this as I believe there isn't really anything left to discuss here. Anyone's free to pr in a fix for this. ", "created_at": "2019-12-19T11:47:59Z" }, { "body": "PR was merged.", "created_at": "2019-12-19T14:35:59Z" }, { "body": "https://github.com/laravel/framework/pull/30883", "created_at": "2019-12-19T14:36:04Z" } ], "number": 30756, "title": "TransactionCommitted event doesn’t contain transaction level I’d expect it to" }
{ "body": " Fire transactionCommitted event before decrementing the transaction level ! as described here #30756 ", "number": 30883, "review_comments": [], "title": "[6.x] TransactionCommitted event doesn’t contain transaction level I’d expect it to" }
{ "commits": [ { "message": "launch transactionCommitted before decreasinig the transactions level\n\nthis is fix for #30756" } ], "files": [ { "diff": "@@ -171,9 +171,9 @@ public function commit()\n $this->getPdo()->commit();\n }\n \n- $this->transactions = max(0, $this->transactions - 1);\n-\n $this->fireConnectionEvent('committed');\n+\n+ $this->transactions = max(0, $this->transactions - 1);\n }\n \n /**", "filename": "src/Illuminate/Database/Concerns/ManagesTransactions.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.5\r\n- PHP Version: 7.3.11\r\n- Database Driver & Version: MySQL - 5.7.27-0ubuntu0.18.04.1\r\n\r\n### Description:\r\nWhile writing a migration to fix a bad database that had stored a foreign key as a varchar, I wrote the following migration:\r\n```php\r\nSchema::table('jobseeker_qualifications', function (Blueprint $table) {\r\n $table->bigIncrements('id')->change();\r\n $table->unsignedBigInteger('user_id')->change();\r\n $table->unsignedBigInteger('jobseekers_education_id')->change();\r\n $table->foreign('user_id')->references('id')->on('users');\r\n $table->foreign('jobseekers_education_id')->references('id')->on('jobseeker_educations');\r\n});\r\n```\r\nHowever, this above migration generated the following SQL:\r\n```sql\r\nALTER TABLE jobseeker_qualifications\r\nCHANGE id id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL,\r\nCHANGE jobseekers_education_id jobseekers_education_id BIGINT UNSIGNED CHARACTER SET utf8 NOT NULL COLLATE `utf8_unicode_ci`,\r\nCHANGE user_id user_id BIGINT UNSIGNED NOT NULL\r\n```\r\n**Work Around:** Removing the instructions related to the character set and running this query manually was successful.\r\n\r\n### Steps To Reproduce:\r\n1. Create a table containing a VARCHAR field that contains valid id values (only numbers).\r\n2. Run a migration similar to the above, requesting a change the VARCHAR to unsigned BIGINT.", "comments": [ { "body": "What was the error message?", "created_at": "2019-11-08T22:34:26Z" }, { "body": "> What was the error message?\r\n\r\n```SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CHARACTER SET utf8 NOT NULL COLLATE `utf8_unicode_ci`, CHANGE user_id user_id B' at line 3```\r\n\r\nThose character set and collate instructions should not have been there.", "created_at": "2019-11-11T09:01:01Z" }, { "body": "What version of the `doctrine/dbal` package are you using (run `composer show)`?", "created_at": "2019-11-11T09:20:07Z" }, { "body": "> What version of the doctrine/dbal package are you using (run composer show)?\r\n\r\nHere:\r\n`doctrine/dbal v2.10.0`", "created_at": "2019-11-11T09:23:46Z" }, { "body": "Can you try downgrading to `2.9.3`?\r\n\r\nIt looks like this is the same bug: https://github.com/doctrine/dbal/issues/3714", "created_at": "2019-11-11T09:28:47Z" }, { "body": "> Can you try downgrading to 2.9.3?\r\n> It looks like this is the same bug: doctrine/dbal#3714\r\n\r\nIt does indeed look like the same bug, I'll subscribe to that bug tracker to see when it's been fixed and I could update this ticket in turn.\r\n\r\nI don't have the time at the moment to try the downgrade due to work pressures and the manual script work around is functional for the moment, but if I get a chance to I shall look in to it.", "created_at": "2019-11-11T09:39:12Z" }, { "body": "Seems like this is related to DBAL and not Laravel so going to close this one.", "created_at": "2019-11-11T10:50:29Z" }, { "body": "DBAL just closed the issue: see https://github.com/doctrine/dbal/issues/3714#issuecomment-558573089", "created_at": "2019-11-26T11:09:27Z" }, { "body": "Can please folks from Laravel and folks from Doctrine make an agreement and push this issue a bit further? \r\nhttps://github.com/doctrine/dbal/issues/3714#issuecomment-559585932\r\n\r\nLaravel says it's issue on Doctrine's side. Doctrine says it's issue on Laravel side. Meanwhile we are locked on older version of Doctrine when we want to keep our projects up-to-date.\r\nThank you in advance.\r\n\r\nPlease note this happened to us when changing varchar column to integer.", "created_at": "2019-11-28T21:23:35Z" }, { "body": "Hello everyone, I'm one of the core members of the Doctrine team 👋\r\n\r\nAs I mentioned on the issue in DBAL, I completely understand your frustration and am sorry for this inconvenience.\r\n\r\nWe really believe that the issue is related to how Laravel configures the DBAL objects to perform the comparisons and think that it was working previously due to a bug that got fixed. \r\n\r\nI don't know Laravel so much to solve this but feel free to ping me in a PR or on Doctrine's slack channel and I'll do my best to support the resolution of this issue. \r\n\r\n@JohnyProkie thanks for pointing us here and @driesvints and other Laravel maintainers for their hard work on building bridges between the two projects 🤟\r\n", "created_at": "2019-11-28T22:32:04Z" }, { "body": "@lcobucci Thank you a lot for stepping in!", "created_at": "2019-11-29T08:03:26Z" }, { "body": "Let's figure this out. If anyone could help pinpoint where we can implement a fix that'd be great. \r\n\r\n@lcobucci thanks for your hard work on Doctrine as well :)", "created_at": "2019-11-29T12:49:22Z" }, { "body": "@driesvints I haven't debugged anything but https://github.com/laravel/framework/blob/1bbe5528568555d597582fdbec73e31f8a818dbc/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php#L125-L127 might give us a clue.\r\n\r\nLaravel should make sure to not set the charset/collation info on the objects while performing the changes.", "created_at": "2019-11-29T15:09:52Z" }, { "body": "@lcobucci it does seem that only applies to `json` and `binary` columns while the issue here is changing a column type from `varchar` to `bigint` so I'm not sure if that's the actual culprit?\r\n\r\nhttps://github.com/laravel/framework/blob/1bbe5528568555d597582fdbec73e31f8a818dbc/src/Illuminate/Database/Schema/Grammars/ChangeColumn.php#L124-L128", "created_at": "2019-12-02T11:29:11Z" }, { "body": "@driesvints that's the problem. As [@AlterTable explained it](https://github.com/doctrine/dbal/issues/3714#issuecomment-549767693):\r\n\r\n> But when it's original type was varchar/text, there is a implicit change: the charset definition should be removed. Neither Laravel nor Doctrine handled this.\r\n> I think there are two ways to fix this, one is add extra checks in \\Doctrine\\DBAL\\Schema\\Table::changeColumn, another is modify Laravel migrate, add checks after changed attributes are set. I prefer the second one.\r\n\r\nLaravel should define `characterset` and `collation` as `null` to remove that info.\r\n\r\nDoes this help?", "created_at": "2019-12-02T12:37:50Z" }, { "body": "@lcobucci heya, it does. I think this is indeed the correct way to go forward. I currently don't have time to work on this so if anyone is experiencing this issue and wants to move this forward, feel free to send in a PR.", "created_at": "2019-12-06T16:43:37Z" }, { "body": "Hi all, if anyone on Laravel 6.x & doctrine/dbal 2.10 experiencing this issue, the quick fix is to set charset and collation to empty string on column change statement. For example:\r\n\r\n`$table->integer('resource_type')->default(0)->charset('')->collation('')->change();`\r\n\r\nIt does work on my case where previous column type is string (varchar).\r\nLooks like someone has already sent PR to fix this, but I hope solution above still help before the PR merged.", "created_at": "2019-12-09T23:25:01Z" }, { "body": "> Hi all, if anyone on Laravel 6.x & doctrine/dbal 2.10 experiencing this issue, the quick fix is to set charset and collation to empty string on column change statement. For example:\r\n> \r\n> `$table->integer('resource_type')->default(0)->charset('')->collation('')->change();`\r\n> \r\n> It does work on my case where previous column type is string (varchar).\r\n> Looks like someone has already sent PR to fix this, but I hope solution above still help before the PR merged.\r\n\r\nThis unfortunately isn't working for me for some reason. I've tried `null` and `''` for charset and collation and I still get the same error. I'm going from `string` to `bigInteger`:\r\n\r\n```php\r\n$table->bigInteger('number')\r\n ->charset('')\r\n ->collation('')\r\n ->change();\r\n```\r\n\r\nI finally ended up just running the raw query:\r\n\r\n```sql\r\n\\DB::statement('alter table orders modify number bigint not null');\r\n```", "created_at": "2020-02-11T15:39:29Z" }, { "body": "Fixed by https://github.com/laravel/framework/commit/fccdf7c42d5ceb50985b3e8243d7ba650de996d6", "created_at": "2020-04-30T20:10:30Z" }, { "body": "still present in:\r\n\"php\": \"^7.2\",\r\n\"laravel/framework\": \"^6.0\",\r\n\"doctrine/dbal\": \"^2.10\",\r\n\r\nerror while trying to change column from text to blob\r\n\r\nworkaround for me was to make a intermediary migration that runs above the alter and drop the column and recreate it for both fwd and reverse migration\r\n\r\n`Doctrine\\DBAL\\Driver\\PDOException::(\"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARACTER SET utf8mb4 DEFAULT NULL' at line 1\")\r\n /var/www/****/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:66`", "created_at": "2020-06-10T13:15:40Z" }, { "body": "@strtz try to update dependencies", "created_at": "2020-07-02T17:22:46Z" }, { "body": "> Fixed by [fccdf7c](https://github.com/laravel/framework/commit/fccdf7c42d5ceb50985b3e8243d7ba650de996d6)\r\n\r\nIt worked thanks @taylorotwell ", "created_at": "2020-08-11T09:40:10Z" } ], "number": 30539, "title": "Migrating a varchar to a bigint causes invalid charset instructions to appear" }
{ "body": "Referencing #30539\r\nPR for 6.x branch", "number": 30794, "review_comments": [], "title": "[6.x] set collation and charSet to null if type is smallint, int or bigint" }
{ "commits": [ { "message": "set collation and charSet to null if type is smallint, int or bigint" }, { "message": "fix for CI" } ], "files": [ { "diff": "@@ -127,6 +127,17 @@ protected static function getDoctrineColumnChangeOptions(Fluent $fluent)\n ];\n }\n \n+ if (in_array($fluent['type'], ['smallInteger', 'integer', 'bigInteger'])) {\n+ $options['customSchemaOptions'] = [\n+ 'collation' => null,\n+ 'charset' => null,\n+ ];\n+ $options['platformOptions'] = [\n+ 'collation' => null,\n+ 'charset' => null,\n+ ];\n+ }\n+\n return $options;\n }\n ", "filename": "src/Illuminate/Database/Schema/Grammars/ChangeColumn.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.12\r\n- PHP Version: 7.2.11\r\n- Database Driver & Version: mysql/sqlite\r\n\r\n### Description:\r\nIf you use Artisan::call method to make a migration to a database that is not your default, it will change default database connection for the whole application. I would reasonably expect, that the --database flag would only persist for the called artisan command.\r\n\r\n### Steps To Reproduce:\r\n```\r\n logger(DB::getDefaultConnection());\r\n logger(DB::getDatabaseName());\r\n\r\nArtisan::call('migrate', ['--database' => 'sqlite_cache', '--path' => 'some/path/to/migrations']);\r\n\r\n logger(DB::getDefaultConnection());\r\n logger(DB::getDatabaseName());\r\n```\r\n\r\nBefore the Artisan::call you will get your default connection details (f.e. mysql), after the Artisan::call you will get sqlite_cache as default connection.", "comments": [ { "body": "Heya, thanks for reporting.\r\n\r\nI'll need more info and/or code to debug this further. Please post relevant code like models, jobs, commands, notifications, events, listeners, controller methods, routes, etc. You may use https://paste.laravel.io to post larger snippets or just reply with shorter code snippets. \r\n\r\nThanks!", "created_at": "2019-04-18T12:01:39Z" }, { "body": "You can put this code in your AppServiceProvider and see it for yourself. Let's say your DB_CONNECTION is set to mysql. After Artisan::call is called, your database connection will be set to sqlite.\r\n\r\n```\r\nclass AppServiceProvider extends ServiceProvider\r\n{\r\n public function boot()\r\n {\r\n logger(DB::getDefaultConnection());\r\n logger(DB::getDatabaseName());\r\n \r\n Artisan::call('migrate', ['--database' => 'sqlite']);\r\n \r\n logger(DB::getDefaultConnection());\r\n logger(DB::getDatabaseName());\r\n }\r\n}\r\n```\r\n\r\nYou then need to restore your original default with DB::setDefaultConnection(...). I suppose Artisan should do that automatically when --database flag is used.", "created_at": "2019-04-18T13:13:35Z" }, { "body": "The problem is that when Artisan is running any database related commands, it sets the option passed with'--database' flag as the framework's default connection. I guess that it was not meant to call such artisan commands somewhere in between while the framework is processing the request (like in my case).\r\n\r\nI guess, the solutions here are two:\r\n1) It should remember what connection is actually set as the default, and after finishing with processing the command set it back to the \"real\" default one.\r\n\r\n2) Use the specified connection, without changing the default connection (for example like QueryBuilder does).", "created_at": "2019-04-29T18:48:53Z" }, { "body": "Hmm, you're correct I believe. Although I've seen quite some issues about this I believe that the connection should be reset once the command has been run. Although this is a bit hard to do since everything's done in a single request.", "created_at": "2019-04-30T10:02:29Z" }, { "body": "Last time I tried to fix this issue I sent this PR, but upon better testing I realized it didn't fix it at all. Inside the PR there's a code snippet that I use to avoid this issue.\r\n\r\nhttps://github.com/laravel/framework/pull/24875", "created_at": "2019-05-05T10:22:31Z" }, { "body": "Since the prs which fixes this have been rejected I'm afraid this is a nofix. Sorry about this.\r\n\r\nPlease see Taylor's comments here: https://github.com/laravel/framework/pull/28644#issuecomment-498426644", "created_at": "2019-06-24T11:05:56Z" }, { "body": "> Since the prs which fixes this have been rejected I'm afraid this is a nofix. Sorry about this.\r\n\r\nJust to confirm, does Laravel team still consider this a bug or an expected behaviour due to migration limitation. A `nofix` seem to indicate expected behaviour but this still being tagged as `bug`.", "created_at": "2019-11-25T02:00:21Z" }, { "body": "@crynobone I don't always unlabel issues which I close", "created_at": "2019-11-26T09:22:28Z" }, { "body": "@driesvints just wondering if Laravel still going to accept a fix to this issue or let it be?", "created_at": "2019-11-26T11:19:09Z" }, { "body": "@crynobone taylor let me know that we're open to a pr but perhaps it's best that it targets the next major release", "created_at": "2019-11-26T13:40:10Z" }, { "body": "@MattStrauss's implementation of this in #28644 looks pretty solid and has tests.", "created_at": "2019-11-26T21:39:37Z" }, { "body": "The PR for this got merged and will be available in the next major Laravel release.", "created_at": "2019-12-06T16:14:57Z" } ], "number": 28253, "title": "Artisan::call migrate --database flag changes default connection" }
{ "body": "This will be useful when having an application that handle migrations\r\nfor more than one database connection.\r\n\r\nThe side affect of current implementation is that until the request\r\n(web/console) is terminated the database will used the latest migration\r\nconnection as default.\r\n\r\nSolved #28253\r\n\r\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>\r\n\r\n<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n", "number": 30720, "review_comments": [ { "body": "```suggestion\r\n```", "created_at": "2019-11-30T10:55:00Z" }, { "body": "```suggestion\r\n 'driver' => 'sqlite',\r\n```", "created_at": "2019-11-30T10:55:10Z" }, { "body": "```suggestion\r\n\r\n if (! $repository2->repositoryExists()) {\r\n```", "created_at": "2019-11-30T10:55:17Z" }, { "body": "```suggestion\r\n $this->previousConnection = $this->resolver->getDefaultConnection();\r\n\r\n```", "created_at": "2019-11-30T10:56:02Z" }, { "body": "```suggestion\r\n $previousConnection = $this->migrator->getConnection();\r\n\r\n```", "created_at": "2019-11-30T10:56:20Z" }, { "body": "Done", "created_at": "2019-11-30T11:25:47Z" }, { "body": "Done", "created_at": "2019-11-30T11:26:02Z" }, { "body": "Done", "created_at": "2019-11-30T11:26:31Z" }, { "body": "Done", "created_at": "2019-11-30T11:26:38Z" } ], "title": "[7.x] Restore default connection after Artisan migrate/seed call" }
{ "commits": [ { "message": "[7.x] Restore default connection after Artisan migrate/seed call\n\nThis will be useful when having an application that handle migrations\nfor more than one database connection.\n\nThe side affect of current implementation is that until the request\n(web/console) is terminated the database will used the latest migration\nconnection as default.\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>" }, { "message": "Fixes styling based on review.\n\nSigned-off-by: Mior Muhammad Zaki <crynobone@gmail.com>" } ], "files": [ { "diff": "@@ -49,6 +49,8 @@ public function __construct(Migrator $migrator)\n */\n public function handle()\n {\n+ $previousConnection = $this->migrator->getConnection();\n+\n $this->migrator->setConnection($this->option('database'));\n \n if (! $this->migrator->repositoryExists()) {\n@@ -66,6 +68,8 @@ public function handle()\n } else {\n $this->error('No migrations found');\n }\n+\n+ $this->migrator->restorePriorConnection($previousConnection);\n }\n \n /**", "filename": "src/Illuminate/Database/Console/Migrations/StatusCommand.php", "status": "modified" }, { "diff": "@@ -57,12 +57,18 @@ public function handle()\n return;\n }\n \n+ $previousConnection = $this->resolver->getDefaultConnection();\n+\n $this->resolver->setDefaultConnection($this->getDatabase());\n \n Model::unguarded(function () {\n $this->getSeeder()->__invoke();\n });\n \n+ if ($previousConnection) {\n+ $this->resolver->setDefaultConnection($previousConnection);\n+ }\n+\n $this->info('Database seeding completed successfully.');\n }\n ", "filename": "src/Illuminate/Database/Console/Seeds/SeedCommand.php", "status": "modified" }, { "diff": "@@ -51,6 +51,13 @@ class Migrator\n */\n protected $connection;\n \n+ /**\n+ * The connection name before migration is run.\n+ *\n+ * @var string\n+ */\n+ protected $previousConnection = null;\n+\n /**\n * The paths to all of the migration files.\n *\n@@ -141,6 +148,8 @@ public function runPending(array $migrations, array $options = [])\n if (count($migrations) === 0) {\n $this->note('<info>Nothing to migrate.</info>');\n \n+ $this->restorePriorConnection();\n+\n return;\n }\n \n@@ -166,6 +175,8 @@ public function runPending(array $migrations, array $options = [])\n }\n }\n \n+ $this->restorePriorConnection();\n+\n $this->fireMigrationEvent(new MigrationsEnded);\n }\n \n@@ -223,6 +234,8 @@ public function rollback($paths = [], array $options = [])\n if (count($migrations) === 0) {\n $this->note('<info>Nothing to rollback.</info>');\n \n+ $this->restorePriorConnection();\n+\n return [];\n }\n \n@@ -280,6 +293,8 @@ protected function rollbackMigrations(array $migrations, $paths, array $options)\n );\n }\n \n+ $this->restorePriorConnection();\n+\n $this->fireMigrationEvent(new MigrationsEnded);\n \n return $rolledBack;\n@@ -302,6 +317,8 @@ public function reset($paths = [], $pretend = false)\n if (count($migrations) === 0) {\n $this->note('<info>Nothing to rollback.</info>');\n \n+ $this->restorePriorConnection();\n+\n return [];\n }\n \n@@ -528,7 +545,9 @@ public function getConnection()\n */\n public function setConnection($name)\n {\n- if (! is_null($name)) {\n+ if ($name) {\n+ $this->previousConnection = $this->resolver->getDefaultConnection();\n+\n $this->resolver->setDefaultConnection($name);\n }\n \n@@ -548,6 +567,19 @@ public function resolveConnection($connection)\n return $this->resolver->connection($connection ?: $this->connection);\n }\n \n+ /**\n+ * Restore prior connection after migration runs.\n+ *\n+ * @param string $passedPreviousConnection\n+ * @return void\n+ */\n+ public function restorePriorConnection($passedPreviousConnection = null)\n+ {\n+ if ($previousConnection = $passedPreviousConnection ?? $this->previousConnection) {\n+ $this->resolver->setDefaultConnection($previousConnection);\n+ }\n+ }\n+\n /**\n * Get the schema grammar out of a migration connection.\n *", "filename": "src/Illuminate/Database/Migrations/Migrator.php", "status": "modified" }, { "diff": "@@ -28,10 +28,15 @@ protected function setUp(): void\n $this->db = $db = new DB;\n \n $db->addConnection([\n- 'driver' => 'sqlite',\n- 'database' => ':memory:',\n+ 'driver' => 'sqlite',\n+ 'database' => ':memory:',\n ]);\n \n+ $db->addConnection([\n+ 'driver' => 'sqlite',\n+ 'database' => ':memory:',\n+ ], 'sqlite2');\n+\n $db->setAsGlobal();\n \n $container = new Container;\n@@ -53,6 +58,13 @@ protected function setUp(): void\n if (! $repository->repositoryExists()) {\n $repository->createRepository();\n }\n+\n+ $repository2 = new DatabaseMigrationRepository($db->getDatabaseManager(), 'migrations');\n+ $repository2->setSource('sqlite2');\n+\n+ if (! $repository2->repositoryExists()) {\n+ $repository2->createRepository();\n+ }\n }\n \n protected function tearDown(): void\n@@ -170,4 +182,45 @@ public function testMigrationsCanBeProperlySortedAcrossMultiplePaths()\n \n $this->assertEquals($expected, $migrationsFilesFullPaths);\n }\n+\n+ public function testConnectionPriorToMigrationIsNotChangedAfterMigration()\n+ {\n+ $this->migrator->setConnection('default');\n+ $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->assertEquals('default', $this->migrator->getConnection());\n+ }\n+\n+ public function testConnectionPriorToMigrationIsNotChangedAfterRollback()\n+ {\n+ $this->migrator->setConnection('default');\n+ $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->migrator->rollback([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->assertEquals('default', $this->migrator->getConnection());\n+ }\n+\n+ public function testConnectionPriorToMigrationIsNotChangedWhenNoOutstandingMigrationsExist()\n+ {\n+ $this->migrator->setConnection('default');\n+ $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->migrator->setConnection('default');\n+ $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->assertEquals('default', $this->migrator->getConnection());\n+ }\n+\n+ public function testConnectionPriorToMigrationIsNotChangedWhenNothingToRollback()\n+ {\n+ $this->migrator->setConnection('default');\n+ $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->migrator->rollback([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->migrator->rollback([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->assertEquals('default', $this->migrator->getConnection());\n+ }\n+\n+ public function testConnectionPriorToMigrationIsNotChangedAfterMigrateReset()\n+ {\n+ $this->migrator->setConnection('default');\n+ $this->migrator->run([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->migrator->reset([__DIR__.'/migrations/one'], ['database' => 'sqlite2']);\n+ $this->assertEquals('default', $this->migrator->getConnection());\n+ }\n }", "filename": "tests/Database/DatabaseMigratorIntegrationTest.php", "status": "modified" }, { "diff": "@@ -25,6 +25,7 @@ public function testHandle()\n $seeder->shouldReceive('__invoke')->once();\n \n $resolver = m::mock(ConnectionResolverInterface::class);\n+ $resolver->shouldReceive('getDefaultConnection')->once();\n $resolver->shouldReceive('setDefaultConnection')->once()->with('sqlite');\n \n $container = m::mock(Container::class);", "filename": "tests/Database/SeedCommandTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.6\r\n- PHP Version: 7.3\r\n\r\n### Description:\r\n\r\n- [BelongsTo relation returns old relation when associate() is called with model ID · Issue #26401 · laravel/framework](https://github.com/laravel/framework/issues/26401)\r\n\r\nThis issue is almost the same as previously submitted #26401 (@joostbaptist), but reports incomplete bug fixes.\r\n\r\nThe argument can be checked with `isDirty()` when the relation corresponding to the **synced** key is loaded, but it will fail if the relation corresponding to the **dirty** key is loaded.\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n$user = User::find(1);\r\n\r\n$post = new Post();\r\n$post->user()->associate(2);\r\n$post->save();\r\n\r\n$post->user()->associate($user); // dirty\r\n$post->user()->associate(2); // clean\r\n\r\nassert($user !== $post->user); // fails\r\n```\r\n\r\n### Patch Proposal:\r\n\r\n```diff\r\n /**\r\n * Associate the model instance to the given parent.\r\n *\r\n * @param \\Illuminate\\Database\\Eloquent\\Model|int|string $model\r\n * @return \\Illuminate\\Database\\Eloquent\\Model\r\n */\r\n public function associate($model)\r\n {\r\n $ownerKey = $model instanceof Model ? $model->getAttribute($this->ownerKey) : $model;\r\n \r\n $this->child->setAttribute($this->foreignKey, $ownerKey);\r\n \r\n if ($model instanceof Model) {\r\n $this->child->setRelation($this->relationName, $model);\r\n- } elseif ($this->child->isDirty($this->foreignKey)) {\r\n+ } elseif (\r\n+ $this->child->relationLoaded($this->relationName)\r\n+ && optional($this->child->getRelationValue($this->relationName))->getKey() !== $ownerKey\r\n+ ) {\r\n $this->child->unsetRelation($this->relationName);\r\n }\r\n \r\n return $this->child;\r\n }\r\n```", "comments": [ { "body": "Thanks for reporting. Feel free to send in a PR with a test.", "created_at": "2019-11-28T17:54:18Z" }, { "body": "@driesvints \r\n\r\n```php\r\noptional($this->child->getRelationValue($this->relationName))->getKey()\r\n```\r\n\r\nI'm pretty anxious whether the statement is really appropriate. How do you think?\r\n\r\n(CC: @taylorotwell @joostbaptist @staudenmeir)", "created_at": "2019-11-28T18:12:48Z" }, { "body": "I think it would be easier to remove the key comparison and just always unset the relation when `associate()` is called with an ID.", "created_at": "2019-11-28T19:30:41Z" }, { "body": "@staudenmeir Good idea", "created_at": "2019-11-28T19:35:00Z" }, { "body": "@driesvints Should we target 7.x?", "created_at": "2019-11-28T20:07:04Z" } ], "number": 30691, "title": "[7.x] Bug: BelongsTo relation returns old relation when associate() is called with model ID " }
{ "body": "Fixes #30691", "number": 30712, "review_comments": [], "title": "[6.x] Fix: Always unset BelongsTo relation when associate() received model ID" }
{ "commits": [ { "message": "Fix: Always unset BelongsTo relation when associate() received model ID" } ], "files": [ { "diff": "@@ -207,7 +207,7 @@ public function associate($model)\n \n if ($model instanceof Model) {\n $this->child->setRelation($this->relationName, $model);\n- } elseif ($this->child->isDirty($this->foreignKey)) {\n+ } else {\n $this->child->unsetRelation($this->relationName);\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsTo.php", "status": "modified" } ] }
{ "body": "https://github.com/laravel/framework/issues/7043\n\n``` php\nModel::findOrFail([1, 2]);\n```\n\nwill now throw a `ModelNotFoundException` if _any_ of the requested IDs don't exist.\n", "comments": [ { "body": ":+1: \n", "created_at": "2015-01-19T20:19:55Z" } ], "number": 7048, "title": "[5.0] The findOrFail method should throw an error when any model is missing" }
{ "body": "### Ensure Builder::findOrFail with Arrayable throws ModelNotFoundException\r\n\r\nI found a regression in #7048 and #19019, where the Eloquent Builder will not throw a `ModelNotFoundException` when an `Arrayable` is passed to `findOrFail`.\r\n\r\nIn #7048, we are checking if the `$ids` is an array and we count the results against the number of ids.\r\n\r\nBut since #19019, the `find` method also accepts an `Arrayable` for the ids.\r\n\r\nSo if an `Arrayable` is passed, the check is skipped and `findOrFail` returns the results.\r\n\r\nTo fix this, we are first checking if the `$ids` is an `Arrayable` and we convert the ids to an array before checking the results.\r\n\r\n### Ensure find* methods on relationships are accepting Arrayable ids\r\n\r\nThis regression is also observed in #9143, because the `find`, `findMany` and `findOrFail` methods were copied from the Eloquent Builder to the `BelongsToMany` and `HasManyThrough` relations, but they did not account for Arrayable ids.\r\n\r\nFor this reason, we need to convert the passed ids to an array before executing the queries.\r\n\r\n**This is a potentially breaking change**, so this should not be merged in 6.x. The reason is because in 6.x a collection/arrayable of ids will not throw an exception if the number of ids does not match the number of found records. While an array with the same ids would throw an exception:\r\n\r\nFor example:\r\n\r\n```php\r\n<?php\r\n\r\nPost::create(['id' => 1]);\r\n\r\n// Before (6.x)\r\nPost::findOrFail([1, 2]); // throws an exception\r\nPost::findOrFail(collect([1, 2])); // returns a collection with posts 1 and 2\r\n\r\n// After (7.x)\r\nPost::findOrFail([1, 2]); // throws an exception\r\nPost::findOrFail(collect([1, 2])); // throws an exception\r\n```", "number": 30312, "review_comments": [], "title": "[7.x] Fix regressions on find* methods with Arrayable ids" }
{ "commits": [ { "message": "Ensure Builder::findOrFail with Arrayable throws ModelNotFoundException\n\nI found a regression in #7048 and #19019, where the Eloquent Builder will not throw a `ModelNotFoundException` when an `Arrayable` is passed to `findOrFail`.\n\nIn this #7048, we are checking if the `$ids` is an array and we count the results against the number of ids.\n\nBut since #19019, the `find` method also accepts an `Arrayable` for the ids.\n\nSo if an `Arrayable` is passed, the check is skipped and the method returns the results.\n\nTo fix this, we are first checking if the `$ids` is an `Arrayable` and we convert the ids to an array before checking the results." }, { "message": "Ensure find* methods on relationships are accepting Arrayable idsThe regression in #7048 and #19019 is also observed in #9143, because the `find`, `findMany` and `findOrFail` methods are copied from the Eloquent Builder to the `BelongsToMany` and `HasManyThrough` relations.For this reason, we need to convert the passed ids to an array before executing the queries." } ], "files": [ { "diff": "@@ -360,6 +360,8 @@ public function findOrFail($id, $columns = ['*'])\n {\n $result = $this->find($id, $columns);\n \n+ $id = $id instanceof Arrayable ? $id->toArray() : $id;\n+\n if (is_array($id)) {\n if (count($result) === count(array_unique($id))) {\n return $result;", "filename": "src/Illuminate/Database/Eloquent/Builder.php", "status": "modified" }, { "diff": "@@ -2,6 +2,7 @@\n \n namespace Illuminate\\Database\\Eloquent\\Relations;\n \n+use Illuminate\\Contracts\\Support\\Arrayable;\n use Illuminate\\Database\\Eloquent\\Builder;\n use Illuminate\\Database\\Eloquent\\Collection;\n use Illuminate\\Database\\Eloquent\\Model;\n@@ -504,21 +505,31 @@ public function updateOrCreate(array $attributes, array $values = [], array $joi\n */\n public function find($id, $columns = ['*'])\n {\n- return is_array($id) ? $this->findMany($id, $columns) : $this->where(\n+ if (is_array($id) || $id instanceof Arrayable) {\n+ return $this->findMany($id, $columns);\n+ }\n+\n+ return $this->where(\n $this->getRelated()->getQualifiedKeyName(), '=', $id\n )->first($columns);\n }\n \n /**\n * Find multiple related models by their primary keys.\n *\n- * @param mixed $ids\n+ * @param \\Illuminate\\Contracts\\Support\\Arrayable|array $ids\n * @param array $columns\n * @return \\Illuminate\\Database\\Eloquent\\Collection\n */\n public function findMany($ids, $columns = ['*'])\n {\n- return empty($ids) ? $this->getRelated()->newCollection() : $this->whereIn(\n+ $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids;\n+\n+ if (empty($ids)) {\n+ return $this->getRelated()->newCollection();\n+ }\n+\n+ return $this->whereIn(\n $this->getRelated()->getQualifiedKeyName(), $ids\n )->get($columns);\n }\n@@ -536,6 +547,8 @@ public function findOrFail($id, $columns = ['*'])\n {\n $result = $this->find($id, $columns);\n \n+ $id = $id instanceof Arrayable ? $id->toArray() : $id;\n+\n if (is_array($id)) {\n if (count($result) === count(array_unique($id))) {\n return $result;", "filename": "src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php", "status": "modified" }, { "diff": "@@ -2,6 +2,7 @@\n \n namespace Illuminate\\Database\\Eloquent\\Relations;\n \n+use Illuminate\\Contracts\\Support\\Arrayable;\n use Illuminate\\Database\\Eloquent\\Builder;\n use Illuminate\\Database\\Eloquent\\Collection;\n use Illuminate\\Database\\Eloquent\\Model;\n@@ -285,7 +286,7 @@ public function firstOrFail($columns = ['*'])\n */\n public function find($id, $columns = ['*'])\n {\n- if (is_array($id)) {\n+ if (is_array($id) || $id instanceof Arrayable) {\n return $this->findMany($id, $columns);\n }\n \n@@ -297,12 +298,14 @@ public function find($id, $columns = ['*'])\n /**\n * Find multiple related models by their primary keys.\n *\n- * @param mixed $ids\n+ * @param \\Illuminate\\Contracts\\Support\\Arrayable|array $ids\n * @param array $columns\n * @return \\Illuminate\\Database\\Eloquent\\Collection\n */\n public function findMany($ids, $columns = ['*'])\n {\n+ $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids;\n+\n if (empty($ids)) {\n return $this->getRelated()->newCollection();\n }\n@@ -325,6 +328,8 @@ public function findOrFail($id, $columns = ['*'])\n {\n $result = $this->find($id, $columns);\n \n+ $id = $id instanceof Arrayable ? $id->toArray() : $id;\n+\n if (is_array($id)) {\n if (count($result) === count(array_unique($id))) {\n return $result;", "filename": "src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php", "status": "modified" }, { "diff": "@@ -126,6 +126,17 @@ public function testFindOrFailMethodWithManyThrowsModelNotFoundException()\n $builder->findOrFail([1, 2], ['column']);\n }\n \n+ public function testFindOrFailMethodWithManyUsingCollectionThrowsModelNotFoundException()\n+ {\n+ $this->expectException(ModelNotFoundException::class);\n+\n+ $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);\n+ $builder->setModel($this->getMockModel());\n+ $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', [1, 2]);\n+ $builder->shouldReceive('get')->with(['column'])->andReturn(new Collection([1]));\n+ $builder->findOrFail(new Collection([1, 2]), ['column']);\n+ }\n+\n public function testFirstOrFailMethodThrowsModelNotFoundException()\n {\n $this->expectException(ModelNotFoundException::class);", "filename": "tests/Database/DatabaseEloquentBuilderTest.php", "status": "modified" }, { "diff": "@@ -6,6 +6,7 @@\n use Illuminate\\Database\\Eloquent\\Model as Eloquent;\n use Illuminate\\Database\\Eloquent\\ModelNotFoundException;\n use Illuminate\\Database\\Eloquent\\SoftDeletes;\n+use Illuminate\\Support\\Collection;\n use Illuminate\\Support\\LazyCollection;\n use PHPUnit\\Framework\\TestCase;\n \n@@ -120,6 +121,40 @@ public function testWhereHasOnARelationWithCustomIntermediateAndLocalKey()\n $this->assertCount(1, $country);\n }\n \n+ public function testFindMethod()\n+ {\n+ HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])\n+ ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])\n+ ->posts()->createMany([\n+ ['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com'],\n+ ['id' => 2, 'title' => 'Another title', 'body' => 'Another body', 'email' => 'taylorotwell@gmail.com'],\n+ ]);\n+\n+ $country = HasManyThroughTestCountry::first();\n+ $post = $country->posts()->find(1);\n+\n+ $this->assertNotNull($post);\n+ $this->assertSame('A title', $post->title);\n+\n+ $this->assertCount(2, $country->posts()->find([1, 2]));\n+ $this->assertCount(2, $country->posts()->find(new Collection([1, 2])));\n+ }\n+\n+ public function testFindManyMethod()\n+ {\n+ HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])\n+ ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])\n+ ->posts()->createMany([\n+ ['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com'],\n+ ['id' => 2, 'title' => 'Another title', 'body' => 'Another body', 'email' => 'taylorotwell@gmail.com'],\n+ ]);\n+\n+ $country = HasManyThroughTestCountry::first();\n+\n+ $this->assertCount(2, $country->posts()->findMany([1, 2]));\n+ $this->assertCount(2, $country->posts()->findMany(new Collection([1, 2])));\n+ }\n+\n public function testFirstOrFailThrowsAnException()\n {\n $this->expectException(ModelNotFoundException::class);\n@@ -142,6 +177,30 @@ public function testFindOrFailThrowsAnException()\n HasManyThroughTestCountry::first()->posts()->findOrFail(1);\n }\n \n+ public function testFindOrFailWithManyThrowsAnException()\n+ {\n+ $this->expectException(ModelNotFoundException::class);\n+ $this->expectExceptionMessage('No query results for model [Illuminate\\Tests\\Database\\HasManyThroughTestPost] 1, 2');\n+\n+ HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])\n+ ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])\n+ ->posts()->create(['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com']);\n+\n+ HasManyThroughTestCountry::first()->posts()->findOrFail([1, 2]);\n+ }\n+\n+ public function testFindOrFailWithManyUsingCollectionThrowsAnException()\n+ {\n+ $this->expectException(ModelNotFoundException::class);\n+ $this->expectExceptionMessage('No query results for model [Illuminate\\Tests\\Database\\HasManyThroughTestPost] 1, 2');\n+\n+ HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])\n+ ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])\n+ ->posts()->create(['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com']);\n+\n+ HasManyThroughTestCountry::first()->posts()->findOrFail(new Collection([1, 2]));\n+ }\n+\n public function testFirstRetrievesFirstRecord()\n {\n $this->seedData();", "filename": "tests/Database/DatabaseEloquentHasManyThroughIntegrationTest.php", "status": "modified" }, { "diff": "@@ -475,6 +475,15 @@ public function testFindOrFailWithMultipleIdsThrowsModelNotFoundException()\n EloquentTestUser::findOrFail([1, 2]);\n }\n \n+ public function testFindOrFailWithMultipleIdsUsingCollectionThrowsModelNotFoundException()\n+ {\n+ $this->expectException(ModelNotFoundException::class);\n+ $this->expectExceptionMessage('No query results for model [Illuminate\\Tests\\Database\\EloquentTestUser] 1, 2');\n+\n+ EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);\n+ EloquentTestUser::findOrFail(new Collection([1, 2]));\n+ }\n+\n public function testOneToOneRelationship()\n {\n $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);", "filename": "tests/Database/DatabaseEloquentIntegrationTest.php", "status": "modified" }, { "diff": "@@ -347,12 +347,16 @@ public function testFindMethod()\n $post->tags()->attach(Tag::all());\n \n $this->assertEquals($tag2->name, $post->tags()->find($tag2->id)->name);\n+ $this->assertCount(0, $post->tags()->findMany([]));\n $this->assertCount(2, $post->tags()->findMany([$tag->id, $tag2->id]));\n+ $this->assertCount(0, $post->tags()->findMany(new Collection()));\n+ $this->assertCount(2, $post->tags()->findMany(new Collection([$tag->id, $tag2->id])));\n }\n \n public function testFindOrFailMethod()\n {\n $this->expectException(ModelNotFoundException::class);\n+ $this->expectExceptionMessage('No query results for model [Illuminate\\Tests\\Integration\\Database\\EloquentBelongsToManyTest\\Tag] 10');\n \n $post = Post::create(['title' => Str::random()]);\n \n@@ -363,6 +367,34 @@ public function testFindOrFailMethod()\n $post->tags()->findOrFail(10);\n }\n \n+ public function testFindOrFailMethodWithMany()\n+ {\n+ $this->expectException(ModelNotFoundException::class);\n+ $this->expectExceptionMessage('No query results for model [Illuminate\\Tests\\Integration\\Database\\EloquentBelongsToManyTest\\Tag] 10, 11');\n+\n+ $post = Post::create(['title' => Str::random()]);\n+\n+ Tag::create(['name' => Str::random()]);\n+\n+ $post->tags()->attach(Tag::all());\n+\n+ $post->tags()->findOrFail([10, 11]);\n+ }\n+\n+ public function testFindOrFailMethodWithManyUsingCollection()\n+ {\n+ $this->expectException(ModelNotFoundException::class);\n+ $this->expectExceptionMessage('No query results for model [Illuminate\\Tests\\Integration\\Database\\EloquentBelongsToManyTest\\Tag] 10, 11');\n+\n+ $post = Post::create(['title' => Str::random()]);\n+\n+ Tag::create(['name' => Str::random()]);\n+\n+ $post->tags()->attach(Tag::all());\n+\n+ $post->tags()->findOrFail(new Collection([10, 11]));\n+ }\n+\n public function testFindOrNewMethod()\n {\n $post = Post::create(['title' => Str::random()]);", "filename": "tests/Integration/Database/EloquentBelongsToManyTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.0.3\r\n- PHP Version: 7.3\r\n\r\n### Description:\r\nI used [Monolog Channe](https://readouble.com/laravel/6.0/en/logging.html)l with [NullHandler](https://github.com/Seldaek/monolog/blob/master/src/Monolog/Handler/NullHandler.php) on Laravel 5.8. It is worked fine.\r\nBut Laravel 6.0 throw following exception.\r\n\r\n```\r\n[2019-09-18 09:59:05] laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {\"exception\":\"[object] (Error(code: 0): Call to undefined method Monolog\\\\Handler\\\\NullHandler::setFormatter() at /vagrant/server/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:376)\r\n[stacktrace]\r\n#0 /vagrant/server/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(347): Illuminate\\\\Log\\\\LogManager->prepareHandler(Object(Monolog\\\\Handler\\\\NullHandler), Array)\r\n#1 /vagrant/server/vendor/laravel/framework/src/Illuminate/Log/LogManager.php(185): Illuminate\\\\Log\\\\LogManager->createMonologDriver(Array)\r\n```\r\n\r\nI guess it is Monolog 1.x -> 2.0 compatibility problem.\r\nLaravel 6.0 newly depend on Monolog 2.0 instead 1.x.\r\n\r\n`Illuminate/Log/LogManager.php` use [`Monolog\\Handler\\HandlerInterface`](https://github.com/Seldaek/monolog/blob/master/src/Monolog/Handler/HandlerInterface.php).\r\nThe interface has `setFormatter()` in Monolog 1.x ([old](https://github.com/Seldaek/monolog/blob/1.x/src/Monolog/Handler/HandlerInterface.php)).\r\nHowever In Monolog 2.0, `setFormatter()` moved to [`Monolog\\Handler\\FormattableHandlerInterface`](https://github.com/Seldaek/monolog/blob/master/src/Monolog/Handler/FormattableHandlerInterface.php).\r\nLogManager must check `FormattableHandlerInterface` before call `setFormatter()` if there are Monolog 2.0.\r\n\r\n### Steps To Reproduce:\r\nMy `config/logging.php` is following.\r\n```\r\n'fluent' => [\r\n 'driver' => 'monolog',\r\n 'level' => 'info',\r\n 'handler' => env('FLUENTD_ENABLE', true) ? App\\Logging\\FluentdHandler::class : Monolog\\Handler\\NullHandler::class,\r\n],\r\n```", "comments": [ { "body": "Did you add these changes? https://github.com/laravel/laravel/commit/c70c986e58fe1a14f7c74626e6e97032d4084d5f", "created_at": "2019-09-24T16:38:32Z" }, { "body": "@driesvints \r\nNo. I use `NullHandler` as my custom monolog channel.\r\nBut I think that this null channel will occur the same problem.", "created_at": "2019-09-25T03:44:31Z" }, { "body": "I managed to reproduce this. Thanks for reporting. Appreciating a PR if you could whip one up.", "created_at": "2019-09-26T09:49:04Z" } ], "number": 30026, "title": "[6.0] Monolog Channel can't use NullHandler in Monolog 2.0" }
{ "body": "Monolog 1 has the `setFormatter` method on the [HandlerInterface](https://github.com/Seldaek/monolog/blob/1.x/src/Monolog/Handler/HandlerInterface.php#L82) while Monolog 2 extracted that method from the `HandlerInterface` to a [FormattableHandlerInterface](https://github.com/Seldaek/monolog/blob/2.0.0/src/Monolog/Handler/FormattableHandlerInterface.php). This now means that a bunch of handlers in Monolog 2 don't have that method aka they are not formattable. The problem is that Laravel is calling the `setFormatter` method without checking if it actually exists on the handler when using Monolog 2 which causes an exception to be thrown.\r\n\r\nThis PR fixes the problem by checking for the `FormattableHandlerInterface` if Monolog 2 is being used. A test has also been added which tests the instantiation of a logger which has the `NullHandler` handler which is no longer formattable in Monolog 2. This test will be run with Monolog 1 in the CI with the low deps option and with Monolog 2 in the newest deps pipeline so it confirms that the instantiation now works with both Monolog versions. This test of course doesn't pass without the fix in this PR.\r\n\r\nFixes #30026 \r\n", "number": 30123, "review_comments": [ { "body": "Can't we just check for the `FormattableHandlerInterface` instance everywhere instead of tall the extra if statements and `$isHandlerFormattable` variable?", "created_at": "2019-09-27T20:32:22Z" }, { "body": "```suggestion\r\n } elseif ($handler instanceof FormattableHandlerInterface && $config['formatter'] !== 'default') {\r\n```", "created_at": "2019-09-27T20:32:37Z" }, { "body": "@driesvints \r\n\r\n> elseif ($handler instanceof FormattableHandlerInterface && $config['formatter'] !== 'default')\r\n\r\nThis would always return `false` on Monolog 1 as the `FormattableHandlerInterface` doesn't exist on Monolog 1.", "created_at": "2019-09-27T20:36:03Z" }, { "body": "Ah gotcha. nvm", "created_at": "2019-09-27T20:40:56Z" } ], "title": "[6.x] Fix Monolog v2 handler instantiation" }
{ "commits": [ { "message": "Fix Monolog handler instantiation" } ], "files": [ { "diff": "@@ -7,6 +7,7 @@\n use InvalidArgumentException;\n use Monolog\\Formatter\\LineFormatter;\n use Monolog\\Handler\\ErrorLogHandler;\n+use Monolog\\Handler\\FormattableHandlerInterface;\n use Monolog\\Handler\\HandlerInterface;\n use Monolog\\Handler\\RotatingFileHandler;\n use Monolog\\Handler\\SlackWebhookHandler;\n@@ -372,9 +373,17 @@ protected function prepareHandlers(array $handlers)\n */\n protected function prepareHandler(HandlerInterface $handler, array $config = [])\n {\n- if (! isset($config['formatter'])) {\n+ $isHandlerFormattable = false;\n+\n+ if (Monolog::API === 1) {\n+ $isHandlerFormattable = true;\n+ } elseif (Monolog::API === 2 && $handler instanceof FormattableHandlerInterface) {\n+ $isHandlerFormattable = true;\n+ }\n+\n+ if ($isHandlerFormattable && ! isset($config['formatter'])) {\n $handler->setFormatter($this->formatter());\n- } elseif ($config['formatter'] !== 'default') {\n+ } elseif ($isHandlerFormattable && $config['formatter'] !== 'default') {\n $handler->setFormatter($this->app->make($config['formatter'], $config['formatter_with'] ?? []));\n }\n ", "filename": "src/Illuminate/Log/LogManager.php", "status": "modified" }, { "diff": "@@ -9,6 +9,7 @@\n use Monolog\\Formatter\\NormalizerFormatter;\n use Monolog\\Handler\\LogEntriesHandler;\n use Monolog\\Handler\\NewRelicHandler;\n+use Monolog\\Handler\\NullHandler;\n use Monolog\\Handler\\StreamHandler;\n use Monolog\\Handler\\SyslogHandler;\n use Monolog\\Logger as Monolog;\n@@ -164,6 +165,44 @@ public function testLogManagerCreatesMonologHandlerWithConfiguredFormatter()\n $this->assertSame('Y/m/d--test', $dateFormat->getValue($formatter));\n }\n \n+ public function testLogManagerCreatesMonologHandlerWithProperFormatter()\n+ {\n+ $config = $this->app->make('config');\n+ $config->set('logging.channels.null', [\n+ 'driver' => 'monolog',\n+ 'handler' => NullHandler::class,\n+ 'formatter' => HtmlFormatter::class,\n+ ]);\n+\n+ $manager = new LogManager($this->app);\n+\n+ // create logger with handler specified from configuration\n+ $logger = $manager->channel('null');\n+ $handler = $logger->getLogger()->getHandlers()[0];\n+\n+ if (Monolog::API === 1) {\n+ $this->assertInstanceOf(NullHandler::class, $handler);\n+ $this->assertInstanceOf(HtmlFormatter::class, $handler->getFormatter());\n+ } else {\n+ $this->assertInstanceOf(NullHandler::class, $handler);\n+ }\n+\n+ $config->set('logging.channels.null2', [\n+ 'driver' => 'monolog',\n+ 'handler' => NullHandler::class,\n+ ]);\n+\n+ $logger = $manager->channel('null2');\n+ $handler = $logger->getLogger()->getHandlers()[0];\n+\n+ if (Monolog::API === 1) {\n+ $this->assertInstanceOf(NullHandler::class, $handler);\n+ $this->assertInstanceOf(LineFormatter::class, $handler->getFormatter());\n+ } else {\n+ $this->assertInstanceOf(NullHandler::class, $handler);\n+ }\n+ }\n+\n public function testLogManagerCreateSingleDriverWithConfiguredFormatter()\n {\n $config = $this->app['config'];", "filename": "tests/Log/LogManagerTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 6.0, 5.8\r\n- PHP Version: 7.1\r\n- Database Driver & Version: 6.0, 5.8\r\n\r\n### Description:\r\n\r\nIncompatibility between `assertSoftDeleted` with `softDelete` when you define a custom name column.\r\n\r\n### Steps To Reproduce:\r\n - Create a migration with `softDeletes` method and a different column name. Example: `$table->softDeletes('deleted_date');`.\r\n - Create a model with `SoftDeletes` trait.\r\n - Define the soft delete column: `const DELETED_AT = 'deleted_date';`.\r\n - Create a test that use `assertSoftDeleted` method and check model.", "comments": [ { "body": "Unfortunately yes, the `deleted_at` column is currently hardcoded in the PHPUnit constraint class https://github.com/laravel/framework/blob/v6.0.4/src/Illuminate/Foundation/Testing/Constraints/SoftDeletedInDatabase.php#L54", "created_at": "2019-09-26T21:32:23Z" }, { "body": "Hmm, this indeed seems unwanted.", "created_at": "2019-09-27T10:30:11Z" }, { "body": "PR merged", "created_at": "2019-09-27T14:11:24Z" }, { "body": "Thanks guys.", "created_at": "2019-09-27T19:05:16Z" } ], "number": 30110, "title": "Incompatibility of assertSoftDeleted with softDelete trait" }
{ "body": "This fixes issue #30110 where it isn't possible to use `assertSoftDeleted` if you're using a column name other than `deleted_at`. This allows the custom column name to be passed into the assertion, and it also adds support if you pass in a model instance.\r\n\r\nA few things to note:\r\n\r\n* I updated the model check to also include that it uses the `SoftDeletes` trait. It wasn't required previously but now that we call `getDeletedAtColumn()` we want to be sure that the method will be there. This would be backwards incompatible if you were using this assertion but not using the `SoftDeletes` trait, but I don't think that would be expected behaviour.\r\n\r\n* I've popped `$deletedAtColumn` on as the last argument to the method so as not to break anything. However I have a gut feeling it should rather be between the `$data` and `$connection` arguments. Curious as to your thoughts in regard to this.", "number": 30111, "review_comments": [], "title": "[6.x] Add custom deleted_at column name for assertSoftDeleted" }
{ "commits": [ { "message": "Add custom deleted_at column name for assertSoftDeleted" }, { "message": "Add missing definition" } ], "files": [ { "diff": "@@ -3,6 +3,7 @@\n namespace Illuminate\\Foundation\\Testing\\Concerns;\n \n use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Eloquent\\SoftDeletes;\n use Illuminate\\Foundation\\Testing\\Constraints\\HasInDatabase;\n use Illuminate\\Foundation\\Testing\\Constraints\\SoftDeletedInDatabase;\n use Illuminate\\Support\\Arr;\n@@ -52,21 +53,34 @@ protected function assertDatabaseMissing($table, array $data, $connection = null\n * @param \\Illuminate\\Database\\Eloquent\\Model|string $table\n * @param array $data\n * @param string|null $connection\n+ * @param string|null $deletedAtColumn\n * @return $this\n */\n- protected function assertSoftDeleted($table, array $data = [], $connection = null)\n+ protected function assertSoftDeleted($table, array $data = [], $connection = null, $deletedAtColumn = 'deleted_at')\n {\n- if ($table instanceof Model) {\n- return $this->assertSoftDeleted($table->getTable(), [$table->getKeyName() => $table->getKey()], $table->getConnectionName());\n+ if ($this->isSoftDeletableModel($table)) {\n+ return $this->assertSoftDeleted($table->getTable(), [$table->getKeyName() => $table->getKey()], $table->getConnectionName(), $table->getDeletedAtColumn());\n }\n \n $this->assertThat(\n- $table, new SoftDeletedInDatabase($this->getConnection($connection), $data)\n+ $table, new SoftDeletedInDatabase($this->getConnection($connection), $data, $deletedAtColumn)\n );\n \n return $this;\n }\n \n+ /**\n+ * Determine if the argument is a soft deletable model.\n+ *\n+ * @param mixed $model\n+ * @return bool\n+ */\n+ protected function isSoftDeletableModel($model)\n+ {\n+ return $model instanceof Model\n+ && in_array(SoftDeletes::class, class_uses_recursive($model));\n+ }\n+\n /**\n * Get the database connection.\n *", "filename": "src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php", "status": "modified" }, { "diff": "@@ -28,18 +28,28 @@ class SoftDeletedInDatabase extends Constraint\n */\n protected $data;\n \n+ /**\n+ * The name of the column that indicates soft deletion has occurred.\n+ *\n+ * @var string\n+ */\n+ protected $deletedAtColumn;\n+\n /**\n * Create a new constraint instance.\n *\n * @param \\Illuminate\\Database\\Connection $database\n * @param array $data\n+ * @param string $deletedAtColumn\n * @return void\n */\n- public function __construct(Connection $database, array $data)\n+ public function __construct(Connection $database, array $data, string $deletedAtColumn)\n {\n $this->data = $data;\n \n $this->database = $database;\n+\n+ $this->deletedAtColumn = $deletedAtColumn;\n }\n \n /**\n@@ -51,7 +61,9 @@ public function __construct(Connection $database, array $data)\n public function matches($table): bool\n {\n return $this->database->table($table)\n- ->where($this->data)->whereNotNull('deleted_at')->count() > 0;\n+ ->where($this->data)\n+ ->whereNotNull($this->deletedAtColumn)\n+ ->count() > 0;\n }\n \n /**", "filename": "src/Illuminate/Foundation/Testing/Constraints/SoftDeletedInDatabase.php", "status": "modified" }, { "diff": "@@ -4,6 +4,7 @@\n \n use Illuminate\\Database\\Connection;\n use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Eloquent\\SoftDeletes;\n use Illuminate\\Database\\Query\\Builder;\n use Illuminate\\Foundation\\Testing\\Concerns\\InteractsWithDatabase;\n use Mockery as m;\n@@ -131,13 +132,27 @@ public function testAssertSoftDeletedInDatabaseDoesNotFindModelResults()\n $this->assertSoftDeleted(new ProductStub($this->data));\n }\n \n- protected function mockCountBuilder($countResult)\n+ public function testAssertSoftDeletedInDatabaseDoesNotFindModelWithCustomColumnResults()\n+ {\n+ $this->expectException(ExpectationFailedException::class);\n+ $this->expectExceptionMessage('The table is empty.');\n+\n+ $this->data = ['id' => 1];\n+\n+ $builder = $this->mockCountBuilder(0, 'trashed_at');\n+\n+ $builder->shouldReceive('get')->andReturn(collect());\n+\n+ $this->assertSoftDeleted(new CustomProductStub($this->data));\n+ }\n+\n+ protected function mockCountBuilder($countResult, $deletedAtColumn = 'deleted_at')\n {\n $builder = m::mock(Builder::class);\n \n $builder->shouldReceive('where')->with($this->data)->andReturnSelf();\n \n- $builder->shouldReceive('whereNotNull')->with('deleted_at')->andReturnSelf();\n+ $builder->shouldReceive('whereNotNull')->with($deletedAtColumn)->andReturnSelf();\n \n $builder->shouldReceive('count')->andReturn($countResult);\n \n@@ -156,7 +171,14 @@ protected function getConnection()\n \n class ProductStub extends Model\n {\n+ use SoftDeletes;\n+\n protected $table = 'products';\n \n protected $guarded = [];\n }\n+\n+class CustomProductStub extends ProductStub\n+{\n+ const DELETED_AT = 'trashed_at';\n+}", "filename": "tests/Foundation/FoundationInteractsWithDatabaseTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.*\r\n- PHP Version: 7.2.*\r\n\r\n### Description:\r\nThere is a bug in **validateDimensions** public method in\r\nframework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php\r\n\r\n`public function validateDimensions($attribute, $value, $parameters)\r\n {\r\n if ($this->isValidFileInstance($value) && $value->getClientMimeType() === 'image/svg+xml') {\r\n return true;\r\n }`\r\n\r\nisValidFileInstance() method allows 2 kind of files:\r\nSymfony\\Component\\HttpFoundation\\File\\File\r\nand\r\nSymfony\\Component\\HttpFoundation\\File\\UploadedFile\r\n\r\nBut only **UploadedFile** has **getClientMimeType()** method. I suppose it should be changed to **getMimeType()**.\r\n\r\nIn addition to that, according to Symfony documentation:\r\n\r\n>The client mime type is extracted from the request from which the file\r\n>was uploaded, so it should not be considered as a safe value.\r\n>\r\n>For a trusted mime type, use getMimeType() instead (which guesses the mime\r\n>type based on the file content).\r\n\r\n", "comments": [ { "body": "You're correct. This seems like a bug. Appreciating a PR if you could whip one up.", "created_at": "2019-09-12T12:23:03Z" } ], "number": 29962, "title": "Change getClientMimeType() to getMimeType()" }
{ "body": "### The Problem\r\n\r\nWhen a user validates the dimensions of a `Symfony\\Component\\HttpFoundation\\File\\File` via the `Illuminate/Validation/Concerns/ValidatesAttributes` trait the request throws an error within `validateDimensions` because the `getClientMimeType()` method does not exist on the instance.\r\n\r\nOnly `UploadedFile` has the currently used `getClientMimeType()` method.\r\n\r\n\r\n### The Solution\r\n\r\nThis PR fixes that issue by using the `getMimeType()`method that exists on both valid file instances.\r\n\r\n### Additional\r\n\r\nAccording to Symfony documentation:\r\n\r\n> The client mime type is extracted from the request from which the file\r\n> was uploaded, so it should not be considered as a safe value.\r\n>\r\n> For a trusted mime type, use getMimeType() instead (which guesses the mime\r\n> type based on the file content).\r\n\r\n### What does this break?\r\nThe mime type will not be extracted from the request but guessed from the files content. So the uploaded files must be valid. In case of a .svg the file must contain the opening `<xml>` tag otherwise it will be interpreted as `plain/text` and the validation will fail.\r\n\r\nI think that is **not a breaking change**, because uploaded files should – in the past also – always be valid. \r\n\r\n---\r\n\r\nResolves #29962", "number": 30009, "review_comments": [], "title": "[6.x] Allow a symfony file instance in validate dimensions" }
{ "commits": [ { "message": "allow a symfony file instance in validate dimensions" } ], "files": [ { "diff": "@@ -499,7 +499,7 @@ public function validateDigitsBetween($attribute, $value, $parameters)\n */\n public function validateDimensions($attribute, $value, $parameters)\n {\n- if ($this->isValidFileInstance($value) && $value->getClientMimeType() === 'image/svg+xml') {\n+ if ($this->isValidFileInstance($value) && $value->getMimeType() === 'image/svg+xml') {\n return true;\n }\n ", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -2656,6 +2656,12 @@ public function testValidateImageDimensions()\n \n $v = new Validator($trans, ['x' => $uploadedFile], ['x' => 'dimensions:max_width=1,max_height=1']);\n $this->assertTrue($v->passes());\n+\n+ $file = new File(__DIR__.'/fixtures/image.svg', '', 'image/svg+xml', null, null, true);\n+ $trans = $this->getIlluminateArrayTranslator();\n+\n+ $v = new Validator($trans, ['x' => $file], ['x' => 'dimensions:max_width=1,max_height=1']);\n+ $this->assertTrue($v->passes());\n }\n \n /**", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" }, { "diff": "@@ -1,2 +1,3 @@\n+<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"300\" viewBox=\"0 0 400 600\">\n </svg>", "filename": "tests/Validation/fixtures/image.svg", "status": "modified" } ] }
{ "body": "- Laravel Version: **5.8.*** & **6.0.*** (Yes, tested this on both versions to be sure)\r\n- PHP Version: 7.2.22\r\n- Database Driver & Version: not related\r\n\r\n### Description:\r\n\r\nFor some reason, with the paths & files i'll show below, the migrations are returned out of order when the same migrations are in the `vendor/` directory (from a package) and also when they are on `database/migrations/` (if those same migrations are published using the `vendor:publish` command).\r\n\r\nAfter some code sniffing, the culprit so far is the `sortBy` [here](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L461).\r\n\r\n### Steps To Reproduce:\r\n\r\nThe code below is to pretty much simulate what the [getMigrationFiles()](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L457) method does without the last part which is not necessary here, since the response in the end will be wrong too.\r\n\r\nSo this can be placed anywhere on the migrator class.\r\n\r\n```php\r\n$files = [\r\n // Path from a package\r\n \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n\r\n // Path from the app\r\n \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n];\r\n\r\n$files = collect($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n})->dd();\r\n```\r\n\r\nWhen this is ran, it will spit something like this:\r\n\r\n```php\r\nIlluminate\\Support\\Collection^ {#683\r\n #items: array:30 [\r\n 0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n 15 => \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n\r\n 16 => \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n 1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n\r\n 17 => \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n 2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n\r\n 3 => \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n 18 => \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n\r\n 19 => \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n 4 => \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n\r\n 5 => \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n 20 => \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n\r\n 21 => \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n 6 => \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n\r\n 22 => \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n 7 => \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n\r\n 8 => \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n 23 => \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n\r\n 9 => \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n 24 => \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n\r\n 10 => \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n 25 => \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n\r\n 11 => \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n 26 => \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n\r\n 12 => \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n 27 => \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n\r\n 13 => \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n 28 => \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n\r\n 14 => \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n 29 => \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n\r\n ]\r\n}\r\n```\r\n\r\n> Note: I've added a few line breaks between the files combination so it's easier to follow.\r\n\r\nAs you can see, some of the migrations are out of order starting from the index `16` and `1` as the vendor one is coming after the one from the app, which is wrong.\r\n\r\nI would fire a pull request to remove the `sortBy` as it seems to be superfluous there but maybe there was a particular edge case for it 🤷‍♂\r\n\r\nAny pointers?\r\n\r\nThanks!", "comments": [ { "body": "Migrations must be sorted, so that the first created ones are executed first.\r\n\r\n\r\nSo the problem with your migrations are, that they have the same timestamps, so 2019_08_08_100000 will be executed first, no matter if it comes from vendor or database.\r\n\r\nAre you registering and publishing the migrations or why do you have both vendor and app migrations with the same name?\r\n", "created_at": "2019-09-12T08:27:13Z" }, { "body": "> Migrations must be sorted, so that the first created ones are executed first.\r\n\r\nYes, i'm aware of that of course, but as you can see above, they are returned out of order, the vendor ones **should** always come first, regardless if the name is the same or not, which does not happen for all of them.\r\n\r\n> So the problem with your migrations are, that they have the same timestamps, so 2019_08_08_100000 will be executed first, no matter if it comes from vendor or database.\r\n\r\nNo, not really, that's not a problem with my migrations and i guess you missed the point there, which is not the problem with file names or timestamps being the same or even being on vendor and published on the app.\r\n\r\nLaravel allows publishing migrations of packages, even they have the exact same file name and then the paths (from packages or any other custom paths you might want to have) are mixed together with the app database/migrations one [here](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Console/Migrations/BaseCommand.php#L28).\r\n\r\nAs i mentioned on the OP, the problem is that they are being sorted incorrectly. The `glob` method already returns them pretty much sorted, so the `sortBy` is mixing them up again and returning them in a very incorrect order for some of them.\r\n\r\n> Are you registering and publishing the migrations or why do you have both vendor and app migrations with the same name?\r\n\r\nThat's mentioned on the OP, but i'm publishing migrations from a package. Reason for that is that i need to augment a few migrations, for several reasons that are unrelated to this.\r\n\r\nSo yes, this is clearly a bug, because if you pay attention to what's returned, you see that the majority of the migrations are sorted correctly, but a few of them have the incorrect order, which is the problem here.", "created_at": "2019-09-12T09:18:16Z" }, { "body": "Seems like this hasn't been changed within three years so I'd thread carefully with any possible changes. Is it really a problem that the indexes are wrong? Seems like the migrations are still being returned in the proper order?", "created_at": "2019-09-12T10:50:33Z" }, { "body": "> Seems like this hasn't been changed within three years so I'd thread carefully with any possible changes.\r\n\r\nYup, it hasn't changed in a while, but i think i got hit by this before.\r\n\r\n> Is it really a problem that the indexes are wrong?\r\n\r\nI thought about it, reseting the indexes does not seem to fix it, at least what i tried yesterday did not yield different results.\r\n\r\n> Seems like the migrations are still being returned in the proper order?\r\n\r\nWhy do you think that? They are clearly not being returned in the proper order.\r\n\r\nCheck the following ones (which are above too)\r\n\r\n```php\r\n0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n15 => \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n```\r\n\r\n```php\r\n16 => \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n```\r\n\r\n```php\r\n17 => \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n```\r\n\r\nClearly, they are out of order.\r\n\r\n- The first one is correct\r\n- The second one is incorrect\r\n- The third one is also incorrect\r\n\r\nReason i say they are incorrect is because the vendor ones comes after the published migrations, which is not the expected behaviour.\r\n\r\nThen [here](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L463) it's going to map the migrations incorrectly, running the one from `vendor/` instead of the published one.\r\n\r\nDoes it help to properly understand the problem now?\r\n\r\nI can look into a fix if you prefer.", "created_at": "2019-09-12T11:00:24Z" }, { "body": "> Does it help to properly understand the problem now?\r\n\r\nIt does! Thanks for clarifying. \r\n\r\nI agree with you that we should look into this further. Feel free to send in a PR but definitely include some tests for it. \r\n\r\nThanks!", "created_at": "2019-09-12T11:31:29Z" }, { "body": "I got bit by this once a while ago. If I remember correctly, the issue is this:\r\n\r\n```\r\nsortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n```\r\nSo, the `sortBy` functions seems necessary to put the migration files in the correct order under typical use cases. But the way that the items are sorted with the `getMigrationName` method, below, only the `basename` is taken into account. \r\n\r\n```\r\n public function getMigrationName($path)\r\n {\r\n return str_replace('.php', '', basename($path));\r\n }\r\n```\r\n\r\nSo it seems that this method would strip away the `/vendor/billing/resources/migrations/` from the vendor migration file names and the `/database/migrations/` from the \"normal\" migration file names during the sorting process, **which effectively leaves the disparate file names equivalent**. And the apparent random sorting as shown by the OP, may be the result. ", "created_at": "2019-09-12T18:15:10Z" }, { "body": "Yes, that's where i got too @570studio :)\r\n\r\nHopefully i can try to get into this tomorrow or saturday to see if i can find a clean solution for this, but i'm open for ideas/suggestions :)", "created_at": "2019-09-12T18:18:33Z" }, { "body": "So I was initially thinking that this could be solved by adding the `sortByDesc` collection method to sort the full file names (which would include the paths) before the other `sortBy` method was called. That way all of the `vendor/migration` files would appear before the `database/migration` files and the final sorting should work the way the OP desires, like this:\r\n\r\n```\r\n public function getMigrationFiles($paths)\r\n {\r\n return Collection::make($paths)->flatMap(function ($path) {\r\n return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\r\n })->filter()->sortKeysDesc(function ($file) {\r\n return $file; \r\n })->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->values()->keyBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->all();\r\n }\r\n```\r\nBut as I though about it more, some devs, use [custom migration paths](https://laravel.com/docs/6.0/migrations#generating-migrations). And since you can use any naming convention that you like in creating a custom migration path, this change could **potentially** cause those cases some issues. But then again, it would only be a problem if they were using the exact same migration names in their custom path and the regular (or some other) migration path, and their app migration strategy is customized for the current sorting behavior. \r\n\r\nPerhaps a more practical solution is simply to update the name of your migrations, if possible, so that they would be sorted after their vendor counterparts under the current scheme. Or perhaps I am not understanding the issue correctly, in which case, you can disregard pretty much all of this ;)", "created_at": "2019-09-13T12:08:06Z" }, { "body": "> But as I though about it more, some devs, use custom migration paths. And since you can use any naming convention that you like in creating a custom migration path, this change could potentially cause those cases some issues.\r\n\r\nNot seeing this as a problem with Laravel itself, but rather how a person name their migrations. But either way, if the files are sorted better on the Migrator class, the problem i'm having would not be a problem anymore since the application migrations would always come after the vendor or any other paths you might be loading the migrations from.\r\n\r\n> Perhaps a more practical solution is simply to update the name of your migrations\r\n\r\nRenaming the migrations does not solve the problem because you can't rename published migrations that belongs to a package as that would introduce other problems like trying to create the same table twice, since the migrations will be pretty much unique.\r\n\r\n> Or perhaps I am not understanding the issue correctly, in which case, you can disregard pretty much all of this ;)\r\n\r\nNo, your thinking is correct. We just need to figure out a proper (clean if possible heh) way to sort the files without them to be mixed case in the end :)\r\n\r\nThanks for the inputs so far, really appreciate it :)", "created_at": "2019-09-13T12:19:03Z" }, { "body": "@driesvints I have this so far:\r\n\r\n```php\r\npublic function getMigrationFiles($paths)\r\n{\r\n return Collection::make($paths)->map(function ($path) {\r\n $files = Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\r\n\r\n return Collection::make($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->toArray();\r\n })->flatten()->filter()->values()->keyBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->all();\r\n}\r\n```\r\n\r\nBasically instead of doing a `flatMap` i'm doing a `map` and sorting the files for each path in a more \"separated\" way i guess, then files from both paths are combined.\r\n\r\nWith this change, the returned result is what i would expect.\r\n\r\nAny clue on how to test it? Since the end result does not contain any valuable data to assert against i'm afraid. There's the possibility of adding a new method i suppose to return the files before being keyed by.. but i don't know what's preferable here", "created_at": "2019-09-13T18:55:33Z" }, { "body": "@brunogaspar \r\n\r\n> Renaming the migrations does not solve the problem because you can't rename published migrations that belongs to a package as that would introduce other problems like trying to create the same table twice, since the migrations will be pretty much unique.\r\n\r\nSorry if I was unclear, I was suggesting you change the name of **your** migrations, not the vendor migrations. For example, changing the final \"0\" in your migration files (where you have this conflict) to a \"1\" to assure that they are sorted **after** the vendor migration files without making any changes to the framework. \r\n\r\n```\r\n0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n15 => \"/database/migrations/2019_08_08_100001_billing_rename_table_one.php\"\r\n\r\n16 => \"/database/migrations/2019_08_08_200001_billing_rename_table_two.php\"\r\n1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n\r\n17 => \"/database/migrations/2019_08_08_300001_billing_rename_table_three.php\"\r\n2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n```", "created_at": "2019-09-13T20:38:25Z" }, { "body": "> Sorry if I was unclear, I was suggesting you change the name of your migrations, not the vendor migrations. For example, changing the final \"0\" in your migration files (where you have this conflict) to a \"1\" to assure that they are sorted after the vendor migration files without making any changes to the framework.\r\n\r\nOhh sorry, i misunderstood you, i was thinking the other way around, my bad.\r\n\r\nBut to the problem, if i publish the migrations, i shouldn't need to modify any migration file name if i just want to augment them in any way, as that's a bit counter intuitive, in my opinion of course.\r\n\r\nConsidering that i have this problem for a few migrations, not just one, that will be a bit annoying to perform just because the framework has a bug.\r\n\r\nBut either way, that would be of course, a hack, and if there's a possibility to fix this issue, i really would like to have it fixed instead of having to hack around it heh", "created_at": "2019-09-13T20:53:49Z" }, { "body": "Totally makes sense. I agree that the sorting is a bit off, per your OP. \r\n\r\nPerhaps for a test you can try something like below as a starting point. I suggest using the array keys (as the values will be specific to your local setup/location). Also, you may want to add an extra migration file to the current test stub migrations if it will help to clearly define your testing purpose and show that it works correctly. \r\n\r\n```\r\n public function testMigrationsCanSortsFilesFromMultiplePaths()\r\n {\r\n $migrationFileKeys = array_keys($this->migrator->getMigrationFiles([__DIR__.'/migrations/one', __DIR__.'/migrations/two']));\r\n $this->assertEquals(['2016_01_01_000000_create_users_table', '2016_01_01_100000_create_password_resets_table', '2016_01_01_200000_create_flights_table'], $migrationFileKeys);\r\n }\r\n```\r\n\r\nThat being said, I'm not 100% understanding the logic of the `map`->`sort`->`flatten` strategy you outline below. I get that it works in your scenario, but I'm confused as to what dictates the order in which the migration paths will be sorted. \r\n\r\nOne last question on your specific example. Am I correct in stating that you publish the vendor migrations files from the given package, and that is how you end up with the duplicately named files? I think **this may be a bug within the package (or possibly how the framework handles migrations when published from a vendor)**, because once a package has its vendor migration files published to the app, then the migration path to the vendor/migrations should no longer be run for the exact reason of the issues that you are currently facing. Does that make sense?", "created_at": "2019-09-13T21:31:15Z" }, { "body": "> That being said, I'm not 100% understanding the logic of the map->sort->flatten strategy you outline below. I get that it works in your scenario, but I'm confused as to what dictates the order in which the migration paths will be sorted.\r\n\r\nHere's a slight modified version of the above using the `flatMap` still\r\n\r\n```php\r\nreturn Collection::make($paths)->flatMap(function ($path) {\r\n $files = Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\r\n\r\n return Collection::make($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->toArray();\r\n})->filter()->values()->keyBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n})->all();\r\n```\r\n\r\nNot sure if it can be made a tad simpler..\r\n\r\nBut basically, i'm ordering the files inside the `map` call, instead of ordering them after, which was where the problem was being caused, because it was sorting all the files from all the paths combined.\r\n\r\n> Am I correct in stating that you publish the vendor migrations files from the given package, and that is how you end up with the duplicately named files? \r\n\r\nYes, that's correct.\r\n\r\n> I think this may be a bug within the package (or possibly how the framework handles migrations when published from a vendor), \r\n\r\nNo bug in the package as far as i know. This can in fact happen with any other package.\r\n\r\n> because once a package has its vendor migration files published to the app, then the migration path to the vendor/migrations should no longer be run for the exact reason of the issues that you are currently facing.\r\n\r\nIf the package migrations are published, they will not run during any `php artisan migrate` call, but the framework still needs to do the lookup within all the migration paths, because imagine, you can publish the migrations and delete a couple of the published ones.\r\n\r\nI actually tried this approach, publish all migrations for this package, delete the ones i didn't actually need and keep the ones i wanted to augment. Unfortunately it yields the exact same problem for me :\\", "created_at": "2019-09-13T21:51:36Z" }, { "body": "Fired a pull request for this.", "created_at": "2019-09-13T22:41:22Z" } ], "number": 29964, "title": "[5.8][6.0] Migrations Out of Order" }
{ "body": "For some reason, with the paths & files i'll show below, the migrations are returned out of order when the same migrations are in the `vendor/` directory (from a package) and also when they are on `database/migrations/` (if those same migrations are published using the `vendor:publish` command).\r\n\r\nAfter some code sniffing, the culprit so far is the `sortBy` [here](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L461).\r\n\r\n### Steps To Reproduce:\r\n\r\nThe code below is to pretty much simulate what the [getMigrationFiles()](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L457) method does without the last part which is not necessary here, since the response in the end will be wrong too.\r\n\r\nSo this can be placed anywhere on the migrator class.\r\n\r\n```php\r\n$files = [\r\n // Path from a package\r\n \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n\r\n // Path from the app\r\n \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n];\r\n\r\n$files = collect($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n})->dd();\r\n```\r\n\r\nWhen this is ran, it will spit something like this:\r\n\r\n```php\r\nIlluminate\\Support\\Collection^ {#683\r\n #items: array:30 [\r\n 0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n 15 => \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n\r\n 16 => \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n 1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n\r\n 17 => \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n 2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n\r\n 3 => \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n 18 => \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n\r\n 19 => \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n 4 => \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n\r\n 5 => \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n 20 => \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n\r\n 21 => \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n 6 => \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n\r\n 22 => \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n 7 => \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n\r\n 8 => \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n 23 => \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n\r\n 9 => \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n 24 => \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n\r\n 10 => \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n 25 => \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n\r\n 11 => \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n 26 => \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n\r\n 12 => \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n 27 => \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n\r\n 13 => \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n 28 => \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n\r\n 14 => \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n 29 => \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n\r\n ]\r\n}\r\n```\r\n\r\n> Note: I've added a few line breaks between the files combination so it's easier to follow.\r\n\r\nAs you can see, some of the migrations are out of order starting from the index `16` and `1` as the vendor one is coming after the one from the app, which is wrong.\r\n\r\n> *Note:* There's a whole lot more explanation for this on #29964 too that would be difficult to add to the description here.\r\n\r\nI've added those empty migration \"stubs\" to make ensure i didn't disrupt the other tests and not cause the class already defined on path exception in some cases.\r\n\r\nFixes: #29964 ", "number": 29996, "review_comments": [], "title": "[6.x] Fix Migrations out of order with multiple path with certain filenames" }
{ "commits": [ { "message": "fix: Migrations out of order with multiple path with certain filenames\n\nSigned-off-by: Bruno Gaspar <brunofgaspar1@gmail.com>" } ], "files": [ { "diff": "@@ -458,10 +458,10 @@ public function getMigrationFiles($paths)\n {\n return Collection::make($paths)->flatMap(function ($path) {\n return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\n- })->filter()->sortBy(function ($file) {\n- return $this->getMigrationName($file);\n- })->values()->keyBy(function ($file) {\n+ })->filter()->values()->keyBy(function ($file) {\n return $this->getMigrationName($file);\n+ })->sortBy(function ($file, $key) {\n+ return $key;\n })->all();\n }\n ", "filename": "src/Illuminate/Database/Migrations/Migrator.php", "status": "modified" }, { "diff": "@@ -148,4 +148,26 @@ public function testMigrationsCanBeResetAcrossMultiplePaths()\n $this->assertFalse($this->db->schema()->hasTable('password_resets'));\n $this->assertFalse($this->db->schema()->hasTable('flights'));\n }\n+\n+ public function testMigrationsCanBeProperlySortedAcrossMultiplePaths()\n+ {\n+ $paths = [__DIR__.'/migrations/multi_path/vendor', __DIR__.'/migrations/multi_path/app'];\n+\n+ $migrationsFilesFullPaths = array_values($this->migrator->getMigrationFiles($paths));\n+\n+ $expected = [\n+ __DIR__.'/migrations/multi_path/app/2016_01_01_000000_create_users_table.php', // This file was not created on the \"vendor\" directory on purpose\n+ __DIR__.'/migrations/multi_path/vendor/2016_01_01_200000_create_flights_table.php', // This file was not created on the \"app\" directory on purpose\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000001_rename_table_one.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000002_rename_table_two.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000003_rename_table_three.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000004_rename_table_four.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000005_create_table_one.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000006_create_table_two.php',\n+ __DIR__.'/migrations/multi_path/vendor/2019_08_08_000007_create_table_three.php', // This file was not created on the \"app\" directory on purpose\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000008_create_table_four.php',\n+ ];\n+\n+ $this->assertEquals($expected, $migrationsFilesFullPaths);\n+ }\n }", "filename": "tests/Database/DatabaseMigratorIntegrationTest.php", "status": "modified" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2016_01_01_000000_create_users_table.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000001_rename_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000002_rename_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000003_rename_table_three.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000004_rename_table_four.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000005_create_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000006_create_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000008_create_table_four.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2016_01_01_200000_create_flights_table.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000001_rename_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000002_rename_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000003_rename_table_three.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000004_rename_table_four.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000005_create_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000006_create_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000007_create_table_three.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000008_create_table_four.php", "status": "added" } ] }
{ "body": "- Laravel Version: 5.8.*\r\n- PHP Version: 7.2.*\r\n\r\n### Description:\r\nThere is a bug in **validateDimensions** public method in\r\nframework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php\r\n\r\n`public function validateDimensions($attribute, $value, $parameters)\r\n {\r\n if ($this->isValidFileInstance($value) && $value->getClientMimeType() === 'image/svg+xml') {\r\n return true;\r\n }`\r\n\r\nisValidFileInstance() method allows 2 kind of files:\r\nSymfony\\Component\\HttpFoundation\\File\\File\r\nand\r\nSymfony\\Component\\HttpFoundation\\File\\UploadedFile\r\n\r\nBut only **UploadedFile** has **getClientMimeType()** method. I suppose it should be changed to **getMimeType()**.\r\n\r\nIn addition to that, according to Symfony documentation:\r\n\r\n>The client mime type is extracted from the request from which the file\r\n>was uploaded, so it should not be considered as a safe value.\r\n>\r\n>For a trusted mime type, use getMimeType() instead (which guesses the mime\r\n>type based on the file content).\r\n\r\n", "comments": [ { "body": "You're correct. This seems like a bug. Appreciating a PR if you could whip one up.", "created_at": "2019-09-12T12:23:03Z" } ], "number": 29962, "title": "Change getClientMimeType() to getMimeType()" }
{ "body": "As @boobooking mentioned in #29962 \r\n\r\nIlluminate/Validation/Concerns/ValidatesAttributes::isValidFileInstance allows an instance of Symfony\\Component\\HttpFoundation\\File\\UploadedFile as well as Symfony\\Component\\HttpFoundation\\File\\File. But the method getClientMimeType – that is called by validating dimensions – only exists on UploadedFile.\r\n\r\nThis PR fixes this issue by using the getMimeType method that exists on both objects.\r\n\r\nresolve #29962\r\n", "number": 29994, "review_comments": [], "title": "allow a symfony file instance in validate dimensions" }
{ "commits": [ { "message": "allow a symfony file instance in validate diminsions\n\nfix #29962" } ], "files": [ { "diff": "@@ -499,7 +499,7 @@ public function validateDigitsBetween($attribute, $value, $parameters)\n */\n public function validateDimensions($attribute, $value, $parameters)\n {\n- if ($this->isValidFileInstance($value) && $value->getClientMimeType() === 'image/svg+xml') {\n+ if ($this->isValidFileInstance($value) && $value->getMimeType() === 'image/svg') {\n return true;\n }\n ", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -2603,11 +2603,17 @@ public function testValidateImageDimensions()\n $this->assertTrue($v->passes());\n \n // Ensure svg images always pass as size is irreleveant\n- $uploadedFile = new UploadedFile(__DIR__.'/fixtures/image.svg', '', 'image/svg+xml', null, null, true);\n+ $uploadedFile = new UploadedFile(__DIR__.'/fixtures/image.svg', '', 'image/svg', null, null, true);\n $trans = $this->getIlluminateArrayTranslator();\n \n $v = new Validator($trans, ['x' => $uploadedFile], ['x' => 'dimensions:max_width=1,max_height=1']);\n $this->assertTrue($v->passes());\n+\n+ $file = new File(__DIR__.'/fixtures/image.svg', '', 'image/svg', null, null, true);\n+ $trans = $this->getIlluminateArrayTranslator();\n+\n+ $v = new Validator($trans, ['x' => $file], ['x' => 'dimensions:max_width=1,max_height=1']);\n+ $this->assertTrue($v->passes());\n }\n \n /**", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: **5.8.*** & **6.0.*** (Yes, tested this on both versions to be sure)\r\n- PHP Version: 7.2.22\r\n- Database Driver & Version: not related\r\n\r\n### Description:\r\n\r\nFor some reason, with the paths & files i'll show below, the migrations are returned out of order when the same migrations are in the `vendor/` directory (from a package) and also when they are on `database/migrations/` (if those same migrations are published using the `vendor:publish` command).\r\n\r\nAfter some code sniffing, the culprit so far is the `sortBy` [here](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L461).\r\n\r\n### Steps To Reproduce:\r\n\r\nThe code below is to pretty much simulate what the [getMigrationFiles()](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L457) method does without the last part which is not necessary here, since the response in the end will be wrong too.\r\n\r\nSo this can be placed anywhere on the migrator class.\r\n\r\n```php\r\n$files = [\r\n // Path from a package\r\n \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n\r\n // Path from the app\r\n \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n];\r\n\r\n$files = collect($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n})->dd();\r\n```\r\n\r\nWhen this is ran, it will spit something like this:\r\n\r\n```php\r\nIlluminate\\Support\\Collection^ {#683\r\n #items: array:30 [\r\n 0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n 15 => \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n\r\n 16 => \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n 1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n\r\n 17 => \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n 2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n\r\n 3 => \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n 18 => \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n\r\n 19 => \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n 4 => \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n\r\n 5 => \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n 20 => \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n\r\n 21 => \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n 6 => \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n\r\n 22 => \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n 7 => \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n\r\n 8 => \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n 23 => \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n\r\n 9 => \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n 24 => \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n\r\n 10 => \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n 25 => \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n\r\n 11 => \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n 26 => \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n\r\n 12 => \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n 27 => \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n\r\n 13 => \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n 28 => \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n\r\n 14 => \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n 29 => \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n\r\n ]\r\n}\r\n```\r\n\r\n> Note: I've added a few line breaks between the files combination so it's easier to follow.\r\n\r\nAs you can see, some of the migrations are out of order starting from the index `16` and `1` as the vendor one is coming after the one from the app, which is wrong.\r\n\r\nI would fire a pull request to remove the `sortBy` as it seems to be superfluous there but maybe there was a particular edge case for it 🤷‍♂\r\n\r\nAny pointers?\r\n\r\nThanks!", "comments": [ { "body": "Migrations must be sorted, so that the first created ones are executed first.\r\n\r\n\r\nSo the problem with your migrations are, that they have the same timestamps, so 2019_08_08_100000 will be executed first, no matter if it comes from vendor or database.\r\n\r\nAre you registering and publishing the migrations or why do you have both vendor and app migrations with the same name?\r\n", "created_at": "2019-09-12T08:27:13Z" }, { "body": "> Migrations must be sorted, so that the first created ones are executed first.\r\n\r\nYes, i'm aware of that of course, but as you can see above, they are returned out of order, the vendor ones **should** always come first, regardless if the name is the same or not, which does not happen for all of them.\r\n\r\n> So the problem with your migrations are, that they have the same timestamps, so 2019_08_08_100000 will be executed first, no matter if it comes from vendor or database.\r\n\r\nNo, not really, that's not a problem with my migrations and i guess you missed the point there, which is not the problem with file names or timestamps being the same or even being on vendor and published on the app.\r\n\r\nLaravel allows publishing migrations of packages, even they have the exact same file name and then the paths (from packages or any other custom paths you might want to have) are mixed together with the app database/migrations one [here](https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Console/Migrations/BaseCommand.php#L28).\r\n\r\nAs i mentioned on the OP, the problem is that they are being sorted incorrectly. The `glob` method already returns them pretty much sorted, so the `sortBy` is mixing them up again and returning them in a very incorrect order for some of them.\r\n\r\n> Are you registering and publishing the migrations or why do you have both vendor and app migrations with the same name?\r\n\r\nThat's mentioned on the OP, but i'm publishing migrations from a package. Reason for that is that i need to augment a few migrations, for several reasons that are unrelated to this.\r\n\r\nSo yes, this is clearly a bug, because if you pay attention to what's returned, you see that the majority of the migrations are sorted correctly, but a few of them have the incorrect order, which is the problem here.", "created_at": "2019-09-12T09:18:16Z" }, { "body": "Seems like this hasn't been changed within three years so I'd thread carefully with any possible changes. Is it really a problem that the indexes are wrong? Seems like the migrations are still being returned in the proper order?", "created_at": "2019-09-12T10:50:33Z" }, { "body": "> Seems like this hasn't been changed within three years so I'd thread carefully with any possible changes.\r\n\r\nYup, it hasn't changed in a while, but i think i got hit by this before.\r\n\r\n> Is it really a problem that the indexes are wrong?\r\n\r\nI thought about it, reseting the indexes does not seem to fix it, at least what i tried yesterday did not yield different results.\r\n\r\n> Seems like the migrations are still being returned in the proper order?\r\n\r\nWhy do you think that? They are clearly not being returned in the proper order.\r\n\r\nCheck the following ones (which are above too)\r\n\r\n```php\r\n0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n15 => \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n```\r\n\r\n```php\r\n16 => \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n```\r\n\r\n```php\r\n17 => \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n```\r\n\r\nClearly, they are out of order.\r\n\r\n- The first one is correct\r\n- The second one is incorrect\r\n- The third one is also incorrect\r\n\r\nReason i say they are incorrect is because the vendor ones comes after the published migrations, which is not the expected behaviour.\r\n\r\nThen [here](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L463) it's going to map the migrations incorrectly, running the one from `vendor/` instead of the published one.\r\n\r\nDoes it help to properly understand the problem now?\r\n\r\nI can look into a fix if you prefer.", "created_at": "2019-09-12T11:00:24Z" }, { "body": "> Does it help to properly understand the problem now?\r\n\r\nIt does! Thanks for clarifying. \r\n\r\nI agree with you that we should look into this further. Feel free to send in a PR but definitely include some tests for it. \r\n\r\nThanks!", "created_at": "2019-09-12T11:31:29Z" }, { "body": "I got bit by this once a while ago. If I remember correctly, the issue is this:\r\n\r\n```\r\nsortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n```\r\nSo, the `sortBy` functions seems necessary to put the migration files in the correct order under typical use cases. But the way that the items are sorted with the `getMigrationName` method, below, only the `basename` is taken into account. \r\n\r\n```\r\n public function getMigrationName($path)\r\n {\r\n return str_replace('.php', '', basename($path));\r\n }\r\n```\r\n\r\nSo it seems that this method would strip away the `/vendor/billing/resources/migrations/` from the vendor migration file names and the `/database/migrations/` from the \"normal\" migration file names during the sorting process, **which effectively leaves the disparate file names equivalent**. And the apparent random sorting as shown by the OP, may be the result. ", "created_at": "2019-09-12T18:15:10Z" }, { "body": "Yes, that's where i got too @570studio :)\r\n\r\nHopefully i can try to get into this tomorrow or saturday to see if i can find a clean solution for this, but i'm open for ideas/suggestions :)", "created_at": "2019-09-12T18:18:33Z" }, { "body": "So I was initially thinking that this could be solved by adding the `sortByDesc` collection method to sort the full file names (which would include the paths) before the other `sortBy` method was called. That way all of the `vendor/migration` files would appear before the `database/migration` files and the final sorting should work the way the OP desires, like this:\r\n\r\n```\r\n public function getMigrationFiles($paths)\r\n {\r\n return Collection::make($paths)->flatMap(function ($path) {\r\n return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\r\n })->filter()->sortKeysDesc(function ($file) {\r\n return $file; \r\n })->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->values()->keyBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->all();\r\n }\r\n```\r\nBut as I though about it more, some devs, use [custom migration paths](https://laravel.com/docs/6.0/migrations#generating-migrations). And since you can use any naming convention that you like in creating a custom migration path, this change could **potentially** cause those cases some issues. But then again, it would only be a problem if they were using the exact same migration names in their custom path and the regular (or some other) migration path, and their app migration strategy is customized for the current sorting behavior. \r\n\r\nPerhaps a more practical solution is simply to update the name of your migrations, if possible, so that they would be sorted after their vendor counterparts under the current scheme. Or perhaps I am not understanding the issue correctly, in which case, you can disregard pretty much all of this ;)", "created_at": "2019-09-13T12:08:06Z" }, { "body": "> But as I though about it more, some devs, use custom migration paths. And since you can use any naming convention that you like in creating a custom migration path, this change could potentially cause those cases some issues.\r\n\r\nNot seeing this as a problem with Laravel itself, but rather how a person name their migrations. But either way, if the files are sorted better on the Migrator class, the problem i'm having would not be a problem anymore since the application migrations would always come after the vendor or any other paths you might be loading the migrations from.\r\n\r\n> Perhaps a more practical solution is simply to update the name of your migrations\r\n\r\nRenaming the migrations does not solve the problem because you can't rename published migrations that belongs to a package as that would introduce other problems like trying to create the same table twice, since the migrations will be pretty much unique.\r\n\r\n> Or perhaps I am not understanding the issue correctly, in which case, you can disregard pretty much all of this ;)\r\n\r\nNo, your thinking is correct. We just need to figure out a proper (clean if possible heh) way to sort the files without them to be mixed case in the end :)\r\n\r\nThanks for the inputs so far, really appreciate it :)", "created_at": "2019-09-13T12:19:03Z" }, { "body": "@driesvints I have this so far:\r\n\r\n```php\r\npublic function getMigrationFiles($paths)\r\n{\r\n return Collection::make($paths)->map(function ($path) {\r\n $files = Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\r\n\r\n return Collection::make($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->toArray();\r\n })->flatten()->filter()->values()->keyBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->all();\r\n}\r\n```\r\n\r\nBasically instead of doing a `flatMap` i'm doing a `map` and sorting the files for each path in a more \"separated\" way i guess, then files from both paths are combined.\r\n\r\nWith this change, the returned result is what i would expect.\r\n\r\nAny clue on how to test it? Since the end result does not contain any valuable data to assert against i'm afraid. There's the possibility of adding a new method i suppose to return the files before being keyed by.. but i don't know what's preferable here", "created_at": "2019-09-13T18:55:33Z" }, { "body": "@brunogaspar \r\n\r\n> Renaming the migrations does not solve the problem because you can't rename published migrations that belongs to a package as that would introduce other problems like trying to create the same table twice, since the migrations will be pretty much unique.\r\n\r\nSorry if I was unclear, I was suggesting you change the name of **your** migrations, not the vendor migrations. For example, changing the final \"0\" in your migration files (where you have this conflict) to a \"1\" to assure that they are sorted **after** the vendor migration files without making any changes to the framework. \r\n\r\n```\r\n0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n15 => \"/database/migrations/2019_08_08_100001_billing_rename_table_one.php\"\r\n\r\n16 => \"/database/migrations/2019_08_08_200001_billing_rename_table_two.php\"\r\n1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n\r\n17 => \"/database/migrations/2019_08_08_300001_billing_rename_table_three.php\"\r\n2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n```", "created_at": "2019-09-13T20:38:25Z" }, { "body": "> Sorry if I was unclear, I was suggesting you change the name of your migrations, not the vendor migrations. For example, changing the final \"0\" in your migration files (where you have this conflict) to a \"1\" to assure that they are sorted after the vendor migration files without making any changes to the framework.\r\n\r\nOhh sorry, i misunderstood you, i was thinking the other way around, my bad.\r\n\r\nBut to the problem, if i publish the migrations, i shouldn't need to modify any migration file name if i just want to augment them in any way, as that's a bit counter intuitive, in my opinion of course.\r\n\r\nConsidering that i have this problem for a few migrations, not just one, that will be a bit annoying to perform just because the framework has a bug.\r\n\r\nBut either way, that would be of course, a hack, and if there's a possibility to fix this issue, i really would like to have it fixed instead of having to hack around it heh", "created_at": "2019-09-13T20:53:49Z" }, { "body": "Totally makes sense. I agree that the sorting is a bit off, per your OP. \r\n\r\nPerhaps for a test you can try something like below as a starting point. I suggest using the array keys (as the values will be specific to your local setup/location). Also, you may want to add an extra migration file to the current test stub migrations if it will help to clearly define your testing purpose and show that it works correctly. \r\n\r\n```\r\n public function testMigrationsCanSortsFilesFromMultiplePaths()\r\n {\r\n $migrationFileKeys = array_keys($this->migrator->getMigrationFiles([__DIR__.'/migrations/one', __DIR__.'/migrations/two']));\r\n $this->assertEquals(['2016_01_01_000000_create_users_table', '2016_01_01_100000_create_password_resets_table', '2016_01_01_200000_create_flights_table'], $migrationFileKeys);\r\n }\r\n```\r\n\r\nThat being said, I'm not 100% understanding the logic of the `map`->`sort`->`flatten` strategy you outline below. I get that it works in your scenario, but I'm confused as to what dictates the order in which the migration paths will be sorted. \r\n\r\nOne last question on your specific example. Am I correct in stating that you publish the vendor migrations files from the given package, and that is how you end up with the duplicately named files? I think **this may be a bug within the package (or possibly how the framework handles migrations when published from a vendor)**, because once a package has its vendor migration files published to the app, then the migration path to the vendor/migrations should no longer be run for the exact reason of the issues that you are currently facing. Does that make sense?", "created_at": "2019-09-13T21:31:15Z" }, { "body": "> That being said, I'm not 100% understanding the logic of the map->sort->flatten strategy you outline below. I get that it works in your scenario, but I'm confused as to what dictates the order in which the migration paths will be sorted.\r\n\r\nHere's a slight modified version of the above using the `flatMap` still\r\n\r\n```php\r\nreturn Collection::make($paths)->flatMap(function ($path) {\r\n $files = Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\r\n\r\n return Collection::make($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n })->toArray();\r\n})->filter()->values()->keyBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n})->all();\r\n```\r\n\r\nNot sure if it can be made a tad simpler..\r\n\r\nBut basically, i'm ordering the files inside the `map` call, instead of ordering them after, which was where the problem was being caused, because it was sorting all the files from all the paths combined.\r\n\r\n> Am I correct in stating that you publish the vendor migrations files from the given package, and that is how you end up with the duplicately named files? \r\n\r\nYes, that's correct.\r\n\r\n> I think this may be a bug within the package (or possibly how the framework handles migrations when published from a vendor), \r\n\r\nNo bug in the package as far as i know. This can in fact happen with any other package.\r\n\r\n> because once a package has its vendor migration files published to the app, then the migration path to the vendor/migrations should no longer be run for the exact reason of the issues that you are currently facing.\r\n\r\nIf the package migrations are published, they will not run during any `php artisan migrate` call, but the framework still needs to do the lookup within all the migration paths, because imagine, you can publish the migrations and delete a couple of the published ones.\r\n\r\nI actually tried this approach, publish all migrations for this package, delete the ones i didn't actually need and keep the ones i wanted to augment. Unfortunately it yields the exact same problem for me :\\", "created_at": "2019-09-13T21:51:36Z" }, { "body": "Fired a pull request for this.", "created_at": "2019-09-13T22:41:22Z" } ], "number": 29964, "title": "[5.8][6.0] Migrations Out of Order" }
{ "body": "For some reason, with the paths & files i'll show below, the migrations are returned out of order when the same migrations are in the `vendor/` directory (from a package) and also when they are on `database/migrations/` (if those same migrations are published using the `vendor:publish` command).\r\n\r\nAfter some code sniffing, the culprit so far is the `sortBy` [here](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L461).\r\n\r\n### Steps To Reproduce:\r\n\r\nThe code below is to pretty much simulate what the [getMigrationFiles()](https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Migrations/Migrator.php#L457) method does without the last part which is not necessary here, since the response in the end will be wrong too.\r\n\r\nSo this can be placed anywhere on the migrator class.\r\n\r\n```php\r\n$files = [\r\n // Path from a package\r\n \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n\r\n // Path from the app\r\n \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\",\r\n \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\",\r\n \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\",\r\n \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\",\r\n \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\",\r\n \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\",\r\n\r\n \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\",\r\n \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\",\r\n \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\",\r\n \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\",\r\n \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\",\r\n \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\",\r\n \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\",\r\n \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\",\r\n \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\",\r\n];\r\n\r\n$files = collect($files)->filter()->sortBy(function ($file) {\r\n return $this->getMigrationName($file);\r\n})->dd();\r\n```\r\n\r\nWhen this is ran, it will spit something like this:\r\n\r\n```php\r\nIlluminate\\Support\\Collection^ {#683\r\n #items: array:30 [\r\n 0 => \"/vendor/billing/resources/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n 15 => \"/database/migrations/2019_08_08_100000_billing_rename_table_one.php\"\r\n\r\n 16 => \"/database/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n 1 => \"/vendor/billing/resources/migrations/2019_08_08_200000_billing_rename_table_two.php\"\r\n\r\n 17 => \"/database/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n 2 => \"/vendor/billing/resources/migrations/2019_08_08_300000_billing_rename_table_three.php\"\r\n\r\n 3 => \"/vendor/billing/resources/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n 18 => \"/database/migrations/2019_08_08_400000_billing_rename_table_four.php\"\r\n\r\n 19 => \"/database/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n 4 => \"/vendor/billing/resources/migrations/2019_08_08_500000_billing_rename_table_five.php\"\r\n\r\n 5 => \"/vendor/billing/resources/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n 20 => \"/database/migrations/2019_08_08_600000_billing_rename_table_six.php\"\r\n\r\n 21 => \"/database/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n 6 => \"/vendor/billing/resources/migrations/2019_08_09_100000_billing_create_table_one.php\"\r\n\r\n 22 => \"/database/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n 7 => \"/vendor/billing/resources/migrations/2019_08_09_200000_billing_create_table_two.php\"\r\n\r\n 8 => \"/vendor/billing/resources/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n 23 => \"/database/migrations/2019_08_09_300000_billing_create_table_three.php\"\r\n\r\n 9 => \"/vendor/billing/resources/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n 24 => \"/database/migrations/2019_08_09_400000_billing_create_table_four.php\"\r\n\r\n 10 => \"/vendor/billing/resources/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n 25 => \"/database/migrations/2019_08_09_500000_billing_create_table_five.php\"\r\n\r\n 11 => \"/vendor/billing/resources/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n 26 => \"/database/migrations/2019_08_09_600000_billing_create_table_six.php\"\r\n\r\n 12 => \"/vendor/billing/resources/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n 27 => \"/database/migrations/2019_08_09_700000_billing_create_table_seven.php\"\r\n\r\n 13 => \"/vendor/billing/resources/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n 28 => \"/database/migrations/2019_08_09_800000_billing_create_table_eight.php\"\r\n\r\n 14 => \"/vendor/billing/resources/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n 29 => \"/database/migrations/2019_08_09_900000_billing_create_table_nine.php\"\r\n\r\n ]\r\n}\r\n```\r\n\r\n> Note: I've added a few line breaks between the files combination so it's easier to follow.\r\n\r\nAs you can see, some of the migrations are out of order starting from the index `16` and `1` as the vendor one is coming after the one from the app, which is wrong.\r\n\r\n> *Note:* There's a whole lot more explanation for this on #29964 too that would be difficult to add to the description here.\r\n\r\nI've added those empty migration \"stubs\" to make ensure i didn't disrupt the other tests and not cause the class already defined on path exception in some cases.\r\n\r\nFixes: #29964 ", "number": 29988, "review_comments": [], "title": "[5.8] Fix Migrations out of order with multiple path with certain filenames" }
{ "commits": [ { "message": "fix: Migrations out of order with multiple path with certain filenames\n\nSigned-off-by: Bruno Gaspar <brunofgaspar1@gmail.com>" } ], "files": [ { "diff": "@@ -458,10 +458,10 @@ public function getMigrationFiles($paths)\n {\n return Collection::make($paths)->flatMap(function ($path) {\n return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');\n- })->filter()->sortBy(function ($file) {\n- return $this->getMigrationName($file);\n- })->values()->keyBy(function ($file) {\n+ })->filter()->values()->keyBy(function ($file) {\n return $this->getMigrationName($file);\n+ })->sortBy(function ($file, $key) {\n+ return $key;\n })->all();\n }\n ", "filename": "src/Illuminate/Database/Migrations/Migrator.php", "status": "modified" }, { "diff": "@@ -148,4 +148,26 @@ public function testMigrationsCanBeResetAcrossMultiplePaths()\n $this->assertFalse($this->db->schema()->hasTable('password_resets'));\n $this->assertFalse($this->db->schema()->hasTable('flights'));\n }\n+\n+ public function testMigrationsCanBeProperlySortedAcrossMultiplePaths()\n+ {\n+ $paths = [__DIR__.'/migrations/multi_path/vendor', __DIR__.'/migrations/multi_path/app'];\n+\n+ $migrationsFilesFullPaths = array_values($this->migrator->getMigrationFiles($paths));\n+\n+ $expected = [\n+ __DIR__.'/migrations/multi_path/app/2016_01_01_000000_create_users_table.php', // This file was not created on the \"vendor\" directory on purpose\n+ __DIR__.'/migrations/multi_path/vendor/2016_01_01_200000_create_flights_table.php', // This file was not created on the \"app\" directory on purpose\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000001_rename_table_one.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000002_rename_table_two.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000003_rename_table_three.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000004_rename_table_four.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000005_create_table_one.php',\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000006_create_table_two.php',\n+ __DIR__.'/migrations/multi_path/vendor/2019_08_08_000007_create_table_three.php', // This file was not created on the \"app\" directory on purpose\n+ __DIR__.'/migrations/multi_path/app/2019_08_08_000008_create_table_four.php',\n+ ];\n+\n+ $this->assertEquals($expected, $migrationsFilesFullPaths);\n+ }\n }", "filename": "tests/Database/DatabaseMigratorIntegrationTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,35 @@\n+<?php\n+\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Database\\Migrations\\Migration;\n+\n+class CreateUsersTable extends Migration\n+{\n+ /**\n+ * Run the migrations.\n+ *\n+ * @return void\n+ */\n+ public function up()\n+ {\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('name');\n+ $table->string('email')->unique();\n+ $table->string('password');\n+ $table->rememberToken();\n+ $table->timestamps();\n+ });\n+ }\n+\n+ /**\n+ * Reverse the migrations.\n+ *\n+ * @return void\n+ */\n+ public function down()\n+ {\n+ Schema::dropIfExists('users');\n+ }\n+}", "filename": "tests/Database/migrations/multi_path/app/2016_01_01_000000_create_users_table.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000001_rename_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000002_rename_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000003_rename_table_three.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000004_rename_table_four.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000005_create_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000006_create_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/app/2019_08_08_000008_create_table_four.php", "status": "added" }, { "diff": "@@ -0,0 +1,31 @@\n+<?php\n+\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Database\\Migrations\\Migration;\n+\n+class CreateFlightsTable extends Migration\n+{\n+ /**\n+ * Run the migrations.\n+ *\n+ * @return void\n+ */\n+ public function up()\n+ {\n+ Schema::create('flights', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('name');\n+ });\n+ }\n+\n+ /**\n+ * Reverse the migrations.\n+ *\n+ * @return void\n+ */\n+ public function down()\n+ {\n+ Schema::dropIfExists('flights');\n+ }\n+}", "filename": "tests/Database/migrations/multi_path/vendor/2016_01_01_200000_create_flights_table.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000001_rename_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000002_rename_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000003_rename_table_three.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000004_rename_table_four.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000005_create_table_one.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000006_create_table_two.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000007_create_table_three.php", "status": "added" }, { "diff": "", "filename": "tests/Database/migrations/multi_path/vendor/2019_08_08_000008_create_table_four.php", "status": "added" } ] }
{ "body": "- Laravel Version: 5.7.26\r\n- PHP Version: 7.3.2\r\n- Database Driver & Version:\r\n\r\n### Description:\r\nI`m on Windows 10 x64 System and trying to run a schedule, from cli, to run in background.\r\nRunning scheduled command is displayed but it does not fired.\r\nIf i copying it and running manualy it work like it should.\r\nAny ideea what could be?!\r\n\r\n### Steps To Reproduce:\r\n```$schedule->command('my-command')->everyMinute()->runInBackground();```\r\n\r\n```Running scheduled command: (\"C:\\php-7\\php.exe\" \"artisan\" my-command > \"NUL\" 2>&1 & \"C:\\php-7\\php.exe\" \"artisan\" schedule:finish \"framework\\schedule-47987621c9ff2fa8a91fa554f7471894a3325831\") > \"NUL\" 2>&1 &```", "comments": [ { "body": "I'll need more info and/or code to debug this further. Please post relevant code like models, jobs, commands, notifications, events, listeners, controller methods, routes, etc. You may use https://paste.laravel.io to post larger snippets or just reply with shorter code snippets. Thanks!", "created_at": "2019-02-15T15:18:37Z" }, { "body": "Hi @driesvints . It`s just a simple command run in Kernel.php and a normal command file that write a x.txt in public_path with current date time.\r\n\r\nAs i told, after i run ```php artisan schedule:run``` i receive message regarding running scheduled command but nothing happened (no file is writed to public_path as it should by the command function...).\r\n\r\nSo, if i copy / paste the command outputed by schedule:run, everything is working as expected.\r\nCommand will be executed.", "created_at": "2019-02-15T15:41:19Z" }, { "body": "I don't have the means to test on Windows myself so hoping that someone on windows might be of help here. In the meantime you might have more luck on one of the support channels below. If you do confirm this as a bug please report back.\r\n\r\n- [Laracasts Forums](https://laracasts.com/discuss)\r\n- [Laravel.io Forums](https://laravel.io/forum)\r\n- [Discord](https://discordapp.com/invite/KxwQuKb)\r\n- [Larachat](https://larachat.co)\r\n- [IRC](https://webchat.freenode.net/?nick=laravelnewbie&channels=%23laravel&prompt=1)\r\n- [StackOverflow](https://stackoverflow.com)", "created_at": "2019-02-15T15:44:52Z" }, { "body": "I'll try tomorrow to install a fresh Laravel app, maybe on other Windows machine also and do this simpliest schedule / command test. And i`ll came back with news. ", "created_at": "2019-02-15T15:49:40Z" }, { "body": "@driesvints I come back with some conclusions. I installed a fresh laravel app and created a new command.\r\nAnd get same behaviour. Not runned on background.\r\n\r\n```\r\n<?php\r\n\r\nnamespace App\\Console\\Commands;\r\n\r\nuse Illuminate\\Console\\Command;\r\n\r\nclass MyCommand extends Command\r\n{\r\n /**\r\n * The name and signature of the console command.\r\n *\r\n * @var string\r\n */\r\n protected $signature = 'my:command';\r\n\r\n /**\r\n * The console command description.\r\n *\r\n * @var string\r\n */\r\n protected $description = 'Command description';\r\n\r\n /**\r\n * Create a new command instance.\r\n *\r\n * @return void\r\n */\r\n public function __construct()\r\n {\r\n parent::__construct();\r\n }\r\n\r\n /**\r\n * Execute the console command.\r\n *\r\n * @return mixed\r\n */\r\n public function handle()\r\n {\r\n \\File::append(public_path('x.txt'), date('Y-m-d H:i:s') . \"\\r\\n\");\r\n }\r\n}\r\n```\r\n\r\nand in Kernel i have:\r\n\r\n```\r\n protected function schedule(Schedule $schedule)\r\n {\r\n $schedule->command('my:command')\r\n ->everyMinute()\r\n ->runInBackground();\r\n }\r\n```\r\n\r\nOn ```php artisan schedule:run``` i get:\r\n\r\n```Running scheduled command: (\"C:\\php\\php-7\\php.exe\" \"artisan\" my:command > \"NUL\" 2>&1 & \"C:\\php\\php-7\\php.exe\" \"artisan\" schedule:finish \"framework\\schedule-50fc191aea7ac0d2b86a23a08b17304051384890\") > \"NUL\" 2>&1 &```\r\n\r\nBut command is not Fired!\r\n\r\nIf i manualy run that outputed command, will executed it...\r\n\r\n\r\nAnd to exclude my PC, i installed same stuff on other clean Windows 10 PC and is same..\r\n\r\n", "created_at": "2019-02-19T11:04:36Z" }, { "body": "I'm running into the same issue. Laravel 5.7.28/PHP 7.2.7/Win10\r\n\r\nSchedule:\r\n```\r\n$schedule->command('background')->everyMinute()->runInBackground();\r\n```\r\n\r\n`background` command:\r\n```\r\npublic function handle()\r\n{\r\n logger()->debug('ran background command');\r\n}\r\n```\r\n\r\nRunning `schedule:run` from the console I get:\r\n```\r\nRunning scheduled command: (\"C:\\Program Files\\PHP\\v7.2\\php.exe\" \"artisan\" background > \"NUL\" 2>&1 & \"C:\\Program Files\\PHP\\v7.2\\php.exe\" \"artisan\" schedule:finish \"framework\\schedule-77231983319c8e5f12f54d6ce91f8dc5290b559a\") > \"NUL\" 2>&1 &\r\n```\r\nHowever, the command does not run.\r\n\r\nI don't think this is the correct syntax for spawning a background process on windows, based on [this stackoverflow answer](https://superuser.com/a/591084). I don't have much experience here, so I can't say for certain.", "created_at": "2019-02-27T12:33:13Z" }, { "body": "Additionally, since Symfony Process spawns each process under `cmd /c` (I think the full line is `cmd /V:ON /E:ON /D /C (<command>)`), I'm starting to wonder if the problem is related to using parenthesis for command grouping? \r\n\r\nWhen I test in my (cmd.exe) terminal, this doesn't seem to work:\r\n```\r\ncmd /c (command1 & command2)\r\n```\r\n(where `command1` and `command2` are the respective artisan commands from the `schedule:run` console output shown above)\r\n\r\nbut using quotes as suggested in a comment [here](https://stackoverflow.com/a/8055430/6038111) does appear to work:\r\n``` \r\ncmd /c \"(command1 & command2)\" \r\n```\r\n\r\nI haven't dug deep enough into the Laravel and Symfony Process combination to know whether the grouped command is being quoted this way for `cmd`, but that might be something to investigate if anyone else knows more?", "created_at": "2019-02-27T13:31:15Z" }, { "body": "Ping. ", "created_at": "2019-03-01T19:26:53Z" }, { "body": "@Travis-Britz @oriceon currently a bit swamped and still no option to test on Windows. If you one of you two can whip up a PR with a fix, send it in and the other one confirm it we could merge that in.", "created_at": "2019-03-04T15:24:37Z" }, { "body": "@Travis-Britz sure, it works with quotes but still not run as async. Does not respect that >NUL parameter..\r\n\r\nFor async it necessary start /B, and is fired OK from a cli.\r\n\r\n```start /B cmd /V:ON /E:ON /D /C \"(\"C:\\php-7\\php.exe\" \"C:\\php-7\\test1.php\" && \"C:\\php-7\\php.exe\" \"C:\\php-7\\test2.php\")\" > NUL &```\r\n\r\n\r\nSo, it`s about Symfony Process.\r\n\r\n\r\nI changed \\vendor\\symfony\\process\\Process.php in prepareWindowsCommandLine method:\r\n\r\n```$cmd = 'start /B cmd /V:ON /E:ON /D /C \"('.str_replace(\"\\n\", ' ', $cmd).')\"';```\r\n\r\n\r\nThen fired with:\r\n\r\n```\r\n$command = '\"C:\\php-7\\php.exe\" \"C:\\php-7\\test1.php\" && \"C:\\php-7\\php.exe\" \"C:\\php-7\\test2.php\"';\r\n\r\n$process = Process::fromShellCommandline($command, base_path(), null, null, null)->start();\r\n```\r\n\r\nbut if i run, i get ```proc_open(): CreateProcess failed, error code - 2```\r\n\r\nNow, if i set ```$options['bypass_shell'] = true;``` to false, will fire and execute async as it should...\r\n\r\nWhy with bypass_shell false get that error code ? As i found, it means ```ERROR_FILE_NOT_FOUND The system cannot find the file specified..```\r\n\r\n*** bypass_shell (windows only): bypass cmd.exe shell when set to TRUE", "created_at": "2019-03-06T13:36:03Z" }, { "body": "Same issue for me!", "created_at": "2019-03-24T12:59:58Z" }, { "body": "> Same issue for me!\r\n\r\nI found I workaround I'm using that works (for my needs)\r\nI'm using \r\n`$schedule->exec('start /b php artisan command:name')->everyMinute();`\r\ninstead of \r\n`$schedule->command('command:name')->everyMinute();`\r\n\r\nInside the command I'm using a custom mutex (just install a third part package) that prevents the overlapping manually. In this way the after callback doesn't work as expected (it's run immediately, not waiting for task end), but I don't need it in this moment.\r\n\r\nHope this helps someone before the bug is resolved", "created_at": "2019-03-25T08:51:22Z" }, { "body": "For me the problem solved after I deleted the last & character from this line:\r\n[https://github.com/laravel/framework/blob/ada35036792e7565b1e0cdf30f0fb7da88b41e1f/src/Illuminate/Console/Scheduling/CommandBuilder.php#L56](https://github.com/laravel/framework/blob/ada35036792e7565b1e0cdf30f0fb7da88b41e1f/src/Illuminate/Console/Scheduling/CommandBuilder.php#L56)\r\n\r\nBefore: `.ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &'`\r\nAfter: `.ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 '`\r\n\r\n\r\nSadly as far as I can see the `runInBackground()` is running the command as a foreground process on Windows.\r\nI put `sleep(10)` in my code, and the schedule command just wait 10 seconds before moving on to the next job.\r\n\r\n", "created_at": "2019-05-08T19:42:31Z" }, { "body": "Guys, I made a fix that works for me on windows to run artisan commands in the background. \r\n\r\n```php\r\n// @islandblaze: Fix for Windows\r\nif(windows_os()) {\r\n return 'start /b cmd /c \"(' . $event->command . ' & ' . $finished.')' . $redirect . $output . ' 2>&1\"';\r\n}\r\n```\r\n\r\nI added a check for windows platform and executed the command in a new background process which will also notify Laravel once it's completed (via php artisan schedule:finish {id}). This also redirects any output from `$schedulingEvent->then(Closure)` to the same destination defined in `$schedulingEvent->sendOutputTo($outputPath)`.\r\n\r\nI cloned `Illuminate\\Console\\Scheduling\\CommandBuilder` and added an alias in `config/app.php` to replace the original class with my customized clone `App\\VendorCustom\\Illuminate\\Console\\Scheduling\\CommandBuilder`\r\n\r\n```php\r\n// config/app.php\r\n'aliases' => [\r\n ...\r\n 'Illuminate\\Console\\Scheduling\\CommandBuilder' => \r\n App\\VendorCustom\\Illuminate\\Console\\Scheduling\\CommandBuilder::class,\r\n],\r\n```\r\n\r\nhttps://github.com/laravel/framework/blob/ada35036792e7565b1e0cdf30f0fb7da88b41e1f/src/Illuminate/Console/Scheduling/CommandBuilder.php#L54-L57\r\n\r\n**App\\VendorCustom\\Illuminate\\Console\\Scheduling\\CommandBuilder:**\r\n```php\r\n...\r\nprotected function buildBackgroundCommand(Event $event)\r\n{\r\n $output = ProcessUtils::escapeArgument($event->output);\r\n $redirect = $event->shouldAppendOutput ? ' >> ' : ' > ';\r\n $finished = Application::formatCommandString('schedule:finish').' \"'.$event->mutexName().'\"';\r\n\r\n // @islandblaze: Fix for Windows\r\n if(windows_os()) {\r\n return 'start /b cmd /c \"(' . $event->command . ' & ' . $finished.')' . $redirect . $output . ' 2>&1\"';\r\n }\r\n\r\n // Original return statement for non-windows platforms\r\n return $this->ensureCorrectUser($event, \r\n '('.$event->command.$redirect.$output.' 2>&1 '.(windows_os() ? '&' : ';').' '.$finished.') > ' \r\n .ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &' \r\n );\r\n}\r\n...\r\n````\r\n\r\nI hope this helps someone. Cheers!", "created_at": "2019-07-09T19:07:49Z" } ], "number": 27541, "title": "Schedule runInBackground not fired" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nFixed issue #27541 (thanks for the solution to @islandblaze)", "number": 29825, "review_comments": [], "title": "fixed #27541" }
{ "commits": [ { "message": "fixed #27541" } ], "files": [ { "diff": "@@ -5,6 +5,7 @@\n ### Fixed\n - Fixed `MorphTo::associate()` with custom owner key ([#29767](https://github.com/laravel/framework/pull/29767))\n - Fixed self-referencing `MorphOneOrMany` existence queries ([#29765](https://github.com/laravel/framework/pull/29765))\n+- Fixed Schedule runInBackground not fired on Windows ([#X](https://github.com/laravel/framework/pull/X))\n \n \n ## [v5.8.34 (2019-08-27)](https://github.com/laravel/framework/compare/v5.8.33...v5.8.34)", "filename": "CHANGELOG-5.8.md", "status": "modified" }, { "diff": "@@ -51,6 +51,10 @@ protected function buildBackgroundCommand(Event $event)\n \n $finished = Application::formatCommandString('schedule:finish').' \"'.$event->mutexName().'\"';\n \n+ if(windows_os()) {\n+ return 'start /b cmd /c \"(' . $event->command . ' & ' . $finished.')' . $redirect . $output . ' 2>&1\"';\n+ }\n+\n return $this->ensureCorrectUser($event,\n '('.$event->command.$redirect.$output.' 2>&1 '.(windows_os() ? '&' : ';').' '.$finished.') > '\n .ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &'", "filename": "src/Illuminate/Console/Scheduling/CommandBuilder.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.*\r\n- PHP Version: 7.2.13\r\n- Database Driver & Version: MariaDB 10.3.4 \r\n\r\n### Description:\r\nThe pivot model's id attribute is not accessible inside of the updated() method. It is only accessible in the created method.\r\n\r\n### Steps To Reproduce:\r\n\r\nModelA class:\r\n\r\n```\r\npublic function modelB()\r\n{\r\n return $this->belongsToMany(ModelB::class, 'model_a_model_b', 'model_a_id', 'model_b_id')\r\n ->using(PivotModel::class)\r\n ->withPivot('id', 'prop_1', 'prop_2');\r\n}\r\n```\r\nModelB class:\r\n\r\n```\r\npublic function modelA()\r\n{\r\n return $this->belongsToMany(ModelA::class, 'model_a_model_b', 'model_b_id', 'model_a_id')\r\n ->using(PivotModel::class)\r\n ->withPivot('id', 'prop_1', 'prop_2');\r\n}\r\n```\r\n\r\nPivotModel:\r\n\r\n```\r\nuse Illuminate\\Database\\Eloquent\\Relations\\Pivot;\r\n\r\nclass PivotModel extends Pivot\r\n{\r\n public $incrementing = true;\r\n\r\n public static function boot() {\r\n\r\n parent::boot();\r\n\r\n static::created(function ($model) {\r\n dump($model->id); // Accessible\r\n dump($model->toArray()); // The id prop is in the array\r\n });\r\n\r\n static::updated(function ($model) {\r\n dump($model->id); // Not accessible\r\n dump($model->toArray()); // The id prop is not in the array\r\n });\r\n }\r\n}\r\n```\r\n\r\nPivot table migration file\r\n\r\n```\r\nSchema::create('model_a_model_b', function (Blueprint $table) {\r\n $table->increments('id');\r\n $table->unsignedInteger('model_a_id');\r\n $table->unsignedInteger('model_b_id');\r\n $table->string('prop_1');\r\n $table->string('prop_2');\r\n\r\n $table->unique(['model_a_id', 'model_b_id'], 'model_a_id_model_b_id');\r\n\r\n $table->foreign('model_a_id')\r\n ->references('id')->on('model_a')\r\n ->onDelete('cascade')\r\n ;\r\n\r\n $table->foreign('model_b_id')\r\n ->references('id')->on('model_b')\r\n ->onDelete('cascade')\r\n ;\r\n\r\n $table->timestamps();\r\n});\r\n```\r\n\r\nYou can check [my question](https://stackoverflow.com/questions/57562783/cant-access-pivot-models-id-attribute-inside-of-the-staticsaved-method-in) on the SO for more details\r\n\r\n", "comments": [ { "body": "This indeed looks like a bug. Thanks for reporting. Appreciating any help with figuring this out.", "created_at": "2019-08-22T10:17:04Z" }, { "body": "PR was merged", "created_at": "2019-10-11T14:12:14Z" } ], "number": 29678, "title": "Can't get pivot model's id prop on updated event" }
{ "body": "Re-pulling #29720 against 6.0 \r\n\r\n/cc @ralphschindler for feedback\r\n\r\nText from original pull request below\r\n\r\n---\r\nThis PR fixes #29678 and may possibly fix #29636 \r\n\r\n## Problem\r\nCustom pivot classes were missing attributes as well as information on what was changed/dirty when used with a custom updated event. This is happening because in `updateExistingPivotUsingCustomClass()` `save()` is called on a newly generated pivot model rather than the existing attached pivot model. Because of this the \"new\" pivot model is passed into the updating event and it is lacking any other attributes that weren't passed to be updated aside from the keys necessary to perform the update.\r\n\r\nWhen attempting to fix this problem I also ran into another problem which is that `getCurrentlyAttachedPivots()` was generating a pivot object that was missing some information (table, connection, timestamps).\r\n\r\n## Solution\r\nInstead of generating a new pivot object to run save on it is run on the pivot returned from `getCurrentlyAttachedPivots()`, this should retain all the additional attributes that weren't specifically updated in this call.\r\n\r\nIn `getCurrentlyAttachedPivots()` I've essentially copied the instantiation style of `newPivot()` so that the object generated will not just have the attributes from the database but also get the proper table name and connection information.\r\n", "number": 29734, "review_comments": [], "title": "[7.x] Change custom pivot model when used in updated event" }
{ "commits": [ { "message": "Fix pivot when used in updating event" }, { "message": "Moving custom pivot updating events to existing test class" } ], "files": [ { "diff": "@@ -227,14 +227,9 @@ protected function updateExistingPivotUsingCustomClass($id, array $attributes, $\n \n $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;\n \n- $pivot = $this->newPivot([\n- $this->foreignPivotKey => $this->parent->{$this->parentKey},\n- $this->relatedPivotKey => $this->parseId($id),\n- ], true);\n-\n- $pivot->timestamps = in_array($this->updatedAt(), $this->pivotColumns);\n-\n- $pivot->fill($attributes)->save();\n+ if ($updated) {\n+ $pivot->save();\n+ }\n \n if ($touch) {\n $this->touchIfTouching();\n@@ -482,7 +477,9 @@ protected function getCurrentlyAttachedPivots()\n return $this->currentlyAttached ?: $this->newPivotQuery()->get()->map(function ($record) {\n $class = $this->using ? $this->using : Pivot::class;\n \n- return (new $class)->setRawAttributes((array) $record, true);\n+ $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true);\n+\n+ return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey);\n });\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php", "status": "modified" }, { "diff": "@@ -31,6 +31,7 @@ protected function setUp(): void\n Schema::create('project_users', function (Blueprint $table) {\n $table->integer('user_id');\n $table->integer('project_id');\n+ $table->text('permissions')->nullable();\n $table->string('role')->nullable();\n });\n \n@@ -73,6 +74,52 @@ public function testPivotWithPivotCriteriaTriggerEventsToBeFiredOnCreateUpdateNo\n $project->contributors()->detach($user->id);\n $this->assertEquals([], PivotEventsTestCollaborator::$eventsCalled);\n }\n+\n+ public function testCustomPivotUpdateEventHasExistingAttributes()\n+ {\n+ $_SERVER['pivot_attributes'] = false;\n+\n+ $user = PivotEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = PivotEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar']]);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(\n+ [\n+ 'user_id' => '1',\n+ 'project_id' => '1',\n+ 'permissions' => '[\"foo\",\"bar\"]',\n+ 'role' => 'Lead Developer',\n+ ],\n+ $_SERVER['pivot_attributes']\n+ );\n+ }\n+\n+ public function testCustomPivotUpdateEventHasDirtyCorrect()\n+ {\n+ $_SERVER['pivot_dirty_attributes'] = false;\n+\n+ $user = PivotEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = PivotEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar'], 'role' => 'Developer']);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(['role' => 'Lead Developer'], $_SERVER['pivot_dirty_attributes']);\n+ }\n }\n \n class PivotEventsTestUser extends Model\n@@ -103,6 +150,10 @@ class PivotEventsTestCollaborator extends Pivot\n {\n public $table = 'project_users';\n \n+ protected $casts = [\n+ 'permissions' => 'json',\n+ ];\n+\n public static $eventsCalled = [];\n \n public static function boot()\n@@ -122,6 +173,8 @@ public static function boot()\n });\n \n static::updated(function ($model) {\n+ $_SERVER['pivot_attributes'] = $model->getAttributes();\n+ $_SERVER['pivot_dirty_attributes'] = $model->getDirty();\n static::$eventsCalled[] = 'updated';\n });\n ", "filename": "tests/Integration/Database/EloquentPivotEventsTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.32\r\n- PHP Version: 7.3.1\r\n- Database Driver & Version: PostgreSQL 10.6\r\n\r\n### Description:\r\n\r\nI have a pivot table with some additional attributes. I also defined a custom intermediate model for this pivot to be able to observe relation changes.\r\n\r\n#### Tables example\r\n\r\n|consultants|\r\n|---|\r\nid\r\n...\r\n\r\n|consultancies|\r\n|---|\r\nid\r\n...\r\n\r\n|consultancy_constultant|\r\n|---|\r\nconsultancy_id\r\nconsultant_id\r\nfrom\r\ntill\r\njob_title\r\n\r\nIn ConsultancyConsultantObserver `updated` gets fired and executed. I want to store in history log all changes user made. So I simply call `$model->getChanges()` to get changed attributes. It works on regular eloquent models, but on pivot models I receive an object, that only has relation ids (in my case consultancy_id and consultant_id) as original attributes stored. So it is not possible to fetch old attribute values at this point.\r\n\r\nI tried to debug it, but I could not catch the point, where it happens - I gave up after 2 hours of trying... \r\n\r\n@ralphschindler you seem to be a relevant contributor to the pivot models stuff. May be you can help me\r\n\r\n**UPDATE**: forget to mention. I update pivot values via sync array. Here is a snipped from code\r\n\r\n```php\r\n$consultant->consultancies()->sync([\r\n 3 => [\r\n 'from' => Arr::get($consultancyInput, 'from', null),\r\n 'till' => Arr::get($consultancyInput, 'till', null),\r\n 'job_title' => Arr::get($consultancyInput, 'job_title', null),\r\n ]\r\n]);\r\n```", "comments": [ { "body": "Are you using [`withPivot`](https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models) method on your relationship?\r\n\r\n> By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:\r\n> ```php\r\n> return $this->belongsToMany('App\\Role')->withPivot('column1', 'column2');\r\n> ```", "created_at": "2019-08-19T14:59:12Z" }, { "body": "Probably related to #28690.", "created_at": "2019-08-19T15:20:26Z" }, { "body": "> Are you using withPivot method on your relationship?\r\n\r\nOh sorry, yes, here is the definition of consultants in Consultancy model:\r\n\r\n```php\r\n public function consultants(): BelongsToMany\r\n {\r\n return $this->belongsToMany('App\\Consultant')\r\n ->using(ConsultancyConsultant::class)\r\n ->withPivot('from', 'till', 'job_title')\r\n ->orderBy('consultancy_consultant.from', 'desc');\r\n }\r\n```", "created_at": "2019-08-19T15:29:18Z" }, { "body": "PR was merged", "created_at": "2019-10-11T14:12:23Z" } ], "number": 29636, "title": "[5.8] Pivot Model Events - originals are not set" }
{ "body": "Re-pulling #29720 against 6.0 \r\n\r\n/cc @ralphschindler for feedback\r\n\r\nText from original pull request below\r\n\r\n---\r\nThis PR fixes #29678 and may possibly fix #29636 \r\n\r\n## Problem\r\nCustom pivot classes were missing attributes as well as information on what was changed/dirty when used with a custom updated event. This is happening because in `updateExistingPivotUsingCustomClass()` `save()` is called on a newly generated pivot model rather than the existing attached pivot model. Because of this the \"new\" pivot model is passed into the updating event and it is lacking any other attributes that weren't passed to be updated aside from the keys necessary to perform the update.\r\n\r\nWhen attempting to fix this problem I also ran into another problem which is that `getCurrentlyAttachedPivots()` was generating a pivot object that was missing some information (table, connection, timestamps).\r\n\r\n## Solution\r\nInstead of generating a new pivot object to run save on it is run on the pivot returned from `getCurrentlyAttachedPivots()`, this should retain all the additional attributes that weren't specifically updated in this call.\r\n\r\nIn `getCurrentlyAttachedPivots()` I've essentially copied the instantiation style of `newPivot()` so that the object generated will not just have the attributes from the database but also get the proper table name and connection information.\r\n", "number": 29734, "review_comments": [], "title": "[7.x] Change custom pivot model when used in updated event" }
{ "commits": [ { "message": "Fix pivot when used in updating event" }, { "message": "Moving custom pivot updating events to existing test class" } ], "files": [ { "diff": "@@ -227,14 +227,9 @@ protected function updateExistingPivotUsingCustomClass($id, array $attributes, $\n \n $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;\n \n- $pivot = $this->newPivot([\n- $this->foreignPivotKey => $this->parent->{$this->parentKey},\n- $this->relatedPivotKey => $this->parseId($id),\n- ], true);\n-\n- $pivot->timestamps = in_array($this->updatedAt(), $this->pivotColumns);\n-\n- $pivot->fill($attributes)->save();\n+ if ($updated) {\n+ $pivot->save();\n+ }\n \n if ($touch) {\n $this->touchIfTouching();\n@@ -482,7 +477,9 @@ protected function getCurrentlyAttachedPivots()\n return $this->currentlyAttached ?: $this->newPivotQuery()->get()->map(function ($record) {\n $class = $this->using ? $this->using : Pivot::class;\n \n- return (new $class)->setRawAttributes((array) $record, true);\n+ $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true);\n+\n+ return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey);\n });\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php", "status": "modified" }, { "diff": "@@ -31,6 +31,7 @@ protected function setUp(): void\n Schema::create('project_users', function (Blueprint $table) {\n $table->integer('user_id');\n $table->integer('project_id');\n+ $table->text('permissions')->nullable();\n $table->string('role')->nullable();\n });\n \n@@ -73,6 +74,52 @@ public function testPivotWithPivotCriteriaTriggerEventsToBeFiredOnCreateUpdateNo\n $project->contributors()->detach($user->id);\n $this->assertEquals([], PivotEventsTestCollaborator::$eventsCalled);\n }\n+\n+ public function testCustomPivotUpdateEventHasExistingAttributes()\n+ {\n+ $_SERVER['pivot_attributes'] = false;\n+\n+ $user = PivotEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = PivotEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar']]);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(\n+ [\n+ 'user_id' => '1',\n+ 'project_id' => '1',\n+ 'permissions' => '[\"foo\",\"bar\"]',\n+ 'role' => 'Lead Developer',\n+ ],\n+ $_SERVER['pivot_attributes']\n+ );\n+ }\n+\n+ public function testCustomPivotUpdateEventHasDirtyCorrect()\n+ {\n+ $_SERVER['pivot_dirty_attributes'] = false;\n+\n+ $user = PivotEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = PivotEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar'], 'role' => 'Developer']);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(['role' => 'Lead Developer'], $_SERVER['pivot_dirty_attributes']);\n+ }\n }\n \n class PivotEventsTestUser extends Model\n@@ -103,6 +150,10 @@ class PivotEventsTestCollaborator extends Pivot\n {\n public $table = 'project_users';\n \n+ protected $casts = [\n+ 'permissions' => 'json',\n+ ];\n+\n public static $eventsCalled = [];\n \n public static function boot()\n@@ -122,6 +173,8 @@ public static function boot()\n });\n \n static::updated(function ($model) {\n+ $_SERVER['pivot_attributes'] = $model->getAttributes();\n+ $_SERVER['pivot_dirty_attributes'] = $model->getDirty();\n static::$eventsCalled[] = 'updated';\n });\n ", "filename": "tests/Integration/Database/EloquentPivotEventsTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.31\r\n- PHP Version: 7.2.19\r\n- Database Driver & Version: Redis Cluster 5.0.5, php-extention phpredis 4.3.0\r\n\r\n### Description:\r\nI use Redis Cluster with php-extention phpredis for queues. This worked fine until I added a function call `delay()`.\r\nI noticed that:\r\n- If I switch from cluster to single, the queue works.\r\n- If I switch from phpredis to predis/predis, the queue works.\r\n\r\n### Steps To Reproduce:\r\n```php\r\ndispatch(\r\n (new SomeJob($data))\r\n ->delay(now()->addSeconds(30))\r\n ->onQueue('{some_queue}')\r\n );\r\n```\r\ndatabase.php:\r\n```php\r\n<?php\r\n\r\n$redisConnStr = env('REDIS_CONNECTION', '127.0.0.1:6379');\r\n\r\n$redis = [\r\n 'client' => 'phpredis',\r\n];\r\n\r\n$redisConnections = explode(',', $redisConnStr);\r\nif (count($redisConnections) === 1) {\r\n\r\n $params = explode(':', $redisConnections[0]);\r\n\r\n $redis = array_merge(\r\n $redis,\r\n [\r\n 'cluster' => env('REDIS_CLUSTER', false),\r\n\r\n 'default' => [\r\n 'host' => $params[0] ?? '127.0.0.1',\r\n 'password' => env('REDIS_PASSWORD', null),\r\n 'port' => (int)($params[1] ?? 6379),\r\n 'database' => env('REDIS_DATABASE', 0),\r\n ]\r\n ]\r\n );\r\n}\r\nelse {\r\n $redisCacheCluster = [];\r\n\r\n foreach ($redisConnections as $conn){\r\n $params = explode(':', $conn);\r\n $redisCacheCluster[] = [\r\n 'host' => $params[0] ?? '127.0.0.1',\r\n 'password' => env('REDIS_PASSWORD', null),\r\n 'port' => (int)($params[1] ?? 6379),\r\n ];\r\n }\r\n\r\n $redis = array_merge(\r\n $redis,\r\n [\r\n 'options' => ['cluster' => 'redis'],\r\n 'clusters' => [\r\n 'default' => $redisCacheCluster,\r\n 'cache' => $redisCacheCluster,\r\n ]\r\n ]\r\n );\r\n}\r\n\r\n\r\nreturn [\r\n'default' => env('DB_CONNECTION', 'mysql'),\r\n'connections' => [\r\n'redis' => $redis,\r\n];\r\n```\r\n.env:\r\n```\r\nQUEUE_CONNECTION=redis\r\nREDIS_CONNECTION=ip:port,ip:port\r\nREDIS_DATABASE=0\r\n```\r\nRun:\r\n```\r\nphp artisan queue:work --queue={some_queue} --tries=1\r\n```", "comments": [ { "body": "I found the location of the problem.\r\nFor dispatching job to Redis Cluster used method `Illuminate\\Redis\\Connections\\PhpRedisConnection::zadd()`.\r\nThe method execute this code:\r\n```php\r\nreturn $this->command('rawCommand', $parameters);\r\n```\r\nThe problem is that the interface of function rawCommand() is different for classes Redis and RedisCluster.\r\nRedis:\r\n```php\r\n/**\r\n * Send arbitrary things to the redis server.\r\n * @param string $command Required command to send to the server.\r\n * @param mixed ...$arguments Optional variable amount of arguments to send to the server.\r\n * @return mixed\r\n * @example\r\n * <pre>\r\n * $redis->rawCommand('SET', 'key', 'value'); // bool(true)\r\n * $redis->rawCommand('GET\", 'key'); // string(5) \"value\"\r\n * </pre>\r\n */\r\n public function rawCommand( $command, $arguments ) {}\r\n```\r\nRedisCluster:\r\n```php\r\n/**\r\n * Send arbitrary things to the redis server at the specified node\r\n *\r\n * @param String | array $nodeParams key or [host,port]\r\n * @param String $command Required command to send to the server.\r\n * @param mixed $arguments Optional variable amount of arguments to send to the server.\r\n *\r\n * @return mixed\r\n */\r\n public function rawCommand($nodeParams, $command, $arguments) { }\r\n```\r\nSo I think that method `Illuminate\\Redis\\Connections\\PhpRedisConnection::zadd()` (and maybe some others) must be overwritten in `Illuminate\\Redis\\Connections\\PhpRedisClusterConnection`", "created_at": "2019-08-23T13:55:08Z" }, { "body": "fixed in https://github.com/laravel/framework/pull/31838", "created_at": "2020-03-08T07:52:57Z" } ], "number": 29637, "title": "[5.8] Delayed jobs are not taken to completion" }
{ "body": "Methods Redis::rawCommand() and RedisCluster::rawCommand() has incompatible interface, so methods zadd() and exists() need different realisation for PhpRedisClusterConnection.\r\nMore details in the issue: #29637", "number": 29730, "review_comments": [], "title": "[5.8] Fix problem with methods using executeRaw() using Redis Cluster" }
{ "commits": [ { "message": "Fix problem with methods using executeRaw()\n\nMethods Redis::rawCommand() and RedisCluster::rawCommand() has incompatible interface, so methods zadd() and exists() need different realisation for PhpRedisClusterConnection." }, { "message": "Merge pull request #2 from sera527/sera527-phpredisclusterconnection-fix\n\nFix problem with methods using executeRaw() using Redis Cluster" }, { "message": "code style fix" } ], "files": [ { "diff": "@@ -4,5 +4,53 @@\n \n class PhpRedisClusterConnection extends PhpRedisConnection\n {\n- //\n+ /**\n+ * Add one or more members to a sorted set or update its score if it already exists.\n+ *\n+ * @param string $key\n+ * @param dynamic $dictionary\n+ * @return int\n+ */\n+ public function zadd($key, ...$dictionary)\n+ {\n+ if (is_array(end($dictionary))) {\n+ foreach (array_pop($dictionary) as $member => $score) {\n+ $dictionary[] = $score;\n+ $dictionary[] = $member;\n+ }\n+ }\n+ $key = $this->applyPrefix($key);\n+\n+ return $this->client->zAdd($key, ...$dictionary);\n+ }\n+\n+ /**\n+ * Determine if the given keys exist.\n+ *\n+ * @param dynamic $keys\n+ * @return int\n+ */\n+ public function exists(...$keys)\n+ {\n+ $keys = collect($keys)->map(function ($key) {\n+ return $this->applyPrefix($key);\n+ });\n+\n+ return $keys->reduce(function ($carry, $key) {\n+ return $carry + $this->client->exists($key);\n+ });\n+ }\n+\n+ /**\n+ * Apply prefix to the given key if necessary.\n+ *\n+ * @param string $key\n+ * @return string\n+ */\n+ private function applyPrefix($key)\n+ {\n+ $prefix = (string) $this->client->getOption(\\RedisCluster::OPT_PREFIX);\n+\n+ return $prefix.$key;\n+ }\n }", "filename": "src/Illuminate/Redis/Connections/PhpRedisClusterConnection.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.32\r\n- PHP Version: 7.3.8\r\n- Database Driver & Version: MariaDB 10.2.23\r\n\r\n### Description / Repro Steps:\r\n1. Build a query that leverages where/orWhere\r\n```\r\n User::query()\r\n ->where(function (Builder $query) {\r\n // basic where\r\n })\r\n ->orWhere(function (Builder $query) {\r\n // basic where\r\n })\r\n ->chunkById(50, function (Collection $users) {\r\n // logic\r\n });\r\n```\r\n\r\nThis generates\r\n```\r\nSELECT * FROM … WHERE a OR b AND id > X\r\n```\r\n\r\nWhich when grouped becomes\r\n```\r\nSELECT * FROM … WHERE a OR (b AND id > X)\r\n```\r\n\r\nWhile I think it should be\r\n```\r\nSELECT * FROM … WHERE (a OR b) AND id > X\r\n```\r\n\r\nThis led to a situation where our queue system ran out of bounds and just queued millions of millions of jobs until redis died out.\r\n\r\n### Workaround\r\n```\r\n User::query()\r\n ->where(function (Builder $query) {\r\n $query->where(function (Builder $query) {\r\n // basic where\r\n })\r\n ->orWhere(function (Builder $query) {\r\n // basic where\r\n });\r\n })\r\n ->chunkById(50, function (Collection $users) {\r\n // logic\r\n });\r\n```\r\n\r\nWe basically just shove the logic into a where closure to force the grouping. I think this is a bug or at least unexpected behavior.", "comments": [ { "body": "I agree that Laravel should support this kind of query.", "created_at": "2019-08-20T13:28:46Z" }, { "body": "Closing this since the proposed PR was rejected. This will probably be a no-fix.", "created_at": "2019-08-27T13:35:31Z" }, { "body": "@driesvints I think it may be fixed. The mentioned PR was changing code in some other functions `forPageBeforeId` and `forPageAfterId`. But maybe a PR that fixes inside `chunkById` would be fine, as already suggested by @rgehan ?", "created_at": "2019-09-07T13:54:02Z" }, { "body": "@halaei you can always attempt a new pr. But I'm keeping the issue as a no-fix because Taylor rejected the first attempt and gave his reasons why.", "created_at": "2019-09-09T11:34:10Z" }, { "body": "@driesvints I consider that a straw man. Does that mean that if I start submitting half baked PRs, claiming to fix real issues, that are being rejected that all those issues will be marked “Wont Fix, because the first attempt was rejected”? That does not seem to be right.\r\n\r\nThe argumentation given by Taylor in #29721 might be valid for `forPage(Before|After)Id`, because other query builder methods can be chained. But you cannot chain anything after `chunkById`, because it calls `get` internally:\r\n\r\nhttps://github.com/laravel/framework/blob/438b78d20e888eaa8217144a330aca7850f51912/src/Illuminate/Database/Concerns/BuildsQueries.php#L92\r\n\r\nThe fact that it uses `forPage(Before|After)Id` is an implementation detail that the API user should not need to know. I can't comment on whether #29721 is technically sound, but if changing `forPage(Before|After)Id` is the easiest way to fix *this* issue then it is a net-positive, even if `forPage(Before|After)Id` still misbuilds queries when not using `chunkById`.\r\n\r\nI propose re-opening this issue. It's definitely non-intuitive and potentionally leads to infinite loops if you don't make sure to examine the generated queries. I am specifically using a query builder, because I don't want to do raw SQL.", "created_at": "2019-09-09T12:03:09Z" }, { "body": "About the infinite loop, it wasted a couple of hours of mine 🥴", "created_at": "2019-09-09T12:20:04Z" }, { "body": "def. needs a fix. ", "created_at": "2021-06-29T23:59:23Z" }, { "body": "This issues saved me hours of debugging what the hell is happening with `chunkById` 🙃", "created_at": "2021-09-20T11:40:15Z" }, { "body": "Same problem there", "created_at": "2021-11-30T16:23:09Z" } ], "number": 29655, "title": "chunkById misbuilds query between where/orWhere " }
{ "body": "This PR fixes #29655\r\n\r\nWhen using `chunkById` after `orWhere`, the condition is invalid, as it generates something like `WHERE a OR b AND id > N`, while it should be `WHERE (a OR b) AND id > N`.\r\n\r\n---\r\n\r\nThis fix feels a tad inelegant, as I don't have much experience with how the query builder work internally.\r\n\r\nI've tried using `cloneWithout(['wheres'])` to generate a new query without the original where clause, but it didn't work, and I haven't been able to find out why.\r\n\r\n@staudenmeir you might have some ideas about how we could make that more elegant", "number": 29721, "review_comments": [], "title": "[5.8] Fix `chunkById` when used after `orWhere`" }
{ "commits": [ { "message": "Group the wheres before applying the lastId condition to the query" }, { "message": "Add test case asserting forPageAfterId nests existing where clause" } ], "files": [ { "diff": "@@ -1961,7 +1961,11 @@ public function forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id')\n $this->orders = $this->removeExistingOrdersFor($column);\n \n if (! is_null($lastId)) {\n- $this->where($column, '<', $lastId);\n+ $clonedQuery = clone $this;\n+ $this->wheres = [];\n+ $this->bindings['where'] = [];\n+ $this->addNestedWhereQuery($clonedQuery)\n+ ->where($column, '<', $lastId);\n }\n \n return $this->orderBy($column, 'desc')\n@@ -1981,7 +1985,11 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')\n $this->orders = $this->removeExistingOrdersFor($column);\n \n if (! is_null($lastId)) {\n- $this->where($column, '>', $lastId);\n+ $clonedQuery = clone $this;\n+ $this->wheres = [];\n+ $this->bindings['where'] = [];\n+ $this->addNestedWhereQuery($clonedQuery)\n+ ->where($column, '>', $lastId);\n }\n \n return $this->orderBy($column, 'asc')", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -1105,6 +1105,23 @@ public function testForPageBeforeIdCorrectlyPaginates()\n $this->assertEquals(1, $results->first()->id);\n }\n \n+ public function testForPageBeforeIdCorrectlyNestExistingWhereClauses()\n+ {\n+ EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);\n+ EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);\n+ EloquentTestUser::create(['id' => 3, 'email' => 'jamesotwell@gmail.com']);\n+ EloquentTestUser::create(['id' => 4, 'email' => 'victoriaotwell@gmail.com']);\n+\n+ // Without nesting the query, it would generate something along the lines\n+ // of `WHERE id = 4 OR (id = 1 AND id < 3)`, which would return 2 rows,\n+ // When correctly nested, it generates a proper where clause, such as:\n+ // `WHERE (id = 4 OR id = 1) AND id < 3`, which returns a single row\n+ $results = EloquentTestUser::where('id', 4)->orWhere('id', 1)->forPageBeforeId(15, 3);\n+ $this->assertInstanceOf(Builder::class, $results);\n+ $this->assertEquals(1, $results->count());\n+ $this->assertEquals(1, $results->first()->id);\n+ }\n+\n public function testForPageAfterIdCorrectlyPaginates()\n {\n EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);\n@@ -1119,6 +1136,20 @@ public function testForPageAfterIdCorrectlyPaginates()\n $this->assertEquals(2, $results->first()->id);\n }\n \n+ public function testForPageAfterIdCorrectlyNestExistingWhereClauses()\n+ {\n+ EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);\n+ EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);\n+\n+ // Without nesting the query, it would generate something along the lines\n+ // of `WHERE id = 1 OR (id = 2 AND id > 1)`, which would always return 1.\n+ // When correctly nested, it generates a proper where clause, such as:\n+ // `WHERE (id = 1 OR id = 2) AND id > 1`\n+ $results = EloquentTestUser::where('id', 1)->orWhere('id', 2)->forPageAfterId(15, 1);\n+ $this->assertInstanceOf(Builder::class, $results);\n+ $this->assertEquals(2, $results->first()->id);\n+ }\n+\n public function testMorphToRelationsAcrossDatabaseConnections()\n {\n $item = null;", "filename": "tests/Database/DatabaseEloquentIntegrationTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.*\r\n- PHP Version: 7.2.13\r\n- Database Driver & Version: MariaDB 10.3.4 \r\n\r\n### Description:\r\nThe pivot model's id attribute is not accessible inside of the updated() method. It is only accessible in the created method.\r\n\r\n### Steps To Reproduce:\r\n\r\nModelA class:\r\n\r\n```\r\npublic function modelB()\r\n{\r\n return $this->belongsToMany(ModelB::class, 'model_a_model_b', 'model_a_id', 'model_b_id')\r\n ->using(PivotModel::class)\r\n ->withPivot('id', 'prop_1', 'prop_2');\r\n}\r\n```\r\nModelB class:\r\n\r\n```\r\npublic function modelA()\r\n{\r\n return $this->belongsToMany(ModelA::class, 'model_a_model_b', 'model_b_id', 'model_a_id')\r\n ->using(PivotModel::class)\r\n ->withPivot('id', 'prop_1', 'prop_2');\r\n}\r\n```\r\n\r\nPivotModel:\r\n\r\n```\r\nuse Illuminate\\Database\\Eloquent\\Relations\\Pivot;\r\n\r\nclass PivotModel extends Pivot\r\n{\r\n public $incrementing = true;\r\n\r\n public static function boot() {\r\n\r\n parent::boot();\r\n\r\n static::created(function ($model) {\r\n dump($model->id); // Accessible\r\n dump($model->toArray()); // The id prop is in the array\r\n });\r\n\r\n static::updated(function ($model) {\r\n dump($model->id); // Not accessible\r\n dump($model->toArray()); // The id prop is not in the array\r\n });\r\n }\r\n}\r\n```\r\n\r\nPivot table migration file\r\n\r\n```\r\nSchema::create('model_a_model_b', function (Blueprint $table) {\r\n $table->increments('id');\r\n $table->unsignedInteger('model_a_id');\r\n $table->unsignedInteger('model_b_id');\r\n $table->string('prop_1');\r\n $table->string('prop_2');\r\n\r\n $table->unique(['model_a_id', 'model_b_id'], 'model_a_id_model_b_id');\r\n\r\n $table->foreign('model_a_id')\r\n ->references('id')->on('model_a')\r\n ->onDelete('cascade')\r\n ;\r\n\r\n $table->foreign('model_b_id')\r\n ->references('id')->on('model_b')\r\n ->onDelete('cascade')\r\n ;\r\n\r\n $table->timestamps();\r\n});\r\n```\r\n\r\nYou can check [my question](https://stackoverflow.com/questions/57562783/cant-access-pivot-models-id-attribute-inside-of-the-staticsaved-method-in) on the SO for more details\r\n\r\n", "comments": [ { "body": "This indeed looks like a bug. Thanks for reporting. Appreciating any help with figuring this out.", "created_at": "2019-08-22T10:17:04Z" }, { "body": "PR was merged", "created_at": "2019-10-11T14:12:14Z" } ], "number": 29678, "title": "Can't get pivot model's id prop on updated event" }
{ "body": "This PR fixes #29678 and may possibly fix #29636 \r\n\r\n## Problem\r\nCustom pivot classes were missing attributes as well as information on what was changed/dirty when used with a custom updated event. This is happening because in `updateExistingPivotUsingCustomClass()` `save()` is called on a newly generated pivot model rather than the existing attached pivot model. Because of this the \"new\" pivot model is passed into the updating event and it is lacking any other attributes that weren't passed to be updated aside from the keys necessary to perform the update.\r\n\r\nWhen attempting to fix this problem I also ran into another problem which is that `getCurrentlyAttachedPivots()` was generating a pivot object that was missing some information (table, connection, timestamps).\r\n\r\n## Solution\r\nInstead of generating a new pivot object to run save on it is run on the pivot returned from `getCurrentlyAttachedPivots()`, this should retain all the additional attributes that weren't specifically updated in this call.\r\n\r\nIn `getCurrentlyAttachedPivots()` I've essentially copied the instantiation style of `newPivot()` so that the object generated will not just have the attributes from the database but also get the proper table name and connection information. \r\n", "number": 29720, "review_comments": [], "title": "[5.8] Bugfix custom pivot model when used in updated event" }
{ "commits": [ { "message": "Fix pivot when used in updating event" }, { "message": "Apply fixes from StyleCI" } ], "files": [ { "diff": "@@ -227,10 +227,9 @@ protected function updateExistingPivotUsingCustomClass($id, array $attributes, $\n \n $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;\n \n- $this->newPivot([\n- $this->foreignPivotKey => $this->parent->{$this->parentKey},\n- $this->relatedPivotKey => $this->parseId($id),\n- ], true)->fill($attributes)->save();\n+ if ($updated) {\n+ $pivot->save();\n+ }\n \n if ($touch) {\n $this->touchIfTouching();\n@@ -478,7 +477,9 @@ protected function getCurrentlyAttachedPivots()\n return $this->currentlyAttached ?: $this->newPivotQuery()->get()->map(function ($record) {\n $class = $this->using ? $this->using : Pivot::class;\n \n- return (new $class)->setRawAttributes((array) $record, true);\n+ $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true);\n+\n+ return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey);\n });\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php", "status": "modified" }, { "diff": "@@ -0,0 +1,125 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database;\n+\n+use Illuminate\\Support\\Facades\\Event;\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Database\\Eloquent\\Relations\\Pivot;\n+\n+/**\n+ * @group integration\n+ */\n+class EloquentCustomPivotCustomEventsTest extends DatabaseTestCase\n+{\n+ protected function setUp(): void\n+ {\n+ parent::setUp();\n+\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('email');\n+ });\n+\n+ Schema::create('projects', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('name');\n+ });\n+\n+ Schema::create('project_users', function (Blueprint $table) {\n+ $table->integer('user_id');\n+ $table->integer('project_id');\n+ $table->text('permissions');\n+ $table->string('role')->nullable();\n+ });\n+\n+ Event::listen(CustomPivotEvent::class, function (CustomPivotEvent $customPivotEvent) {\n+ $_SERVER['pivot_attributes'] = $customPivotEvent->pivot->getAttributes();\n+ $_SERVER['pivot_dirty_attributes'] = $customPivotEvent->pivot->getDirty();\n+ });\n+ }\n+\n+ public function testCustomPivotUpdateEventHasExistingAttributes()\n+ {\n+ $_SERVER['pivot_attributes'] = false;\n+\n+ $user = CustomPivotCustomEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = CustomPivotCustomEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar']]);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(\n+ [\n+ 'user_id' => '1',\n+ 'project_id' => '1',\n+ 'permissions' => '[\"foo\",\"bar\"]',\n+ 'role' => 'Lead Developer',\n+ ],\n+ $_SERVER['pivot_attributes']\n+ );\n+ }\n+\n+ public function testCustomPivotUpdateEventHasDirtyCorrect()\n+ {\n+ $_SERVER['pivot_attributes'] = false;\n+\n+ $user = CustomPivotCustomEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = CustomPivotCustomEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar'], 'role' => 'Developer']);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(['role' => 'Lead Developer'], $_SERVER['pivot_dirty_attributes']);\n+ }\n+}\n+\n+class CustomPivotCustomEventsTestUser extends Model\n+{\n+ public $table = 'users';\n+ public $timestamps = false;\n+}\n+\n+class CustomPivotCustomEventsTestProject extends Model\n+{\n+ public $table = 'projects';\n+ public $timestamps = false;\n+\n+ public function collaborators()\n+ {\n+ return $this->belongsToMany(\n+ CustomPivotCustomEventsTestUser::class, 'project_users', 'project_id', 'user_id'\n+ )->using(CustomPivotCustomEventsTestCollaborator::class)->withPivot('role', 'permissions');\n+ }\n+}\n+\n+class CustomPivotCustomEventsTestCollaborator extends Pivot\n+{\n+ public $dispatchesEvents = ['updated' => CustomPivotEvent::class];\n+ protected $casts = [\n+ 'permissions' => 'json',\n+ ];\n+}\n+\n+class CustomPivotEvent\n+{\n+ public $pivot;\n+\n+ public function __construct(CustomPivotCustomEventsTestCollaborator $pivot)\n+ {\n+ $this->pivot = $pivot;\n+ }\n+}", "filename": "tests/Integration/Database/EloquentCustomPivotCustomEventsTest.php", "status": "added" } ] }
{ "body": "- Laravel Version: 5.8.32\r\n- PHP Version: 7.3.1\r\n- Database Driver & Version: PostgreSQL 10.6\r\n\r\n### Description:\r\n\r\nI have a pivot table with some additional attributes. I also defined a custom intermediate model for this pivot to be able to observe relation changes.\r\n\r\n#### Tables example\r\n\r\n|consultants|\r\n|---|\r\nid\r\n...\r\n\r\n|consultancies|\r\n|---|\r\nid\r\n...\r\n\r\n|consultancy_constultant|\r\n|---|\r\nconsultancy_id\r\nconsultant_id\r\nfrom\r\ntill\r\njob_title\r\n\r\nIn ConsultancyConsultantObserver `updated` gets fired and executed. I want to store in history log all changes user made. So I simply call `$model->getChanges()` to get changed attributes. It works on regular eloquent models, but on pivot models I receive an object, that only has relation ids (in my case consultancy_id and consultant_id) as original attributes stored. So it is not possible to fetch old attribute values at this point.\r\n\r\nI tried to debug it, but I could not catch the point, where it happens - I gave up after 2 hours of trying... \r\n\r\n@ralphschindler you seem to be a relevant contributor to the pivot models stuff. May be you can help me\r\n\r\n**UPDATE**: forget to mention. I update pivot values via sync array. Here is a snipped from code\r\n\r\n```php\r\n$consultant->consultancies()->sync([\r\n 3 => [\r\n 'from' => Arr::get($consultancyInput, 'from', null),\r\n 'till' => Arr::get($consultancyInput, 'till', null),\r\n 'job_title' => Arr::get($consultancyInput, 'job_title', null),\r\n ]\r\n]);\r\n```", "comments": [ { "body": "Are you using [`withPivot`](https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models) method on your relationship?\r\n\r\n> By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:\r\n> ```php\r\n> return $this->belongsToMany('App\\Role')->withPivot('column1', 'column2');\r\n> ```", "created_at": "2019-08-19T14:59:12Z" }, { "body": "Probably related to #28690.", "created_at": "2019-08-19T15:20:26Z" }, { "body": "> Are you using withPivot method on your relationship?\r\n\r\nOh sorry, yes, here is the definition of consultants in Consultancy model:\r\n\r\n```php\r\n public function consultants(): BelongsToMany\r\n {\r\n return $this->belongsToMany('App\\Consultant')\r\n ->using(ConsultancyConsultant::class)\r\n ->withPivot('from', 'till', 'job_title')\r\n ->orderBy('consultancy_consultant.from', 'desc');\r\n }\r\n```", "created_at": "2019-08-19T15:29:18Z" }, { "body": "PR was merged", "created_at": "2019-10-11T14:12:23Z" } ], "number": 29636, "title": "[5.8] Pivot Model Events - originals are not set" }
{ "body": "This PR fixes #29678 and may possibly fix #29636 \r\n\r\n## Problem\r\nCustom pivot classes were missing attributes as well as information on what was changed/dirty when used with a custom updated event. This is happening because in `updateExistingPivotUsingCustomClass()` `save()` is called on a newly generated pivot model rather than the existing attached pivot model. Because of this the \"new\" pivot model is passed into the updating event and it is lacking any other attributes that weren't passed to be updated aside from the keys necessary to perform the update.\r\n\r\nWhen attempting to fix this problem I also ran into another problem which is that `getCurrentlyAttachedPivots()` was generating a pivot object that was missing some information (table, connection, timestamps).\r\n\r\n## Solution\r\nInstead of generating a new pivot object to run save on it is run on the pivot returned from `getCurrentlyAttachedPivots()`, this should retain all the additional attributes that weren't specifically updated in this call.\r\n\r\nIn `getCurrentlyAttachedPivots()` I've essentially copied the instantiation style of `newPivot()` so that the object generated will not just have the attributes from the database but also get the proper table name and connection information. \r\n", "number": 29720, "review_comments": [], "title": "[5.8] Bugfix custom pivot model when used in updated event" }
{ "commits": [ { "message": "Fix pivot when used in updating event" }, { "message": "Apply fixes from StyleCI" } ], "files": [ { "diff": "@@ -227,10 +227,9 @@ protected function updateExistingPivotUsingCustomClass($id, array $attributes, $\n \n $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;\n \n- $this->newPivot([\n- $this->foreignPivotKey => $this->parent->{$this->parentKey},\n- $this->relatedPivotKey => $this->parseId($id),\n- ], true)->fill($attributes)->save();\n+ if ($updated) {\n+ $pivot->save();\n+ }\n \n if ($touch) {\n $this->touchIfTouching();\n@@ -478,7 +477,9 @@ protected function getCurrentlyAttachedPivots()\n return $this->currentlyAttached ?: $this->newPivotQuery()->get()->map(function ($record) {\n $class = $this->using ? $this->using : Pivot::class;\n \n- return (new $class)->setRawAttributes((array) $record, true);\n+ $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true);\n+\n+ return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey);\n });\n }\n ", "filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php", "status": "modified" }, { "diff": "@@ -0,0 +1,125 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Integration\\Database;\n+\n+use Illuminate\\Support\\Facades\\Event;\n+use Illuminate\\Support\\Facades\\Schema;\n+use Illuminate\\Database\\Eloquent\\Model;\n+use Illuminate\\Database\\Schema\\Blueprint;\n+use Illuminate\\Database\\Eloquent\\Relations\\Pivot;\n+\n+/**\n+ * @group integration\n+ */\n+class EloquentCustomPivotCustomEventsTest extends DatabaseTestCase\n+{\n+ protected function setUp(): void\n+ {\n+ parent::setUp();\n+\n+ Schema::create('users', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('email');\n+ });\n+\n+ Schema::create('projects', function (Blueprint $table) {\n+ $table->increments('id');\n+ $table->string('name');\n+ });\n+\n+ Schema::create('project_users', function (Blueprint $table) {\n+ $table->integer('user_id');\n+ $table->integer('project_id');\n+ $table->text('permissions');\n+ $table->string('role')->nullable();\n+ });\n+\n+ Event::listen(CustomPivotEvent::class, function (CustomPivotEvent $customPivotEvent) {\n+ $_SERVER['pivot_attributes'] = $customPivotEvent->pivot->getAttributes();\n+ $_SERVER['pivot_dirty_attributes'] = $customPivotEvent->pivot->getDirty();\n+ });\n+ }\n+\n+ public function testCustomPivotUpdateEventHasExistingAttributes()\n+ {\n+ $_SERVER['pivot_attributes'] = false;\n+\n+ $user = CustomPivotCustomEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = CustomPivotCustomEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar']]);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(\n+ [\n+ 'user_id' => '1',\n+ 'project_id' => '1',\n+ 'permissions' => '[\"foo\",\"bar\"]',\n+ 'role' => 'Lead Developer',\n+ ],\n+ $_SERVER['pivot_attributes']\n+ );\n+ }\n+\n+ public function testCustomPivotUpdateEventHasDirtyCorrect()\n+ {\n+ $_SERVER['pivot_attributes'] = false;\n+\n+ $user = CustomPivotCustomEventsTestUser::forceCreate([\n+ 'email' => 'taylor@laravel.com',\n+ ]);\n+\n+ $project = CustomPivotCustomEventsTestProject::forceCreate([\n+ 'name' => 'Test Project',\n+ ]);\n+\n+ $project->collaborators()->attach($user, ['permissions' => ['foo', 'bar'], 'role' => 'Developer']);\n+\n+ $project->collaborators()->updateExistingPivot($user->id, ['role' => 'Lead Developer']);\n+\n+ $this->assertSame(['role' => 'Lead Developer'], $_SERVER['pivot_dirty_attributes']);\n+ }\n+}\n+\n+class CustomPivotCustomEventsTestUser extends Model\n+{\n+ public $table = 'users';\n+ public $timestamps = false;\n+}\n+\n+class CustomPivotCustomEventsTestProject extends Model\n+{\n+ public $table = 'projects';\n+ public $timestamps = false;\n+\n+ public function collaborators()\n+ {\n+ return $this->belongsToMany(\n+ CustomPivotCustomEventsTestUser::class, 'project_users', 'project_id', 'user_id'\n+ )->using(CustomPivotCustomEventsTestCollaborator::class)->withPivot('role', 'permissions');\n+ }\n+}\n+\n+class CustomPivotCustomEventsTestCollaborator extends Pivot\n+{\n+ public $dispatchesEvents = ['updated' => CustomPivotEvent::class];\n+ protected $casts = [\n+ 'permissions' => 'json',\n+ ];\n+}\n+\n+class CustomPivotEvent\n+{\n+ public $pivot;\n+\n+ public function __construct(CustomPivotCustomEventsTestCollaborator $pivot)\n+ {\n+ $this->pivot = $pivot;\n+ }\n+}", "filename": "tests/Integration/Database/EloquentCustomPivotCustomEventsTest.php", "status": "added" } ] }
{ "body": "- Laravel Version: 5.8.31\r\n- PHP Version: 7.3\r\n\r\n### Description:\r\n\r\nWhen using the `lte` or `gte` rules with a field, the custom attribute names aren't being used.\r\n\r\nExpected: \r\n```\r\nThe maximum price must be greater than or equal minimum price.\r\n```\r\n\r\nActual result:\r\n```\r\nThe maximum price must be greater than or equal price.min.\r\n```\r\n\r\nNotice that it not says:\r\n\r\n```\r\nThe price.max must be greater than or equal price.min.\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n\r\n$rules = [\r\n 'price' => ['nullable', 'array', 'size:2'],\r\n 'price.min' => ['nullable', 'numeric', 'min:1', 'lte:price.max'],\r\n 'price.max' => ['nullable', 'numeric', 'min:1', 'gte:price.min'],\r\n];\r\n\r\n// validation attributes\r\n\r\nreturn [\r\n 'price.min' => 'minimum price',\r\n 'price.max' => 'maximum price',\r\n];", "comments": [ { "body": "Does it work when you use `price_min` instead? I think this is probably conflicting with dot notation.", "created_at": "2019-08-08T13:40:01Z" }, { "body": "`price_min` isn't a field on the request. This is the HTML:\r\n\r\n```html\r\n<input type=\"number\" step=\"any\" min=\"1\" name=\"price[min]\">\r\n<input type=\"number\" step=\"any\" min=\"1\" name=\"price[max]\">\r\n```", "created_at": "2019-08-08T16:11:23Z" }, { "body": "@tillkruss I'm trying to figure out if the dots are indeed the issue here so can you try with the `price_min` naming?", "created_at": "2019-08-08T16:14:40Z" }, { "body": "I was just testing that, you're too fast. Same error:\r\n\r\n```\r\nThe maximum price must be greater than or equal price_min.\r\n```\r\n\r\nI'll try simple fields, one moment.", "created_at": "2019-08-08T16:15:16Z" }, { "body": "If the field has a value then I get a better message:\r\n\r\n```\r\nThe maximum price must be greater than or equal 20.\r\n```\r\n\r\nBut if the field is empty, either as array `price[min]` or a regular field `price_min` I get the same message:\r\n\r\n```\r\nThe maximum price must be greater than or equal price.min.\r\nThe maximum price must be greater than or equal price_min.\r\n```\r\n\r\nIn my particular case, the min and max fields are nullable, because it's not a required field.\r\n", "created_at": "2019-08-08T16:18:51Z" }, { "body": "What if you try this in your validation translation file?\r\n\r\n```php\r\nreturn [\r\n 'price' => [\r\n 'min' => 'minimum price',\r\n 'max' => 'maximum price',\r\n ],\r\n];\r\n```", "created_at": "2019-08-08T16:37:24Z" }, { "body": "I did try that initially, but it didn't work:\r\n\r\n```php\r\nreturn [\r\n 'attributes' => [\r\n 'price.min' => 'minimum price',\r\n 'price.max' => 'maximum price',\r\n 'price' => [\r\n 'min' => 'minimum price',\r\n 'max' => 'maximum price',\r\n ],\r\n ],\r\n];\r\n```", "created_at": "2019-08-08T17:47:28Z" }, { "body": "Okay, just tested this with the setup from the original comment and everything works as expected:\r\n\r\n```bash\r\nmaster $ http --json POST test-app.test/foo price:='{\"min\":5, \"max\":4}' ~/Sites/test-app\r\nHTTP/1.1 422 Unprocessable Entity\r\nCache-Control: no-cache, private\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nDate: Fri, 09 Aug 2019 11:58:09 GMT\r\nServer: nginx/1.17.0\r\nSet-Cookie: laravel_session=eyJpdiI6IkxFRXBTQlMxSzIwZW9WRFlCMnd4b2c9PSIsInZhbHVlIjoiRjhmVExTd29oeDc2UmQ3TGlKYmxHbm1yT05oMmNKTzFuWGRWTXNWQzZERWhUcDlWZmlLbnpsVVVqR2RBc2FXRCIsIm1hYyI6ImU1ODVhMDY2ZGQ1NjlkMDUwYjQ3ZGJhYjBhMDYyY2NmNjQwMzQ4MjJlNzdjYTVmNjg3ODA5NTJmNDU5Mzg4NmMifQ%3D%3D; expires=Fri, 09-Aug-2019 11:59:09 GMT; Max-Age=60; path=/; httponly\r\nTransfer-Encoding: chunked\r\nX-Powered-By: PHP/7.3.5\r\n\r\n{\r\n \"errors\": {\r\n \"price.max\": [\r\n \"The maximum price must be greater than or equal 5.\"\r\n ]\r\n },\r\n \"message\": \"The given data was invalid.\"\r\n}\r\n```\r\n\r\nSo not sure if we're missing anything here?", "created_at": "2019-08-09T11:59:28Z" }, { "body": "I do think the default should be `The :attribute must be greater than or equal to :value.` (notices the extra \"to\").", "created_at": "2019-08-09T12:01:12Z" }, { "body": "Correct, now try it with `min` or `max` missing:\r\n\r\n```\r\nhttp --json POST test-app.test/foo price:='{\"min\":null, \"max\":4}' \r\n```", "created_at": "2019-08-09T19:52:56Z" }, { "body": "I can reproduce it now. Not sure what's going wrong here.", "created_at": "2019-08-12T12:27:52Z" } ], "number": 29441, "title": "lte/gte/gt/lt not using custom attribute labels" }
{ "body": "This PR fixes #29441\r\n\r\nConsider these rules:\r\n```\r\n$rules = [\r\n 'min' => 'numeric',\r\n 'max' => 'numeric|gt:min,\r\n];\r\n```\r\n\r\nAnd these custom attributes:\r\n```\r\n$customAttributes = [\r\n 'min' => 'minimum value',\r\n 'max' => 'maximum value',\r\n];\r\n```\r\n\r\nWith the following data:\r\n```\r\n$data = [\r\n 'max' => 10,\r\n];\r\n```\r\n\r\nValidation fails, with the following error message: `The maximum value must be greater than min.`\r\n\r\nIt completely ignored the custom attribute defined for `max`, and the message should be: `The maximum value must be greater than minimum value.`", "number": 29716, "review_comments": [], "title": "[5.8] Use custom attributes in lt/lte/gt/gte rules messages" }
{ "commits": [ { "message": "Add test for using custom attributes with lt/lte/gt/gte rules" }, { "message": "Use displayableValue when replacing :value for lt/lte/gt/gte rules" } ], "files": [ { "diff": "@@ -260,7 +260,7 @@ protected function replaceSize($message, $attribute, $rule, $parameters)\n protected function replaceGt($message, $attribute, $rule, $parameters)\n {\n if (is_null($value = $this->getValue($parameters[0]))) {\n- return str_replace(':value', $parameters[0], $message);\n+ return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message);\n }\n \n return str_replace(':value', $this->getSize($attribute, $value), $message);\n@@ -278,7 +278,7 @@ protected function replaceGt($message, $attribute, $rule, $parameters)\n protected function replaceLt($message, $attribute, $rule, $parameters)\n {\n if (is_null($value = $this->getValue($parameters[0]))) {\n- return str_replace(':value', $parameters[0], $message);\n+ return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message);\n }\n \n return str_replace(':value', $this->getSize($attribute, $value), $message);\n@@ -296,7 +296,7 @@ protected function replaceLt($message, $attribute, $rule, $parameters)\n protected function replaceGte($message, $attribute, $rule, $parameters)\n {\n if (is_null($value = $this->getValue($parameters[0]))) {\n- return str_replace(':value', $parameters[0], $message);\n+ return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message);\n }\n \n return str_replace(':value', $this->getSize($attribute, $value), $message);\n@@ -314,7 +314,7 @@ protected function replaceGte($message, $attribute, $rule, $parameters)\n protected function replaceLte($message, $attribute, $rule, $parameters)\n {\n if (is_null($value = $this->getValue($parameters[0]))) {\n- return str_replace(':value', $parameters[0], $message);\n+ return str_replace(':value', $this->getDisplayableAttribute($parameters[0]), $message);\n }\n \n return str_replace(':value', $this->getSize($attribute, $value), $message);", "filename": "src/Illuminate/Validation/Concerns/ReplacesAttributes.php", "status": "modified" }, { "diff": "@@ -1669,6 +1669,11 @@ public function testValidateGtPlaceHolderIsReplacedProperly()\n $this->assertFalse($v->passes());\n $this->assertEquals(5, $v->messages()->first('items'));\n \n+ $v = new Validator($trans, ['max' => 10], ['min' => 'numeric', 'max' => 'numeric|gt:min'], [], ['min' => 'minimum value', 'max' => 'maximum value']);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+ $this->assertEquals('minimum value', $v->messages()->first('max'));\n+\n $file = $this->getMockBuilder(UploadedFile::class)->setMethods(['getSize', 'isValid'])->setConstructorArgs([__FILE__, false])->getMock();\n $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));\n $file->expects($this->any())->method('isValid')->will($this->returnValue(true));\n@@ -1706,6 +1711,11 @@ public function testValidateLtPlaceHolderIsReplacedProperly()\n $this->assertFalse($v->passes());\n $this->assertEquals(2, $v->messages()->first('items'));\n \n+ $v = new Validator($trans, ['min' => 1], ['min' => 'numeric|lt:max', 'max' => 'numeric'], [], ['min' => 'minimum value', 'max' => 'maximum value']);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+ $this->assertEquals('maximum value', $v->messages()->first('min'));\n+\n $file = $this->getMockBuilder(UploadedFile::class)->setMethods(['getSize', 'isValid'])->setConstructorArgs([__FILE__, false])->getMock();\n $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));\n $file->expects($this->any())->method('isValid')->will($this->returnValue(true));\n@@ -1743,6 +1753,11 @@ public function testValidateGtePlaceHolderIsReplacedProperly()\n $this->assertFalse($v->passes());\n $this->assertEquals(5, $v->messages()->first('items'));\n \n+ $v = new Validator($trans, ['max' => 10], ['min' => 'numeric', 'max' => 'numeric|gte:min'], [], ['min' => 'minimum value', 'max' => 'maximum value']);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+ $this->assertEquals('minimum value', $v->messages()->first('max'));\n+\n $file = $this->getMockBuilder(UploadedFile::class)->setMethods(['getSize', 'isValid'])->setConstructorArgs([__FILE__, false])->getMock();\n $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));\n $file->expects($this->any())->method('isValid')->will($this->returnValue(true));\n@@ -1780,6 +1795,11 @@ public function testValidateLtePlaceHolderIsReplacedProperly()\n $this->assertFalse($v->passes());\n $this->assertEquals(2, $v->messages()->first('items'));\n \n+ $v = new Validator($trans, ['min' => 1], ['min' => 'numeric|lte:max', 'max' => 'numeric'], [], ['min' => 'minimum value', 'max' => 'maximum value']);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+ $this->assertEquals('maximum value', $v->messages()->first('min'));\n+\n $file = $this->getMockBuilder(UploadedFile::class)->setMethods(['getSize', 'isValid'])->setConstructorArgs([__FILE__, false])->getMock();\n $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));\n $file->expects($this->any())->method('isValid')->will($this->returnValue(true));", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.31\r\n- PHP Version: 7.3\r\n\r\n### Description:\r\n\r\nWhen using the `lte` or `gte` rules with a field, the custom attribute names aren't being used.\r\n\r\nExpected: \r\n```\r\nThe maximum price must be greater than or equal minimum price.\r\n```\r\n\r\nActual result:\r\n```\r\nThe maximum price must be greater than or equal price.min.\r\n```\r\n\r\nNotice that it not says:\r\n\r\n```\r\nThe price.max must be greater than or equal price.min.\r\n```\r\n\r\n### Steps To Reproduce:\r\n\r\n```php\r\n\r\n$rules = [\r\n 'price' => ['nullable', 'array', 'size:2'],\r\n 'price.min' => ['nullable', 'numeric', 'min:1', 'lte:price.max'],\r\n 'price.max' => ['nullable', 'numeric', 'min:1', 'gte:price.min'],\r\n];\r\n\r\n// validation attributes\r\n\r\nreturn [\r\n 'price.min' => 'minimum price',\r\n 'price.max' => 'maximum price',\r\n];", "comments": [ { "body": "Does it work when you use `price_min` instead? I think this is probably conflicting with dot notation.", "created_at": "2019-08-08T13:40:01Z" }, { "body": "`price_min` isn't a field on the request. This is the HTML:\r\n\r\n```html\r\n<input type=\"number\" step=\"any\" min=\"1\" name=\"price[min]\">\r\n<input type=\"number\" step=\"any\" min=\"1\" name=\"price[max]\">\r\n```", "created_at": "2019-08-08T16:11:23Z" }, { "body": "@tillkruss I'm trying to figure out if the dots are indeed the issue here so can you try with the `price_min` naming?", "created_at": "2019-08-08T16:14:40Z" }, { "body": "I was just testing that, you're too fast. Same error:\r\n\r\n```\r\nThe maximum price must be greater than or equal price_min.\r\n```\r\n\r\nI'll try simple fields, one moment.", "created_at": "2019-08-08T16:15:16Z" }, { "body": "If the field has a value then I get a better message:\r\n\r\n```\r\nThe maximum price must be greater than or equal 20.\r\n```\r\n\r\nBut if the field is empty, either as array `price[min]` or a regular field `price_min` I get the same message:\r\n\r\n```\r\nThe maximum price must be greater than or equal price.min.\r\nThe maximum price must be greater than or equal price_min.\r\n```\r\n\r\nIn my particular case, the min and max fields are nullable, because it's not a required field.\r\n", "created_at": "2019-08-08T16:18:51Z" }, { "body": "What if you try this in your validation translation file?\r\n\r\n```php\r\nreturn [\r\n 'price' => [\r\n 'min' => 'minimum price',\r\n 'max' => 'maximum price',\r\n ],\r\n];\r\n```", "created_at": "2019-08-08T16:37:24Z" }, { "body": "I did try that initially, but it didn't work:\r\n\r\n```php\r\nreturn [\r\n 'attributes' => [\r\n 'price.min' => 'minimum price',\r\n 'price.max' => 'maximum price',\r\n 'price' => [\r\n 'min' => 'minimum price',\r\n 'max' => 'maximum price',\r\n ],\r\n ],\r\n];\r\n```", "created_at": "2019-08-08T17:47:28Z" }, { "body": "Okay, just tested this with the setup from the original comment and everything works as expected:\r\n\r\n```bash\r\nmaster $ http --json POST test-app.test/foo price:='{\"min\":5, \"max\":4}' ~/Sites/test-app\r\nHTTP/1.1 422 Unprocessable Entity\r\nCache-Control: no-cache, private\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nDate: Fri, 09 Aug 2019 11:58:09 GMT\r\nServer: nginx/1.17.0\r\nSet-Cookie: laravel_session=eyJpdiI6IkxFRXBTQlMxSzIwZW9WRFlCMnd4b2c9PSIsInZhbHVlIjoiRjhmVExTd29oeDc2UmQ3TGlKYmxHbm1yT05oMmNKTzFuWGRWTXNWQzZERWhUcDlWZmlLbnpsVVVqR2RBc2FXRCIsIm1hYyI6ImU1ODVhMDY2ZGQ1NjlkMDUwYjQ3ZGJhYjBhMDYyY2NmNjQwMzQ4MjJlNzdjYTVmNjg3ODA5NTJmNDU5Mzg4NmMifQ%3D%3D; expires=Fri, 09-Aug-2019 11:59:09 GMT; Max-Age=60; path=/; httponly\r\nTransfer-Encoding: chunked\r\nX-Powered-By: PHP/7.3.5\r\n\r\n{\r\n \"errors\": {\r\n \"price.max\": [\r\n \"The maximum price must be greater than or equal 5.\"\r\n ]\r\n },\r\n \"message\": \"The given data was invalid.\"\r\n}\r\n```\r\n\r\nSo not sure if we're missing anything here?", "created_at": "2019-08-09T11:59:28Z" }, { "body": "I do think the default should be `The :attribute must be greater than or equal to :value.` (notices the extra \"to\").", "created_at": "2019-08-09T12:01:12Z" }, { "body": "Correct, now try it with `min` or `max` missing:\r\n\r\n```\r\nhttp --json POST test-app.test/foo price:='{\"min\":null, \"max\":4}' \r\n```", "created_at": "2019-08-09T19:52:56Z" }, { "body": "I can reproduce it now. Not sure what's going wrong here.", "created_at": "2019-08-12T12:27:52Z" } ], "number": 29441, "title": "lte/gte/gt/lt not using custom attribute labels" }
{ "body": "This PR fixes #29441", "number": 29715, "review_comments": [], "title": "Use custom attributes in lt/lte/gt/gte rules messages" }
{ "commits": [ { "message": "implement encoding in PostgresGrammar" }, { "message": "use timing safe comparison" }, { "message": "Use contract instead of email attribute directly" }, { "message": "Merge branch 'master' of https://github.com/o7n/framework" }, { "message": "Make StyleCI happy" }, { "message": "Make StyleCI happy" }, { "message": "CS fixes" }, { "message": "revert PostgresGrammar" }, { "message": "Check datatype correctly in PostgresGrammar" }, { "message": "Add Postgres JsonArray test" }, { "message": "fix StyleCI stuff" }, { "message": "Add tests" }, { "message": "fixed PHPDoc format" }, { "message": "Don't set default message when denying policy, move \"This action is unauthorized\" message to exception." }, { "message": "Use POST method when re-sending email verfication." }, { "message": "Merge pull request #29179 from garygreen/verify-post\n\n[5.9] Use POST method when re-sending email verfication." }, { "message": "Merge pull request #29178 from garygreen/deny-exception-message\n\n[5.9] Don't set default message when denying policy, move \"This action is unauthorized\" message to exception." }, { "message": "Merge pull request #29166 from mathieutu/arrayable-eloquent\n\n[5.9] Convert Arrayable Eloquent casted attributes to Array." }, { "message": "Merge branch 'master' into master" }, { "message": "Merge branch 'master' into issue-28592" }, { "message": "Use contract for email address" }, { "message": "Merge pull request #29146 from iamgergo/master\n\n[5.9] Handle array and object values when updating JSON fields" }, { "message": "Merge branch 'master' into issue-28592" }, { "message": "reverted the doc block spaces to original" }, { "message": "Merge pull request #29209 from SPie/issue-28592\n\n[5.9] Queue cookies with same name and distinct paths" }, { "message": "Merge branch 'master' of https://github.com/o7n/framework into o7n-master" }, { "message": "formatting" }, { "message": "Use QueueManager contract in Worker\n\nwe can depend on `Illuminate\\Contracts\\Queue\\Factory` in the `Illuminate\\Queue\\Worker` instead of the\nconcrete manager instance. This allows for decorating the QueueManager\nwith extra functionality.\n\nThis solves the issues encountered in [27826](https://github.com/laravel/framework/pull/27826) and [#29225](https://github.com/laravel/framework/pull/29225)." }, { "message": "Fixed code style" }, { "message": "Refactor INSERT queries" } ], "files": [ { "diff": "@@ -8,9 +8,6 @@ env:\n matrix:\n fast_finish: true\n include:\n- - php: 7.1\n- - php: 7.1\n- env: SETUP=lowest\n - php: 7.2\n - php: 7.2\n env: SETUP=lowest", "filename": ".travis.yml", "status": "modified" }, { "diff": "@@ -9,7 +9,7 @@\n \n ## About Laravel\n \n-> **Note:** This repository contains the core code of the Laravel framework. If you want to build an application using Laravel 5, visit the main [Laravel repository](https://github.com/laravel/laravel).\n+> **Note:** This repository contains the core code of the Laravel framework. If you want to build an application using Laravel, visit the main [Laravel repository](https://github.com/laravel/laravel).\n \n Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:\n ", "filename": "README.md", "status": "modified" }, { "diff": "@@ -9,7 +9,7 @@ then\n exit 1\n fi\n \n-CURRENT_BRANCH=\"5.8\"\n+CURRENT_BRANCH=\"6.0\"\n VERSION=$1\n \n # Always prepend with \"v\"", "filename": "bin/release.sh", "status": "modified" }, { "diff": "@@ -3,7 +3,7 @@\n set -e\n set -x\n \n-CURRENT_BRANCH=\"5.8\"\n+CURRENT_BRANCH=\"master\"\n \n function split()\n {", "filename": "bin/split.sh", "status": "modified" }, { "diff": "@@ -15,7 +15,7 @@\n }\n ],\n \"require\": {\n- \"php\": \"^7.1.3\",\n+ \"php\": \"^7.2\",\n \"ext-json\": \"*\",\n \"ext-mbstring\": \"*\",\n \"ext-openssl\": \"*\",\n@@ -25,20 +25,20 @@\n \"erusev/parsedown\": \"^1.7\",\n \"league/flysystem\": \"^1.0.8\",\n \"monolog/monolog\": \"^1.12\",\n- \"nesbot/carbon\": \"^1.26.3 || ^2.0\",\n+ \"nesbot/carbon\": \"^2.0\",\n \"opis/closure\": \"^3.1\",\n \"psr/container\": \"^1.0\",\n \"psr/simple-cache\": \"^1.0\",\n \"ramsey/uuid\": \"^3.7\",\n \"swiftmailer/swiftmailer\": \"^6.0\",\n- \"symfony/console\": \"^4.2\",\n- \"symfony/debug\": \"^4.2\",\n- \"symfony/finder\": \"^4.2\",\n- \"symfony/http-foundation\": \"^4.2\",\n- \"symfony/http-kernel\": \"^4.2\",\n- \"symfony/process\": \"^4.2\",\n- \"symfony/routing\": \"^4.2\",\n- \"symfony/var-dumper\": \"^4.2\",\n+ \"symfony/console\": \"^4.3\",\n+ \"symfony/debug\": \"^4.3\",\n+ \"symfony/finder\": \"^4.3\",\n+ \"symfony/http-foundation\": \"^4.3\",\n+ \"symfony/http-kernel\": \"^4.3\",\n+ \"symfony/process\": \"^4.3\",\n+ \"symfony/routing\": \"^4.3\",\n+ \"symfony/var-dumper\": \"^4.3\",\n \"tijsverkoyen/css-to-inline-styles\": \"^2.2.1\",\n \"vlucas/phpdotenv\": \"^3.3\"\n },\n@@ -78,17 +78,18 @@\n \"require-dev\": {\n \"aws/aws-sdk-php\": \"^3.0\",\n \"doctrine/dbal\": \"^2.6\",\n- \"filp/whoops\": \"^2.1.4\",\n+ \"filp/whoops\": \"^2.4\",\n \"guzzlehttp/guzzle\": \"^6.3\",\n \"league/flysystem-cached-adapter\": \"^1.0\",\n \"mockery/mockery\": \"^1.0\",\n \"moontoast/math\": \"^1.1\",\n- \"orchestra/testbench-core\": \"3.8.*\",\n+ \"orchestra/testbench-core\": \"^4.0\",\n \"pda/pheanstalk\": \"^4.0\",\n- \"phpunit/phpunit\": \"^7.5|^8.0\",\n+ \"phpunit/phpunit\": \"^8.0\",\n \"predis/predis\": \"^1.1.1\",\n- \"symfony/css-selector\": \"^4.2\",\n- \"symfony/dom-crawler\": \"^4.2\",\n+ \"symfony/cache\": \"^4.3\",\n+ \"symfony/css-selector\": \"^4.3\",\n+ \"symfony/dom-crawler\": \"^4.3\",\n \"true/punycode\": \"^2.1\"\n },\n \"autoload\": {\n@@ -110,17 +111,17 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"5.8-dev\"\n+ \"dev-master\": \"7.0-dev\"\n }\n },\n \"suggest\": {\n \"ext-pcntl\": \"Required to use all features of the queue worker.\",\n \"ext-posix\": \"Required to use all features of the queue worker.\",\n \"aws/aws-sdk-php\": \"Required to use the SQS queue driver and SES mail driver (^3.0).\",\n \"doctrine/dbal\": \"Required to rename columns and drop SQLite columns (^2.6).\",\n- \"filp/whoops\": \"Required for friendly error pages in development (^2.1.4).\",\n+ \"filp/whoops\": \"Required for friendly error pages in development (^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 (^6.0).\",\n+ \"guzzlehttp/guzzle\": \"Required to use the Mailgun mail driver and the ping methods on schedules (^6.0).\",\n \"laravel/tinker\": \"Required to use the tinker console command (^1.0).\",\n \"league/flysystem-aws-s3-v3\": \"Required to use the Flysystem S3 driver (^1.0).\",\n \"league/flysystem-cached-adapter\": \"Required to use the Flysystem cache (^1.0).\",\n@@ -131,8 +132,9 @@\n \"pda/pheanstalk\": \"Required to use the beanstalk queue driver (^4.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 (^3.0).\",\n- \"symfony/css-selector\": \"Required to use some of the crawler integration testing tools (^4.2).\",\n- \"symfony/dom-crawler\": \"Required to use most of the crawler integration testing tools (^4.2).\",\n+ \"symfony/cache\": \"Required to PSR-6 cache bridge (^4.3).\",\n+ \"symfony/css-selector\": \"Required to use some of the crawler integration testing tools (^4.3).\",\n+ \"symfony/dom-crawler\": \"Required to use most of the crawler integration testing tools (^4.3).\",\n \"symfony/psr-http-message-bridge\": \"Required to use PSR-7 bridging features (^1.1).\",\n \"wildbit/swiftmailer-postmark\": \"Required to use Postmark mail driver (^3.0).\"\n },", "filename": "composer.json", "status": "modified" }, { "diff": "@@ -6,5 +6,58 @@\n \n class AuthorizationException extends Exception\n {\n- //\n+ /**\n+ * The response from the gate.\n+ *\n+ * @var \\Illuminate\\Auth\\Access\\Response\n+ */\n+ protected $response;\n+\n+ /**\n+ * Create a new authorization exception instance.\n+ *\n+ * @param string|null $message\n+ * @param mixed|null $code\n+ * @param \\Exception|null $previous\n+ * @return void\n+ */\n+ public function __construct($message = null, $code = null, Exception $previous = null)\n+ {\n+ parent::__construct($message ?? 'This action is unauthorized.', 0, $previous);\n+\n+ $this->code = $code;\n+ }\n+\n+ /**\n+ * Get the response from the gate.\n+ *\n+ * @return \\Illuminate\\Auth\\Access\\Response\n+ */\n+ public function response()\n+ {\n+ return $this->response;\n+ }\n+\n+ /**\n+ * Set the response from the gate.\n+ *\n+ * @param \\Illuminate\\Auth\\Access\\Response $response\n+ * @return $this\n+ */\n+ public function setResponse($response)\n+ {\n+ $this->response = $response;\n+\n+ return $this;\n+ }\n+\n+ /**\n+ * Create a deny response object from this exception.\n+ *\n+ * @return \\Illuminate\\Auth\\Access\\Response\n+ */\n+ public function toResponse()\n+ {\n+ return Response::deny($this->message, $this->code);\n+ }\n }", "filename": "src/Illuminate/Auth/Access/AuthorizationException.php", "status": "modified" }, { "diff": "@@ -274,11 +274,7 @@ public function denies($ability, $arguments = [])\n public function check($abilities, $arguments = [])\n {\n return collect($abilities)->every(function ($ability) use ($arguments) {\n- try {\n- return (bool) $this->raw($ability, $arguments);\n- } catch (AuthorizationException $e) {\n- return false;\n- }\n+ return $this->inspect($ability, $arguments)->allowed();\n });\n }\n \n@@ -319,13 +315,29 @@ public function none($abilities, $arguments = [])\n */\n public function authorize($ability, $arguments = [])\n {\n- $result = $this->raw($ability, $arguments);\n+ return $this->inspect($ability, $arguments)->authorize();\n+ }\n \n- if ($result instanceof Response) {\n- return $result;\n- }\n+ /**\n+ * Inspect the user for the given ability.\n+ *\n+ * @param string $ability\n+ * @param array|mixed $arguments\n+ * @return \\Illuminate\\Auth\\Access\\Response\n+ */\n+ public function inspect($ability, $arguments = [])\n+ {\n+ try {\n+ $result = $this->raw($ability, $arguments);\n \n- return $result ? $this->allow() : $this->deny();\n+ if ($result instanceof Response) {\n+ return $result;\n+ }\n+\n+ return $result ? Response::allow() : Response::deny();\n+ } catch (AuthorizationException $e) {\n+ return $e->toResponse();\n+ }\n }\n \n /**\n@@ -334,6 +346,8 @@ public function authorize($ability, $arguments = [])\n * @param string $ability\n * @param array|mixed $arguments\n * @return mixed\n+ *\n+ * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n */\n public function raw($ability, $arguments = [])\n {\n@@ -530,6 +544,7 @@ protected function resolveAuthCallback($user, $ability, array $arguments)\n }\n \n return function () {\n+ //\n };\n }\n ", "filename": "src/Illuminate/Auth/Access/Gate.php", "status": "modified" }, { "diff": "@@ -8,23 +8,23 @@ trait HandlesAuthorization\n * Create a new access response.\n *\n * @param string|null $message\n+ * @param mixed $code\n * @return \\Illuminate\\Auth\\Access\\Response\n */\n- protected function allow($message = null)\n+ protected function allow($message = null, $code = null)\n {\n- return new Response($message);\n+ return Response::allow($message, $code);\n }\n \n /**\n * Throws an unauthorized exception.\n *\n * @param string $message\n- * @return void\n- *\n- * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n+ * @param mixed|null $code\n+ * @return \\Illuminate\\Auth\\Access\\Response\n */\n- protected function deny($message = 'This action is unauthorized.')\n+ protected function deny($message = null, $code = null)\n {\n- throw new AuthorizationException($message);\n+ return Response::deny($message, $code);\n }\n }", "filename": "src/Illuminate/Auth/Access/HandlesAuthorization.php", "status": "modified" }, { "diff": "@@ -2,26 +2,90 @@\n \n namespace Illuminate\\Auth\\Access;\n \n-class Response\n+use Illuminate\\Contracts\\Support\\Arrayable;\n+\n+class Response implements Arrayable\n {\n+ /**\n+ * Indicates whether the response was allowed.\n+ *\n+ * @var bool\n+ */\n+ protected $allowed;\n+\n /**\n * The response message.\n *\n * @var string|null\n */\n protected $message;\n \n+ /**\n+ * The response code.\n+ *\n+ * @var mixed\n+ */\n+ protected $code;\n+\n /**\n * Create a new response.\n *\n- * @param string|null $message\n+ * @param bool $allowed\n+ * @param string $message\n+ * @param mixed $code\n * @return void\n */\n- public function __construct($message = null)\n+ public function __construct($allowed, $message = '', $code = null)\n {\n+ $this->code = $code;\n+ $this->allowed = $allowed;\n $this->message = $message;\n }\n \n+ /**\n+ * Create a new \"allow\" Response.\n+ *\n+ * @param string|null $message\n+ * @param mixed $code\n+ * @return \\Illuminate\\Auth\\Access\\Response\n+ */\n+ public static function allow($message = null, $code = null)\n+ {\n+ return new static(true, $message, $code);\n+ }\n+\n+ /**\n+ * Create a new \"deny\" Response.\n+ *\n+ * @param string|null $message\n+ * @param mixed $code\n+ * @return \\Illuminate\\Auth\\Access\\Response\n+ */\n+ public static function deny($message = null, $code = null)\n+ {\n+ return new static(false, $message, $code);\n+ }\n+\n+ /**\n+ * Determine if the response was allowed.\n+ *\n+ * @return bool\n+ */\n+ public function allowed()\n+ {\n+ return $this->allowed;\n+ }\n+\n+ /**\n+ * Determine if the response was denied.\n+ *\n+ * @return bool\n+ */\n+ public function denied()\n+ {\n+ return ! $this->allowed();\n+ }\n+\n /**\n * Get the response message.\n *\n@@ -32,6 +96,47 @@ public function message()\n return $this->message;\n }\n \n+ /**\n+ * Get the response code / reason.\n+ *\n+ * @return mixed\n+ */\n+ public function code()\n+ {\n+ return $this->code;\n+ }\n+\n+ /**\n+ * Throw authorization exception if response was denied.\n+ *\n+ * @return \\Illuminate\\Auth\\Access\\Response\n+ *\n+ * @throws AuthorizationException\n+ */\n+ public function authorize()\n+ {\n+ if ($this->denied()) {\n+ throw (new AuthorizationException($this->message(), $this->code()))\n+ ->setResponse($this);\n+ }\n+\n+ return $this;\n+ }\n+\n+ /**\n+ * Convert the response to an array.\n+ *\n+ * @return array\n+ */\n+ public function toArray()\n+ {\n+ return [\n+ 'allowed' => $this->allowed(),\n+ 'message' => $this->message(),\n+ 'code' => $this->code(),\n+ ];\n+ }\n+\n /**\n * Get the string representation of the message.\n *", "filename": "src/Illuminate/Auth/Access/Response.php", "status": "modified" }, { "diff": "@@ -0,0 +1,37 @@\n+<?php\n+\n+namespace Illuminate\\Auth\\Events;\n+\n+use Illuminate\\Queue\\SerializesModels;\n+\n+class CurrentDeviceLogout\n+{\n+ use SerializesModels;\n+\n+ /**\n+ * The authentication guard name.\n+ *\n+ * @var string\n+ */\n+ public $guard;\n+\n+ /**\n+ * The authenticated user.\n+ *\n+ * @var \\Illuminate\\Contracts\\Auth\\Authenticatable\n+ */\n+ public $user;\n+\n+ /**\n+ * Create a new event instance.\n+ *\n+ * @param string $guard\n+ * @param \\Illuminate\\Contracts\\Auth\\Authenticatable $user\n+ * @return void\n+ */\n+ public function __construct($guard, $user)\n+ {\n+ $this->user = $user;\n+ $this->guard = $guard;\n+ }\n+}", "filename": "src/Illuminate/Auth/Events/CurrentDeviceLogout.php", "status": "added" }, { "diff": "@@ -35,4 +35,14 @@ public function sendEmailVerificationNotification()\n {\n $this->notify(new Notifications\\VerifyEmail);\n }\n+\n+ /**\n+ * Get the email address that should be used for verification.\n+ *\n+ * @return string\n+ */\n+ public function getEmailForVerification()\n+ {\n+ return $this->email;\n+ }\n }", "filename": "src/Illuminate/Auth/MustVerifyEmail.php", "status": "modified" }, { "diff": "@@ -57,11 +57,11 @@ public function toMail($notifiable)\n }\n \n return (new MailMessage)\n- ->subject(Lang::getFromJson('Reset Password Notification'))\n- ->line(Lang::getFromJson('You are receiving this email because we received a password reset request for your account.'))\n- ->action(Lang::getFromJson('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset()], false)))\n- ->line(Lang::getFromJson('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]))\n- ->line(Lang::getFromJson('If you did not request a password reset, no further action is required.'));\n+ ->subject(Lang::get('Reset Password Notification'))\n+ ->line(Lang::get('You are receiving this email because we received a password reset request for your account.'))\n+ ->action(Lang::get('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset()], false)))\n+ ->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]))\n+ ->line(Lang::get('If you did not request a password reset, no further action is required.'));\n }\n \n /**", "filename": "src/Illuminate/Auth/Notifications/ResetPassword.php", "status": "modified" }, { "diff": "@@ -44,10 +44,10 @@ public function toMail($notifiable)\n }\n \n return (new MailMessage)\n- ->subject(Lang::getFromJson('Verify Email Address'))\n- ->line(Lang::getFromJson('Please click the button below to verify your email address.'))\n- ->action(Lang::getFromJson('Verify Email Address'), $verificationUrl)\n- ->line(Lang::getFromJson('If you did not create an account, no further action is required.'));\n+ ->subject(Lang::get('Verify Email Address'))\n+ ->line(Lang::get('Please click the button below to verify your email address.'))\n+ ->action(Lang::get('Verify Email Address'), $verificationUrl)\n+ ->line(Lang::get('If you did not create an account, no further action is required.'));\n }\n \n /**\n@@ -61,7 +61,10 @@ protected function verificationUrl($notifiable)\n return URL::temporarySignedRoute(\n 'verification.verify',\n Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),\n- ['id' => $notifiable->getKey()]\n+ [\n+ 'id' => $notifiable->getKey(),\n+ 'hash' => sha1($notifiable->getEmailForVerification()),\n+ ]\n );\n }\n ", "filename": "src/Illuminate/Auth/Notifications/VerifyEmail.php", "status": "modified" }, { "diff": "@@ -25,22 +25,14 @@ class PasswordBroker implements PasswordBrokerContract\n */\n protected $users;\n \n- /**\n- * The custom password validator callback.\n- *\n- * @var \\Closure\n- */\n- protected $passwordValidator;\n-\n /**\n * Create a new password broker instance.\n *\n * @param \\Illuminate\\Auth\\Passwords\\TokenRepositoryInterface $tokens\n * @param \\Illuminate\\Contracts\\Auth\\UserProvider $users\n * @return void\n */\n- public function __construct(TokenRepositoryInterface $tokens,\n- UserProvider $users)\n+ public function __construct(TokenRepositoryInterface $tokens, UserProvider $users)\n {\n $this->users = $users;\n $this->tokens = $tokens;\n@@ -82,11 +74,11 @@ public function sendResetLink(array $credentials)\n */\n public function reset(array $credentials, Closure $callback)\n {\n+ $user = $this->validateReset($credentials);\n+\n // If the responses from the validate method is not a user instance, we will\n // assume that it is a redirect and simply return it from this method and\n // the user is properly redirected having an error message on the post.\n- $user = $this->validateReset($credentials);\n-\n if (! $user instanceof CanResetPasswordContract) {\n return $user;\n }\n@@ -115,66 +107,13 @@ protected function validateReset(array $credentials)\n return static::INVALID_USER;\n }\n \n- if (! $this->validateNewPassword($credentials)) {\n- return static::INVALID_PASSWORD;\n- }\n-\n if (! $this->tokens->exists($user, $credentials['token'])) {\n return static::INVALID_TOKEN;\n }\n \n return $user;\n }\n \n- /**\n- * Set a custom password validator.\n- *\n- * @param \\Closure $callback\n- * @return void\n- */\n- public function validator(Closure $callback)\n- {\n- $this->passwordValidator = $callback;\n- }\n-\n- /**\n- * Determine if the passwords match for the request.\n- *\n- * @param array $credentials\n- * @return bool\n- */\n- public function validateNewPassword(array $credentials)\n- {\n- if (isset($this->passwordValidator)) {\n- [$password, $confirm] = [\n- $credentials['password'],\n- $credentials['password_confirmation'],\n- ];\n-\n- return call_user_func(\n- $this->passwordValidator, $credentials\n- ) && $password === $confirm;\n- }\n-\n- return $this->validatePasswordWithDefaults($credentials);\n- }\n-\n- /**\n- * Determine if the passwords are valid for the request.\n- *\n- * @param array $credentials\n- * @return bool\n- */\n- protected function validatePasswordWithDefaults(array $credentials)\n- {\n- [$password, $confirm] = [\n- $credentials['password'],\n- $credentials['password_confirmation'],\n- ];\n-\n- return $password === $confirm && mb_strlen($password) >= 8;\n- }\n-\n /**\n * Get the user for the given credentials.\n *", "filename": "src/Illuminate/Auth/Passwords/PasswordBroker.php", "status": "modified" }, { "diff": "@@ -531,6 +531,32 @@ protected function cycleRememberToken(AuthenticatableContract $user)\n $this->provider->updateRememberToken($user, $token);\n }\n \n+ /**\n+ * Log the user out of the application on their current device only.\n+ *\n+ * @return void\n+ */\n+ public function logoutCurrentDevice()\n+ {\n+ $user = $this->user();\n+\n+ // If we have an event dispatcher instance, we can fire off the logout event\n+ // so any further processing can be done. This allows the developer to be\n+ // listening for anytime a user signs out of this application manually.\n+ $this->clearUserDataFromStorage();\n+\n+ if (isset($this->events)) {\n+ $this->events->dispatch(new Events\\CurrentDeviceLogout($this->name, $user));\n+ }\n+\n+ // Once we have fired the logout event we will clear the users out of memory\n+ // so they are no longer available as the user is no longer considered as\n+ // being signed into this application and should not be available here.\n+ $this->user = null;\n+\n+ $this->loggedOut = true;\n+ }\n+\n /**\n * Invalidate other sessions for the current user.\n *", "filename": "src/Illuminate/Auth/SessionGuard.php", "status": "modified" }, { "diff": "@@ -14,11 +14,11 @@\n }\n ],\n \"require\": {\n- \"php\": \"^7.1.3\",\n- \"illuminate/contracts\": \"5.8.*\",\n- \"illuminate/http\": \"5.8.*\",\n- \"illuminate/queue\": \"5.8.*\",\n- \"illuminate/support\": \"5.8.*\"\n+ \"php\": \"^7.2\",\n+ \"illuminate/contracts\": \"^7.0\",\n+ \"illuminate/http\": \"^7.0\",\n+ \"illuminate/queue\": \"^7.0\",\n+ \"illuminate/support\": \"^7.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -27,13 +27,13 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"5.8-dev\"\n+ \"dev-master\": \"7.0-dev\"\n }\n },\n \"suggest\": {\n- \"illuminate/console\": \"Required to use the auth:clear-resets command (5.8.*).\",\n- \"illuminate/queue\": \"Required to fire login / logout events (5.8.*).\",\n- \"illuminate/session\": \"Required to use the session based guard (5.8.*).\"\n+ \"illuminate/console\": \"Required to use the auth:clear-resets command (^7.0).\",\n+ \"illuminate/queue\": \"Required to fire login / logout events (^7.0).\",\n+ \"illuminate/session\": \"Required to use the session based guard (^7.0).\"\n },\n \"config\": {\n \"sort-packages\": true", "filename": "src/Illuminate/Auth/composer.json", "status": "modified" }, { "diff": "@@ -21,6 +21,20 @@ class BroadcastEvent implements ShouldQueue\n */\n public $event;\n \n+ /**\n+ * The number of times the job may be attempted.\n+ *\n+ * @var int\n+ */\n+ public $tries;\n+\n+ /**\n+ * The number of seconds the job can run before timing out.\n+ *\n+ * @var int\n+ */\n+ public $timeout;\n+\n /**\n * Create a new job handler instance.\n *\n@@ -30,6 +44,8 @@ class BroadcastEvent implements ShouldQueue\n public function __construct($event)\n {\n $this->event = $event;\n+ $this->tries = property_exists($event, 'tries') ? $event->tries : null;\n+ $this->timeout = property_exists($event, 'timeout') ? $event->timeout : null;\n }\n \n /**", "filename": "src/Illuminate/Broadcasting/BroadcastEvent.php", "status": "modified" }, { "diff": "@@ -14,13 +14,13 @@\n }\n ],\n \"require\": {\n- \"php\": \"^7.1.3\",\n+ \"php\": \"^7.2\",\n \"ext-json\": \"*\",\n \"psr/log\": \"^1.0\",\n- \"illuminate/bus\": \"5.8.*\",\n- \"illuminate/contracts\": \"5.8.*\",\n- \"illuminate/queue\": \"5.8.*\",\n- \"illuminate/support\": \"5.8.*\"\n+ \"illuminate/bus\": \"^7.0\",\n+ \"illuminate/contracts\": \"^7.0\",\n+ \"illuminate/queue\": \"^7.0\",\n+ \"illuminate/support\": \"^7.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -29,7 +29,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"5.8-dev\"\n+ \"dev-master\": \"7.0-dev\"\n }\n },\n \"suggest\": {", "filename": "src/Illuminate/Broadcasting/composer.json", "status": "modified" }, { "diff": "@@ -2,6 +2,8 @@\n \n namespace Illuminate\\Bus;\n \n+use Illuminate\\Support\\Arr;\n+\n trait Queueable\n {\n /**\n@@ -39,6 +41,11 @@ trait Queueable\n */\n public $delay;\n \n+ /**\n+ * The middleware the job should be dispatched through.\n+ */\n+ public $middleware = [];\n+\n /**\n * The jobs that should run if this job is successful.\n *\n@@ -113,6 +120,29 @@ public function delay($delay)\n return $this;\n }\n \n+ /**\n+ * Get the middleware the job should be dispatched through.\n+ *\n+ * @return array\n+ */\n+ public function middleware()\n+ {\n+ return $this->middleware ?: [];\n+ }\n+\n+ /**\n+ * Specify the middleware the job should be dispatched through.\n+ *\n+ * @param array|object\n+ * @return $this\n+ */\n+ public function through($middleware)\n+ {\n+ $this->middleware = Arr::wrap($middleware);\n+\n+ return $this;\n+ }\n+\n /**\n * Set the jobs that should run if this job is successful.\n *", "filename": "src/Illuminate/Bus/Queueable.php", "status": "modified" }, { "diff": "@@ -14,10 +14,10 @@\n }\n ],\n \"require\": {\n- \"php\": \"^7.1.3\",\n- \"illuminate/contracts\": \"5.8.*\",\n- \"illuminate/pipeline\": \"5.8.*\",\n- \"illuminate/support\": \"5.8.*\"\n+ \"php\": \"^7.2\",\n+ \"illuminate/contracts\": \"^7.0\",\n+ \"illuminate/pipeline\": \"^7.0\",\n+ \"illuminate/support\": \"^7.0\"\n },\n \"autoload\": {\n \"psr-4\": {\n@@ -26,7 +26,7 @@\n },\n \"extra\": {\n \"branch-alias\": {\n- \"dev-master\": \"5.8-dev\"\n+ \"dev-master\": \"7.0-dev\"\n }\n },\n \"config\": {", "filename": "src/Illuminate/Bus/composer.json", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.6.39\r\n- PHP Version: 7.1.28\r\n- Database Driver & Version: mariadb 10.4\r\n\r\n### Description:\r\n\r\nI'm not 100% sure that this is a bug or intended behaviour but I've been validating an array of values as follows:\r\n\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 2],\r\n];\r\n$rules = [\r\n '*' => 'array',\r\n '*.id' => 'required',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```\r\n\r\nNow if I use the `distinct` rule on the '*.id' column it doesn't work. However if I put it into a non-top-level property, it does eg\r\n\r\n```\r\n$array = [\r\n 'items' => [\r\n ['id' => 1],\r\n ['id' => 2],\r\n ],\r\n];\r\n$rules = [\r\n 'items' => 'array',\r\n 'items.*.id' => 'required|distinct',\r\n];\r\n```\r\n\r\nI guess the question is, are top-level array validation rules supposed to work like this?\r\n\r\n### Steps To Reproduce:\r\n\r\nUsing the following code, the Validator instance will not fire a validation error.\r\n\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 1],\r\n];\r\n$rules = [\r\n '*' => 'array',\r\n '*.id' => 'required|distinct',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```", "comments": [ { "body": "@driesvints This is still an issue in 5.8.29.", "created_at": "2019-07-16T19:24:38Z" }, { "body": "I reproduced it in laravel 5.8 and without ` '*' => 'array', ` it works fine!\r\n\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 1],\r\n];\r\n$rules = [\r\n '*.id' => 'required|distinct',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```\r\nand also it works by changing the order of rules! :\r\n```\r\n$rules = [\r\n '*.id' => 'required|distinct',\r\n '*' => 'array',\r\n];\r\n```\r\n", "created_at": "2019-08-03T06:55:45Z" } ], "number": 29190, "title": "Distinct validation rule not working on top-level array" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\nWhen someone writes validation rules like this:\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 1],\r\n];\r\n$rules = [\r\n '*' => 'array',\r\n '*.id' => 'distinct',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```\r\nit doesn't work as expected. \r\n### Why?\r\nThe `implicitAttributes` array in `Validator` class stores the mapping of 'unparsed' rule to 'parsed' rule. \r\nFor the given rule, it is like: \r\n```\r\n[\r\n \"*\" => [\r\n 0 => 0\r\n 1 => 1\r\n ],\r\n \"*.id\" => [\r\n 0 => \"0.id\"\r\n 1 => \"1.id\"\r\n ]\r\n]\r\n```\r\nSo, when this array is searched to get the `key` of \"0.id\", it finds `*` instead of `*.id` because of loose comparison match between `\"0.id\"` and `0`. \r\nThis scenario can be avoided if all the parsed rule are stored as `string`, which I did in this PR.\r\nI've also added tests to verify the correctness of my solution.\r\n\r\nThis PR will fix #29190 \r\n", "number": 29499, "review_comments": [], "title": "[5.8] Fix top level wildcard validation for 'distinct'" }
{ "commits": [ { "message": "test: 'distinct' validation for top level arrays" }, { "message": "fix: 'distinct' validation for top level arrays" }, { "message": "improvement: 'distinct' validation for top level arrays test" } ], "files": [ { "diff": "@@ -131,7 +131,7 @@ protected function explodeWildcardRules($results, $attribute, $rules)\n foreach ($data as $key => $value) {\n if (Str::startsWith($key, $attribute) || (bool) preg_match('/^'.$pattern.'\\z/', $key)) {\n foreach ((array) $rules as $rule) {\n- $this->implicitAttributes[$attribute][] = $key;\n+ $this->implicitAttributes[$attribute][] = strval($key);\n \n $results = $this->mergeRules($results, $key, $rule);\n }", "filename": "src/Illuminate/Validation/ValidationRuleParser.php", "status": "modified" }, { "diff": "@@ -1899,6 +1899,29 @@ public function testValidateDistinct()\n $this->assertEquals('There is a duplication!', $v->messages()->first('foo.1'));\n }\n \n+ public function testValidateDistinctForTopLevelArrays()\n+ {\n+ $trans = $this->getIlluminateArrayTranslator();\n+\n+ $v = new Validator($trans, ['foo', 'foo'], ['*' => 'distinct']);\n+ $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, [['foo' => 1], ['foo' => 1]], ['*' => 'array', '*.foo' => 'distinct']);\n+ $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, [['foo' => 'a'], ['foo' => 'A']], ['*' => 'array', '*.foo' => 'distinct:ignore_case']);\n+ $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, [['foo' => [['id' => 1]]], ['foo' => [['id' => 1]]]], ['*' => 'array', '*.foo' => 'array', '*.foo.*.id' => 'distinct']);\n+ $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, ['foo', 'foo'], ['*' => 'distinct'], ['*.distinct' => 'There is a duplication!']);\n+ $this->assertFalse($v->passes());\n+ $v->messages()->setFormat(':message');\n+ $this->assertEquals('There is a duplication!', $v->messages()->first('0'));\n+ $this->assertEquals('There is a duplication!', $v->messages()->first('1'));\n+ }\n+\n public function testValidateUnique()\n {\n $trans = $this->getIlluminateArrayTranslator();", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.4\r\n- PHP Version:7.1\r\n- Database Driver & Version:\r\n\r\n### Description:\r\nWe're seeing a lot of issues with concurrent requests to the server where session information is lost. Seeing on other forums and discussions on the slack channels, I see a lot of use cases where concurrent requests cause for session data to be lost.\r\n\r\nMuch of the issues could in my opinion be prevented if not ALL session data is stored at the same time, but if laravel would only update session data for those keys that actually require update.\r\n\r\nIn our project, for instance, we are having a polling mechanism that asks the server for the current session state; each such request however SAVES the session data in its entirety. If - at the same time - the user is doing a rest request to authenticate, or to log out, or basically to do any action that might require session data to be updated, we're having a lot of risks of the requests to impact one another.\r\n\r\nrequest A: POST/auth/login\r\nrequest B: GET /session/state\r\n\r\nif both these requests are sent to the server, B updates the session because user logs in, but request A was already started, and saves the session after that, the authentication information is lost, and the user is logged out again, even though he just authenticated.\r\n\r\nI think it's a \"big\" change, but it would be better if only session data that is changed, is being saved. at this time, the entire session data is always being stored, which isn't desirable.\r\n\r\nAdding a key to the method that stores data will be breaking for all drivers, and may impact existing users that have implemented drivers. therefore, I believe it would be advisable that laravel checks the driver method using reflection to see if the driver already supports key-based storing, and if not should log a warning and fallback to old mechanism. In later laravel version (6?), we could deprecate the old way of dealing with it.\r\n\r\nAny thoughts?\r\n\r\n### Steps To Reproduce:\r\n", "comments": [ { "body": "Just wanted to add that I noticed the startSession middleware is terminable.\r\nThe terminate method is... storing session.\r\n\r\nSince the terminate is executed at the very end of a request (even after sending data to the client), it seems to be a potentially long time between the start of the session, and the storage at terminating middleware, and this definitely explains why I'm seeing such strange behaviour.\r\n\r\nI also see that it seems to be calling an ageing method of some sort for flash messages, which might explain why this has been done.\r\n\r\nI really think this needs to be tackled in some way :-)", "created_at": "2017-03-02T12:57:41Z" }, { "body": "This is a \"known\" issue since at least Laravel 5.1. https://github.com/laravel/framework/issues/14385", "created_at": "2017-03-02T13:40:56Z" }, { "body": "Hi @sisve!\r\nThanks for referencing that issue.\r\nI think mine is a bit different though. I'm not sure that the session is completely wiped out, and the suggested solution in that issue won't fix the real issue that we have.\r\n\r\nI'm mainly concerned that - when I checked the bits of code you sent me through slack - there is a small design issue that you won't be able to fix by migrating to database or to redis either.\r\nIf I understood correctly from what I briefly saw the session middleware that creates the session is terminable, meaning there is logic in the terminate() method of that middleware.\r\n\r\nIn that temination, the session data is saved (I'm thinking because they want to get rid of the flash messages, hence they wait for data to have been sent to the browser before they \"age\"/remove the flash messages from the session.\r\n\r\nThe big issue there is that - no matter what little piece of information the session you want to update, ALL session data is being saved again. So even data that we didn't want to update, is being saved. So no matter what driver you have behind that, I don't think this will be fixed.\r\n\r\nConsidering that it's in the terminate of the middleware, you are creating a big timeframe between the start of the request (in which session information is being retrieved), and the final save. If another concurrent request has meanwhile taken place, you might be saving outdated information to the session.\r\n\r\nI believe that when we can avoid the entire session being saved, but make saves key-based, a lot will be fixed, for many use cases. I understand that the flash messages need to be erased, but if we can achieve that by just updating the session.flash data, and not the entire session, it will be more secure.\r\n\r\nThe solution of not allowing multiple requests is theoretically a good suggestion; in practice it's not. I know a lot of users - including myself - tend to open multiple tabs of the same app because it makes switching easier if you need to compare stuff for instance; you can not and should never trust that you can control the number of requests that come in and in what order.\r\n\r\nFurthermore - the whole idea of sessions is that the information held by the session is available throughout... the session. I don't think it's wise to update session information that shouldn't be touched.\r\n\r\nI hope this makes sense. I LOVE Laravel, but this is a real issue that I think we should be able to tackle.\r\n\r\n\r\nCheers,\r\nDavid.", "created_at": "2017-03-02T15:24:02Z" }, { "body": "I'm also thinking it might be interesting to load the flash messages at the BEGINNING of the request, save the session there, and get rid of the terminate process. The flash messages are supposed to just live between two requests, right? So you could probably get them at the beginning, and try to eliminate the session save at the end. But that would be a workaround really. I still believe it's a minor design issue to save data that might have been already updated by another request, since it's supposed to be session-wide.\r\n\r\nThis whole issue reminds me again of why I always try to eliminate anything that goes into sessions :-)", "created_at": "2017-03-02T15:29:29Z" }, { "body": "Having the exact same issue. Our app is basically useless because of this, and the user experience is terrible, as in load the page (lots of concurrent requests), at the same time issue login request, and we loose the session, and the user is obviously not logged in, because stale session data is written to disc.\r\n\r\nThe obvious fix would be to stop using sessions and switch to a stateless token based scheme, but that would mean refactoring lots of application code, so another fix could be to change the terminate flow to something along the line of:\r\n1. Lock the session file\r\n2. Reload the data\r\n3. Merge in delta changes\r\n4. Write the file\r\n5. Release the lock\r\n\r\nObviously locking sucks, but what else could possible be done to fix this issue?\r\n\r\nThe biggest problem in this fix is that this would be really hard to implement into the session Store implementation as it is today, because it's decoupled from the FileSessionHandler. That makes a lot of sense, but it makes this hard to fix.", "created_at": "2017-08-31T10:43:11Z" }, { "body": "storing session data to files is a worst case if you don't use ram as storage. If resource can be modified by different software , always use locking of data , at least mutexes", "created_at": "2019-03-22T19:11:51Z" }, { "body": "I can implement a \"fix\" for this by simply extending the session expiration in storage if the session data is exactly the same as it was at the beginning of the request. However, this would only work for certain drivers. I think I could make it work for the following drivers: database, redis, memcached, DynamoDB (maybe)...\r\n\r\nI would have to add a `touch` method to the Cache contract, so it would be a breaking change.\r\n\r\nI know it will definitely not be possible on the file driver.\r\n\r\nI'm hesitant to implement it because this would not solve the \"problem\" of two concurrent requests modifying the session at the same time. Note this is also a \"problem\" in other web frameworks such as Rails as well. ", "created_at": "2020-04-30T20:17:08Z" }, { "body": "what if we allow the user to somehow mark some routes as \"concurrently\",\r\nSo the expiration time does not need to be updated on the cookie when a request hits that route.\r\nBasically this allows the server to respond without a cookie.(only on the routes which are marked as \"concurenty.\")\r\n\r\nThe user can accept this limitation (not updating cookie expiration time) to alleviate the problem quite a bit.\r\nI remember the solution I had in mind was impossible at last, because we had to include a cookie on each and every response.\r\n@taylorotwell ", "created_at": "2020-04-30T22:07:28Z" }, { "body": "> I can implement a \"fix\" for this by simply extending the session expiration in storage if the session data is exactly the same as it was at the beginning of the request. However, this would only work for certain drivers. I think I could make it work for the following drivers: database, redis, memcached, DynamoDB (maybe)...\n> \n> I would have to add a `touch` method to the Cache contract, so it would be a breaking change.\n> \n> I know it will definitely not be possible on the file driver.\n> \n> I'm hesitant to implement it because this would not solve the \"problem\" of two concurrent requests modifying the session at the same time. Note this is also a \"problem\" in other web frameworks such as Rails as well. \n\nI think we should have it for these driver as its possible it would be good", "created_at": "2020-05-01T04:43:00Z" }, { "body": "Could we go the ASP.NET way and implement session locking? When routes are marked for write access to sessions they take out an exclusive lock so that other requests that wants to write to the session are blocked until the first is done.\r\n\r\nThis would effectively execute all requests with write-access to the session one at a time.\r\n\r\nRef: https://docs.microsoft.com/en-us/dotnet/api/system.web.sessionstate.sessionstatebehavior\r\n", "created_at": "2020-05-01T05:22:06Z" }, { "body": "I agree with @sisve’s comment 👍", "created_at": "2020-05-01T07:20:52Z" }, { "body": "@sisve how do you recommend determining which requests have \"write access\" to the session?", "created_at": "2020-05-01T18:00:31Z" }, { "body": "https://github.com/laravel/framework/pull/32636\r\n\r\nLet's continue discussion here...", "created_at": "2020-05-01T19:18:25Z" }, { "body": "@taylorotwell by adding a route middleware?", "created_at": "2020-05-01T19:36:10Z" } ], "number": 18187, "title": "Store session data per key" }
{ "body": "related issue : #18187 \r\n\r\nIf the first first serialized string we receive from the session store (after a read operation) is exactly the same as the final final string we are delivering back to the session store, we can skip the write operation.\r\nBecause at best it does not change any thing, or worse it will override the precious work of a concurrent request.\r\n\r\nThis PR brings help to the issue, only (and only) in cases where the session ID is not regenerated by the other concurrent request and only the session data is modified.\r\nbecause the cookie is always sent and contains the session id of the dominant request.\r\n\r\nFor example if the concurrent request performs a `login` the session data is still being lost.\r\nbecause the cookie would not be able to find the new session by it's id.", "number": 29410, "review_comments": [], "title": "[6.0] alleviate session race condition" }
{ "commits": [ { "message": "Remove constant" } ], "files": [ { "diff": "@@ -46,6 +46,13 @@ class Store implements Session\n */\n protected $started = false;\n \n+ /**\n+ * Serialized version of the session data.\n+ *\n+ * @var array\n+ */\n+ protected $originalData = [];\n+\n /**\n * Create a new session instance.\n *\n@@ -94,7 +101,9 @@ protected function loadSession()\n */\n protected function readFromHandler()\n {\n- if ($data = $this->handler->read($this->getId())) {\n+ $this->originalData['id'] = $this->getId();\n+\n+ if ($this->originalData['data'] = $data = $this->handler->read($this->getId())) {\n $data = @unserialize($this->prepareForUnserialize($data));\n \n if ($data !== false && ! is_null($data) && is_array($data)) {\n@@ -125,9 +134,14 @@ public function save()\n {\n $this->ageFlashData();\n \n- $this->handler->write($this->getId(), $this->prepareForStorage(\n- serialize($this->attributes)\n- ));\n+ $data = $this->prepareForStorage(serialize($this->attributes));\n+\n+ // If the serialized session data has not changed\n+ // during the life cycle of the request we just\n+ // skip overriding that with the same thing.\n+ if ($this->isDirty($data)) {\n+ $this->handler->write($this->getId(), $data);\n+ }\n \n $this->started = false;\n }\n@@ -669,4 +683,16 @@ public function setRequestOnHandler($request)\n $this->handler->setRequest($request);\n }\n }\n+\n+ /**\n+ * Determine if the session data has changed since loaded.\n+ *\n+ * @param $data\n+ *\n+ * @return bool\n+ */\n+ protected function isDirty($data)\n+ {\n+ return $this->getId() !== $this->originalData['id'] || $data !== $this->originalData['data'];\n+ }\n }", "filename": "src/Illuminate/Session/Store.php", "status": "modified" }, { "diff": "@@ -35,13 +35,6 @@ class Password extends Facade\n */\n const INVALID_USER = PasswordBroker::INVALID_USER;\n \n- /**\n- * Constant representing an invalid password.\n- *\n- * @var string\n- */\n- const INVALID_PASSWORD = PasswordBroker::INVALID_PASSWORD;\n-\n /**\n * Constant representing an invalid token.\n *", "filename": "src/Illuminate/Support/Facades/Password.php", "status": "modified" }, { "diff": "@@ -150,7 +150,7 @@ public function testSessionIsProperlyUpdated()\n $this->assertFalse($session->isStarted());\n }\n \n- public function testSessionIsReSavedWhenNothingHasChanged()\n+ public function testSessionIsNotReSavedWhenNothingHasChanged()\n {\n $session = $this->getSession();\n $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([", "filename": "tests/Session/SessionStoreTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.4\r\n- PHP Version:7.1\r\n- Database Driver & Version:\r\n\r\n### Description:\r\nWe're seeing a lot of issues with concurrent requests to the server where session information is lost. Seeing on other forums and discussions on the slack channels, I see a lot of use cases where concurrent requests cause for session data to be lost.\r\n\r\nMuch of the issues could in my opinion be prevented if not ALL session data is stored at the same time, but if laravel would only update session data for those keys that actually require update.\r\n\r\nIn our project, for instance, we are having a polling mechanism that asks the server for the current session state; each such request however SAVES the session data in its entirety. If - at the same time - the user is doing a rest request to authenticate, or to log out, or basically to do any action that might require session data to be updated, we're having a lot of risks of the requests to impact one another.\r\n\r\nrequest A: POST/auth/login\r\nrequest B: GET /session/state\r\n\r\nif both these requests are sent to the server, B updates the session because user logs in, but request A was already started, and saves the session after that, the authentication information is lost, and the user is logged out again, even though he just authenticated.\r\n\r\nI think it's a \"big\" change, but it would be better if only session data that is changed, is being saved. at this time, the entire session data is always being stored, which isn't desirable.\r\n\r\nAdding a key to the method that stores data will be breaking for all drivers, and may impact existing users that have implemented drivers. therefore, I believe it would be advisable that laravel checks the driver method using reflection to see if the driver already supports key-based storing, and if not should log a warning and fallback to old mechanism. In later laravel version (6?), we could deprecate the old way of dealing with it.\r\n\r\nAny thoughts?\r\n\r\n### Steps To Reproduce:\r\n", "comments": [ { "body": "Just wanted to add that I noticed the startSession middleware is terminable.\r\nThe terminate method is... storing session.\r\n\r\nSince the terminate is executed at the very end of a request (even after sending data to the client), it seems to be a potentially long time between the start of the session, and the storage at terminating middleware, and this definitely explains why I'm seeing such strange behaviour.\r\n\r\nI also see that it seems to be calling an ageing method of some sort for flash messages, which might explain why this has been done.\r\n\r\nI really think this needs to be tackled in some way :-)", "created_at": "2017-03-02T12:57:41Z" }, { "body": "This is a \"known\" issue since at least Laravel 5.1. https://github.com/laravel/framework/issues/14385", "created_at": "2017-03-02T13:40:56Z" }, { "body": "Hi @sisve!\r\nThanks for referencing that issue.\r\nI think mine is a bit different though. I'm not sure that the session is completely wiped out, and the suggested solution in that issue won't fix the real issue that we have.\r\n\r\nI'm mainly concerned that - when I checked the bits of code you sent me through slack - there is a small design issue that you won't be able to fix by migrating to database or to redis either.\r\nIf I understood correctly from what I briefly saw the session middleware that creates the session is terminable, meaning there is logic in the terminate() method of that middleware.\r\n\r\nIn that temination, the session data is saved (I'm thinking because they want to get rid of the flash messages, hence they wait for data to have been sent to the browser before they \"age\"/remove the flash messages from the session.\r\n\r\nThe big issue there is that - no matter what little piece of information the session you want to update, ALL session data is being saved again. So even data that we didn't want to update, is being saved. So no matter what driver you have behind that, I don't think this will be fixed.\r\n\r\nConsidering that it's in the terminate of the middleware, you are creating a big timeframe between the start of the request (in which session information is being retrieved), and the final save. If another concurrent request has meanwhile taken place, you might be saving outdated information to the session.\r\n\r\nI believe that when we can avoid the entire session being saved, but make saves key-based, a lot will be fixed, for many use cases. I understand that the flash messages need to be erased, but if we can achieve that by just updating the session.flash data, and not the entire session, it will be more secure.\r\n\r\nThe solution of not allowing multiple requests is theoretically a good suggestion; in practice it's not. I know a lot of users - including myself - tend to open multiple tabs of the same app because it makes switching easier if you need to compare stuff for instance; you can not and should never trust that you can control the number of requests that come in and in what order.\r\n\r\nFurthermore - the whole idea of sessions is that the information held by the session is available throughout... the session. I don't think it's wise to update session information that shouldn't be touched.\r\n\r\nI hope this makes sense. I LOVE Laravel, but this is a real issue that I think we should be able to tackle.\r\n\r\n\r\nCheers,\r\nDavid.", "created_at": "2017-03-02T15:24:02Z" }, { "body": "I'm also thinking it might be interesting to load the flash messages at the BEGINNING of the request, save the session there, and get rid of the terminate process. The flash messages are supposed to just live between two requests, right? So you could probably get them at the beginning, and try to eliminate the session save at the end. But that would be a workaround really. I still believe it's a minor design issue to save data that might have been already updated by another request, since it's supposed to be session-wide.\r\n\r\nThis whole issue reminds me again of why I always try to eliminate anything that goes into sessions :-)", "created_at": "2017-03-02T15:29:29Z" }, { "body": "Having the exact same issue. Our app is basically useless because of this, and the user experience is terrible, as in load the page (lots of concurrent requests), at the same time issue login request, and we loose the session, and the user is obviously not logged in, because stale session data is written to disc.\r\n\r\nThe obvious fix would be to stop using sessions and switch to a stateless token based scheme, but that would mean refactoring lots of application code, so another fix could be to change the terminate flow to something along the line of:\r\n1. Lock the session file\r\n2. Reload the data\r\n3. Merge in delta changes\r\n4. Write the file\r\n5. Release the lock\r\n\r\nObviously locking sucks, but what else could possible be done to fix this issue?\r\n\r\nThe biggest problem in this fix is that this would be really hard to implement into the session Store implementation as it is today, because it's decoupled from the FileSessionHandler. That makes a lot of sense, but it makes this hard to fix.", "created_at": "2017-08-31T10:43:11Z" }, { "body": "storing session data to files is a worst case if you don't use ram as storage. If resource can be modified by different software , always use locking of data , at least mutexes", "created_at": "2019-03-22T19:11:51Z" }, { "body": "I can implement a \"fix\" for this by simply extending the session expiration in storage if the session data is exactly the same as it was at the beginning of the request. However, this would only work for certain drivers. I think I could make it work for the following drivers: database, redis, memcached, DynamoDB (maybe)...\r\n\r\nI would have to add a `touch` method to the Cache contract, so it would be a breaking change.\r\n\r\nI know it will definitely not be possible on the file driver.\r\n\r\nI'm hesitant to implement it because this would not solve the \"problem\" of two concurrent requests modifying the session at the same time. Note this is also a \"problem\" in other web frameworks such as Rails as well. ", "created_at": "2020-04-30T20:17:08Z" }, { "body": "what if we allow the user to somehow mark some routes as \"concurrently\",\r\nSo the expiration time does not need to be updated on the cookie when a request hits that route.\r\nBasically this allows the server to respond without a cookie.(only on the routes which are marked as \"concurenty.\")\r\n\r\nThe user can accept this limitation (not updating cookie expiration time) to alleviate the problem quite a bit.\r\nI remember the solution I had in mind was impossible at last, because we had to include a cookie on each and every response.\r\n@taylorotwell ", "created_at": "2020-04-30T22:07:28Z" }, { "body": "> I can implement a \"fix\" for this by simply extending the session expiration in storage if the session data is exactly the same as it was at the beginning of the request. However, this would only work for certain drivers. I think I could make it work for the following drivers: database, redis, memcached, DynamoDB (maybe)...\n> \n> I would have to add a `touch` method to the Cache contract, so it would be a breaking change.\n> \n> I know it will definitely not be possible on the file driver.\n> \n> I'm hesitant to implement it because this would not solve the \"problem\" of two concurrent requests modifying the session at the same time. Note this is also a \"problem\" in other web frameworks such as Rails as well. \n\nI think we should have it for these driver as its possible it would be good", "created_at": "2020-05-01T04:43:00Z" }, { "body": "Could we go the ASP.NET way and implement session locking? When routes are marked for write access to sessions they take out an exclusive lock so that other requests that wants to write to the session are blocked until the first is done.\r\n\r\nThis would effectively execute all requests with write-access to the session one at a time.\r\n\r\nRef: https://docs.microsoft.com/en-us/dotnet/api/system.web.sessionstate.sessionstatebehavior\r\n", "created_at": "2020-05-01T05:22:06Z" }, { "body": "I agree with @sisve’s comment 👍", "created_at": "2020-05-01T07:20:52Z" }, { "body": "@sisve how do you recommend determining which requests have \"write access\" to the session?", "created_at": "2020-05-01T18:00:31Z" }, { "body": "https://github.com/laravel/framework/pull/32636\r\n\r\nLet's continue discussion here...", "created_at": "2020-05-01T19:18:25Z" }, { "body": "@taylorotwell by adding a route middleware?", "created_at": "2020-05-01T19:36:10Z" } ], "number": 18187, "title": "Store session data per key" }
{ "body": "This is a re submission of #29399 \r\nrelated issue : #18187 \r\n\r\nThis is a re submission of #29399 , With the difference that, now we always send the cookie to the client, no matter what.\r\nThis PR brings help to the issue, Only (and only) in cases where the session ID is not regenerated by the other concurrent request and only the session data is modified.\r\n\r\nAlso it may save an unnecessary I/O operation, at the end of the request.\r\n\r\nI thought a lot, but I was not able to find a better solution to cover more cases, unfortunately.", "number": 29409, "review_comments": [], "title": "[6.0] Alleviate session race problem" }
{ "commits": [ { "message": "Add support for custom drivers\n\nThis portion of code is heavily inspired by the CacheManager extension system." }, { "message": "Adhere to the newly created contract" }, { "message": "Test the extend system" }, { "message": "Style changes" }, { "message": "Update RedisManagerExtensionTest.php\n\nStyle changes" }, { "message": "The interface is not enough" }, { "message": "Add assertSessionHasInput to TestResponse" }, { "message": "Merge pull request #29327 from jasonmccreary/session-input-assertion\n\n[5.8] Add assertSessionHasInput to TestResponse" }, { "message": "Merge branch 'add-support-for-custom-redis-driver' of https://github.com/paulhenri-l/framework into paulhenri-l-add-support-for-custom-redis-driver" }, { "message": "formatting" }, { "message": "version" }, { "message": "Use date_create to prevent unsuppressible date validator warnings" }, { "message": "[5.8] update changelog" }, { "message": "[5.8] update changelog" }, { "message": "Merge pull request #29342 from LarsGrevelink/fix-unsuppressible-validator-warnings\n\n[5.8] Use date_create to prevent unsuppressible date validator warnings" }, { "message": "Remove temporary variable" }, { "message": "Correct test methods names" }, { "message": "Merge pull request #29346 from xuanquynh/correct_test_methods_names\n\n[5.8] Correct test methods names" }, { "message": "Merge pull request #29345 from dimacros/5.8\n\n[5.8] Remove temporary variable on Request" }, { "message": "Use pure class name (stdClass)" }, { "message": "Make updateExistingPivot() safe on non-existent pivot" }, { "message": "Fix some docblocks params." }, { "message": "Change visibility to public for hasPivotColumn method" }, { "message": "Fix worker timeout handler for null `$job`\n\nThe queue worker timeout handler may be called with a null `$job` if the\r\ntimeout is reached when there is no job processing (perhaps it took too long\r\nto fetch the next job in the worker loop). This fix checks to make sure there\r\nis a job before attempting to mark the as failed if it will exceed the maximum\r\nnumber of attempts." }, { "message": "Merge pull request #29367 from pactode/5.8\n\n[5.8] Change visibility to public for hasPivotColumn method by pactode" }, { "message": "Merge pull request #29364 from lucasmichot/feature/5.8/fix-docblocks-params\n\n[5.8] Fix some docblocks params." }, { "message": "Merge pull request #29366 from djtarazona/patch-1\n\nFix worker timeout handler when there is no job processing" }, { "message": "Merge pull request #29362 from mpyw/fix-update-existing-pivot-error-on-non-existent-record\n\n[5.8] Make updateExistingPivot() safe on non-existent pivot" }, { "message": "Merge pull request #29360 from xuanquynh/correct_class_name\n\n[5.8] Use pure class name (stdClass)" }, { "message": "Revert \"Correct test methods names\"\n\nThis reverts commit e78edaaa9447e4f1b00a3a56a9f9ed2bfe1f8e47." } ], "files": [ { "diff": "@@ -1,10 +1,19 @@\n # Release Notes for 5.8.x\n \n-## [Unreleased](https://github.com/laravel/framework/compare/v5.8.29...5.8)\n+## [Unreleased](https://github.com/laravel/framework/compare/v5.8.30...5.8)\n+\n+\n+\n+## [v5.8.30 (2019-07-30)](https://github.com/laravel/framework/compare/v5.8.29...v5.8.30)\n \n ### Added\n-- Added`MakesHttpRequests::option()` and `MakesHttpRequests::optionJson()` methods ([#29258](https://github.com/laravel/framework/pull/29258))\n+- Added `MakesHttpRequests::option()` and `MakesHttpRequests::optionJson()` methods ([#29258](https://github.com/laravel/framework/pull/29258))\n - Added `Blueprint::uuidMorphs()` and `Blueprint::nullableUuidMorphs()` methods ([#29289](https://github.com/laravel/framework/pull/29289))\n+- Added `MailgunTransport::getEndpoint()` and `MailgunTransport::setEndpoint()` methods ([#29312](https://github.com/laravel/framework/pull/29312))\n+- Added `WEBP` to image validation rule ([#29309](https://github.com/laravel/framework/pull/29309))\n+- Added `TestResponse::assertSessionHasInput()` method ([#29327](https://github.com/laravel/framework/pull/29327))\n+- Added support for custom redis driver ([#29275](https://github.com/laravel/framework/pull/29275))\n+- Added Postgres support for `collation()` on columns ([#29213](https://github.com/laravel/framework/pull/29213))\n \n ### Fixed\n - Fixed collections with JsonSerializable items and mixed values ([#29205](https://github.com/laravel/framework/pull/29205))\n@@ -13,14 +22,15 @@\n - Fixed default theme for Markdown mails ([#29274](https://github.com/laravel/framework/pull/29274))\n - Fixed UPDATE queries with alias on SQLite ([#29276](https://github.com/laravel/framework/pull/29276))\n - Fixed UPDATE and DELETE queries with join bindings on PostgreSQL ([#29306](https://github.com/laravel/framework/pull/29306))\n+- Fixed support of `DateTime` objects and `int` values in `orWhereDay()`, `orWhereMonth()`, `orWhereYear()` methods in the `Builder` ([#29317](https://github.com/laravel/framework/pull/29317))\n+- Fixed DELETE queries with joins on PostgreSQL ([#29313](https://github.com/laravel/framework/pull/29313))\n+- Prevented a job from firing if job marked as deleted ([#29204](https://github.com/laravel/framework/pull/29204), [1003c27](https://github.com/laravel/framework/commit/1003c27b73f11472c1ebdb9238b839aefddfb048))\n+- Fixed model deserializing with custom `Model::newCollection()` ([#29196](https://github.com/laravel/framework/pull/29196))\n \n ### Reverted\n - Reverted: [Added possibility for `WithFaker::makeFaker()` use local `app.faker_locale` config](https://github.com/laravel/framework/pull/29123) ([#29250](https://github.com/laravel/framework/pull/29250))\n \n-### TODO\n-- tagged today breaks queue deserializing with Model::newCollection() ([#29196](https://github.com/laravel/framework/pull/29196))\n-- Prevent a job from firing if it's been marked as deleted ([#29204](https://github.com/laravel/framework/pull/29204), [1003c27](https://github.com/laravel/framework/commit/1003c27b73f11472c1ebdb9238b839aefddfb048))\n-- Add Postgres support for collation() on columns ([#29213](https://github.com/laravel/framework/pull/29213))\n+### Changed\n - Allocate memory for error handling to allow handling memory exhaustion limits ([#29226](https://github.com/laravel/framework/pull/29226))\n - Teardown test suite after using fail() method ([#29267](https://github.com/laravel/framework/pull/29267))\n ", "filename": "CHANGELOG-5.8.md", "status": "modified" }, { "diff": "@@ -0,0 +1,25 @@\n+<?php\n+\n+namespace Illuminate\\Contracts\\Redis;\n+\n+interface Connector\n+{\n+ /**\n+ * Create a connection to a Redis cluster.\n+ *\n+ * @param array $config\n+ * @param array $options\n+ * @return \\Illuminate\\Redis\\Connections\\Connection\n+ */\n+ public function connect(array $config, array $options);\n+\n+ /**\n+ * Create a connection to a Redis instance.\n+ *\n+ * @param array $config\n+ * @param array $clusterOptions\n+ * @param array $options\n+ * @return \\Illuminate\\Redis\\Connections\\Connection\n+ */\n+ public function connectToCluster(array $config, array $clusterOptions, array $options);\n+}", "filename": "src/Illuminate/Contracts/Redis/Connector.php", "status": "added" }, { "diff": "@@ -203,7 +203,7 @@ public function setPivotKeys($foreignKey, $relatedKey)\n /**\n * Determine if the pivot model or given attributes has timestamp attributes.\n *\n- * @param $attributes array|null\n+ * @param array|null $attributes\n * @return bool\n */\n public function hasTimestampAttributes($attributes = null)", "filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php", "status": "modified" }, { "diff": "@@ -220,12 +220,12 @@ public function updateExistingPivot($id, array $attributes, $touch = true)\n */\n protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch)\n {\n- $updated = $this->getCurrentlyAttachedPivots()\n+ $pivot = $this->getCurrentlyAttachedPivots()\n ->where($this->foreignPivotKey, $this->parent->{$this->parentKey})\n ->where($this->relatedPivotKey, $this->parseId($id))\n- ->first()\n- ->fill($attributes)\n- ->isDirty();\n+ ->first();\n+\n+ $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;\n \n $this->newPivot([\n $this->foreignPivotKey => $this->parent->{$this->parentKey},\n@@ -403,7 +403,7 @@ protected function addTimestampsToAttachment(array $record, $exists = false)\n * @param string $column\n * @return bool\n */\n- protected function hasPivotColumn($column)\n+ public function hasPivotColumn($column)\n {\n return in_array($column, $this->pivotColumns);\n }", "filename": "src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php", "status": "modified" }, { "diff": "@@ -29,7 +29,7 @@ class Application extends Container implements ApplicationContract, HttpKernelIn\n *\n * @var string\n */\n- const VERSION = '5.8.29';\n+ const VERSION = '5.8.30';\n \n /**\n * The base path for the Laravel installation.", "filename": "src/Illuminate/Foundation/Application.php", "status": "modified" }, { "diff": "@@ -675,15 +675,21 @@ public function assertJsonValidationErrors($errors)\n );\n \n if (! is_int($key)) {\n+ $hasError = false;\n+\n foreach (Arr::wrap($jsonErrors[$key]) as $jsonErrorMessage) {\n if (Str::contains($jsonErrorMessage, $value)) {\n- return $this;\n+ $hasError = true;\n+\n+ break;\n }\n }\n \n- PHPUnit::fail(\n- \"Failed to find a validation error in the response for key and message: '$key' => '$value'\".PHP_EOL.PHP_EOL.$errorMessage\n- );\n+ if (! $hasError) {\n+ PHPUnit::fail(\n+ \"Failed to find a validation error in the response for key and message: '$key' => '$value'\".PHP_EOL.PHP_EOL.$errorMessage\n+ );\n+ }\n }\n }\n \n@@ -913,6 +919,41 @@ public function assertSessionHasAll(array $bindings)\n return $this;\n }\n \n+ /**\n+ * Assert that the session has a given value in the flashed input array.\n+ *\n+ * @param string|array $key\n+ * @param mixed $value\n+ * @return $this\n+ */\n+ public function assertSessionHasInput($key, $value = null)\n+ {\n+ if (is_array($key)) {\n+ foreach ($key as $k => $v) {\n+ if (is_int($k)) {\n+ $this->assertSessionHasInput($v);\n+ } else {\n+ $this->assertSessionHasInput($k, $v);\n+ }\n+ }\n+\n+ return $this;\n+ }\n+\n+ if (is_null($value)) {\n+ PHPUnit::assertTrue(\n+ $this->session()->getOldInput($key),\n+ \"Session is missing expected key [{$key}].\"\n+ );\n+ } elseif ($value instanceof Closure) {\n+ PHPUnit::assertTrue($value($this->session()->getOldInput($key)));\n+ } else {\n+ PHPUnit::assertEquals($value, $this->session()->getOldInput($key));\n+ }\n+\n+ return $this;\n+ }\n+\n /**\n * Assert that the session has the given errors.\n *", "filename": "src/Illuminate/Foundation/Testing/TestResponse.php", "status": "modified" }, { "diff": "@@ -422,16 +422,14 @@ public static function createFromBase(SymfonyRequest $request)\n return $request;\n }\n \n- $content = $request->content;\n-\n $newRequest = (new static)->duplicate(\n $request->query->all(), $request->request->all(), $request->attributes->all(),\n $request->cookies->all(), $request->files->all(), $request->server->all()\n );\n \n $newRequest->headers->replace($request->headers->all());\n \n- $newRequest->content = $content;\n+ $newRequest->content = $request->content;\n \n $newRequest->request = $newRequest->getInputSource();\n ", "filename": "src/Illuminate/Http/Request.php", "status": "modified" }, { "diff": "@@ -140,9 +140,11 @@ protected function registerTimeoutHandler($job, WorkerOptions $options)\n // process if it is running too long because it has frozen. This uses the async\n // signals supported in recent versions of PHP to accomplish it conveniently.\n pcntl_signal(SIGALRM, function () use ($job, $options) {\n- $this->markJobAsFailedIfWillExceedMaxAttempts(\n- $job->getConnectionName(), $job, (int) $options->maxTries, $this->maxAttemptsExceededException($job)\n- );\n+ if ($job) {\n+ $this->markJobAsFailedIfWillExceedMaxAttempts(\n+ $job->getConnectionName(), $job, (int) $options->maxTries, $this->maxAttemptsExceededException($job)\n+ );\n+ }\n \n $this->kill(1);\n });", "filename": "src/Illuminate/Queue/Worker.php", "status": "modified" }, { "diff": "@@ -100,7 +100,7 @@ public function setnx($key, $value)\n *\n * @param string $key\n * @param dynamic $dictionary\n- * @return int\n+ * @return array\n */\n public function hmget($key, ...$dictionary)\n {\n@@ -149,7 +149,7 @@ public function hsetnx($hash, $key, $value)\n *\n * @param string $key\n * @param int $count\n- * @param $value $value\n+ * @param mixed $value\n * @return int|false\n */\n public function lrem($key, $count, $value)", "filename": "src/Illuminate/Redis/Connections/PhpRedisConnection.php", "status": "modified" }, { "diff": "@@ -5,10 +5,11 @@\n use Redis;\n use RedisCluster;\n use Illuminate\\Support\\Arr;\n+use Illuminate\\Contracts\\Redis\\Connector;\n use Illuminate\\Redis\\Connections\\PhpRedisConnection;\n use Illuminate\\Redis\\Connections\\PhpRedisClusterConnection;\n \n-class PhpRedisConnector\n+class PhpRedisConnector implements Connector\n {\n /**\n * Create a new clustered PhpRedis connection.", "filename": "src/Illuminate/Redis/Connectors/PhpRedisConnector.php", "status": "modified" }, { "diff": "@@ -4,10 +4,11 @@\n \n use Predis\\Client;\n use Illuminate\\Support\\Arr;\n+use Illuminate\\Contracts\\Redis\\Connector;\n use Illuminate\\Redis\\Connections\\PredisConnection;\n use Illuminate\\Redis\\Connections\\PredisClusterConnection;\n \n-class PredisConnector\n+class PredisConnector implements Connector\n {\n /**\n * Create a new clustered Predis connection.", "filename": "src/Illuminate/Redis/Connectors/PredisConnector.php", "status": "modified" }, { "diff": "@@ -26,6 +26,13 @@ class RedisManager implements Factory\n */\n protected $driver;\n \n+ /**\n+ * The registered custom driver creators.\n+ *\n+ * @var array\n+ */\n+ protected $customCreators = [];\n+\n /**\n * The Redis server configurations.\n *\n@@ -147,10 +154,16 @@ protected function configure(Connection $connection, $name)\n /**\n * Get the connector instance for the current driver.\n *\n- * @return \\Illuminate\\Redis\\Connectors\\PhpRedisConnector|\\Illuminate\\Redis\\Connectors\\PredisConnector\n+ * @return \\Illuminate\\Contracts\\Redis\\Connector\n */\n protected function connector()\n {\n+ $customCreator = $this->customCreators[$this->driver] ?? null;\n+\n+ if ($customCreator) {\n+ return call_user_func($customCreator);\n+ }\n+\n switch ($this->driver) {\n case 'predis':\n return new Connectors\\PredisConnector;\n@@ -215,6 +228,20 @@ public function setDriver($driver)\n $this->driver = $driver;\n }\n \n+ /**\n+ * Register a custom driver creator Closure.\n+ *\n+ * @param string $driver\n+ * @param \\Closure $callback\n+ * @return $this\n+ */\n+ public function extend($driver, \\Closure $callback)\n+ {\n+ $this->customCreators[$driver] = $callback->bindTo($this, $this);\n+\n+ return $this;\n+ }\n+\n /**\n * Pass methods onto the default Redis connection.\n *", "filename": "src/Illuminate/Redis/RedisManager.php", "status": "modified" }, { "diff": "@@ -32,6 +32,13 @@ class Store implements Session\n */\n protected $attributes = [];\n \n+ /**\n+ * The session attributes when started.\n+ *\n+ * @var array\n+ */\n+ protected $originalAttributes = [];\n+\n /**\n * The session handler implementation.\n *\n@@ -84,7 +91,7 @@ public function start()\n */\n protected function loadSession()\n {\n- $this->attributes = array_merge($this->attributes, $this->readFromHandler());\n+ $this->originalAttributes = $this->attributes = array_merge($this->attributes, $this->readFromHandler());\n }\n \n /**\n@@ -123,11 +130,14 @@ protected function prepareForUnserialize($data)\n */\n public function save()\n {\n+ $isDirty = $this->isDirty();\n $this->ageFlashData();\n \n- $this->handler->write($this->getId(), $this->prepareForStorage(\n- serialize($this->attributes)\n- ));\n+ if ($isDirty) {\n+ $this->handler->write($this->getId(), $this->prepareForStorage(\n+ serialize($this->attributes)\n+ ));\n+ }\n \n $this->started = false;\n }\n@@ -669,4 +679,14 @@ public function setRequestOnHandler($request)\n $this->handler->setRequest($request);\n }\n }\n+\n+ /**\n+ * Determine if the session data has changed since loaded.\n+ *\n+ * @return bool\n+ */\n+ protected function isDirty()\n+ {\n+ return $this->originalAttributes !== $this->attributes;\n+ }\n }", "filename": "src/Illuminate/Session/Store.php", "status": "modified" }, { "diff": "@@ -246,7 +246,7 @@ protected function getDateTime($value)\n return Date::parse($value);\n }\n \n- return new DateTime($value);\n+ return date_create($value) ?: null;\n } catch (Exception $e) {\n //\n }", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -63,7 +63,7 @@ public function test_before_can_allow_guests()\n $gate = new Gate(new Container, function () {\n });\n \n- $gate->before(function (?StdClass $user) {\n+ $gate->before(function (?stdClass $user) {\n return true;\n });\n \n@@ -75,7 +75,7 @@ public function test_after_can_allow_guests()\n $gate = new Gate(new Container, function () {\n });\n \n- $gate->after(function (?StdClass $user) {\n+ $gate->after(function (?stdClass $user) {\n return true;\n });\n \n@@ -87,11 +87,11 @@ public function test_closures_can_allow_guest_users()\n $gate = new Gate(new Container, function () {\n });\n \n- $gate->define('foo', function (?StdClass $user) {\n+ $gate->define('foo', function (?stdClass $user) {\n return true;\n });\n \n- $gate->define('bar', function (StdClass $user) {\n+ $gate->define('bar', function (stdClass $user) {\n return false;\n });\n \n@@ -148,19 +148,19 @@ public function test_before_and_after_callbacks_can_allow_guests()\n $gate = new Gate(new Container, function () {\n });\n \n- $gate->before(function (?StdClass $user) {\n+ $gate->before(function (?stdClass $user) {\n $_SERVER['__laravel.gateBefore'] = true;\n });\n \n- $gate->after(function (?StdClass $user) {\n+ $gate->after(function (?stdClass $user) {\n $_SERVER['__laravel.gateAfter'] = true;\n });\n \n- $gate->before(function (StdClass $user) {\n+ $gate->before(function (stdClass $user) {\n $_SERVER['__laravel.gateBefore2'] = true;\n });\n \n- $gate->after(function (StdClass $user) {\n+ $gate->after(function (stdClass $user) {\n $_SERVER['__laravel.gateAfter2'] = true;\n });\n \n@@ -818,7 +818,7 @@ class AccessGateTestGuestNullableInvokable\n {\n public static $calledMethod = null;\n \n- public function __invoke(?StdClass $user)\n+ public function __invoke(?stdClass $user)\n {\n static::$calledMethod = 'Nullable __invoke was called';\n \n@@ -961,12 +961,12 @@ public function update($user, AccessGateTestDummy $dummy)\n \n class AccessGateTestPolicyThatAllowsGuests\n {\n- public function before(?StdClass $user)\n+ public function before(?stdClass $user)\n {\n $_SERVER['__laravel.testBefore'] = true;\n }\n \n- public function edit(?StdClass $user, AccessGateTestDummy $dummy)\n+ public function edit(?stdClass $user, AccessGateTestDummy $dummy)\n {\n return true;\n }\n@@ -979,12 +979,12 @@ public function update($user, AccessGateTestDummy $dummy)\n \n class AccessGateTestPolicyWithNonGuestBefore\n {\n- public function before(StdClass $user)\n+ public function before(stdClass $user)\n {\n $_SERVER['__laravel.testBefore'] = true;\n }\n \n- public function edit(?StdClass $user, AccessGateTestDummy $dummy)\n+ public function edit(?stdClass $user, AccessGateTestDummy $dummy)\n {\n return true;\n }", "filename": "tests/Auth/AuthAccessGateTest.php", "status": "modified" }, { "diff": "@@ -523,6 +523,22 @@ public function testAssertJsonValidationErrorMessagesMultipleMessages()\n $testResponse->assertJsonValidationErrors(['one' => 'foo', 'two' => 'bar']);\n }\n \n+ public function testAssertJsonValidationErrorMessagesMultipleMessagesCanFail()\n+ {\n+ $this->expectException(AssertionFailedError::class);\n+\n+ $data = [\n+ 'status' => 'ok',\n+ 'errors' => ['one' => 'foo', 'two' => 'bar'],\n+ ];\n+\n+ $testResponse = TestResponse::fromBaseResponse(\n+ (new Response)->setContent(json_encode($data))\n+ );\n+\n+ $testResponse->assertJsonValidationErrors(['one' => 'foo', 'three' => 'baz']);\n+ }\n+\n public function testAssertJsonValidationErrorMessagesMixed()\n {\n $data = [", "filename": "tests/Foundation/FoundationTestResponseTest.php", "status": "modified" }, { "diff": "@@ -15,7 +15,7 @@ class HttpJsonResponseTest extends TestCase\n /**\n * @dataProvider setAndRetrieveDataProvider\n *\n- * @param $data\n+ * @param mixed $data\n */\n public function testSetAndRetrieveData($data): void\n {", "filename": "tests/Http/HttpJsonResponseTest.php", "status": "modified" }, { "diff": "@@ -179,6 +179,33 @@ public function test_custom_pivot_class_using_sync()\n $this->assertNotEmpty($results['detached']);\n }\n \n+ public function test_custom_pivot_class_using_update_existing_pivot()\n+ {\n+ Carbon::setTestNow('2017-10-10 10:10:10');\n+\n+ $post = Post::create(['title' => Str::random()]);\n+ $tag = TagWithCustomPivot::create(['name' => Str::random()]);\n+\n+ DB::table('posts_tags')->insert([\n+ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'],\n+ ]);\n+\n+ // Test on actually existing pivot\n+ $this->assertEquals(\n+ 1,\n+ $post->tagsWithCustomExtraPivot()->updateExistingPivot($tag->id, ['flag' => 'exclude'])\n+ );\n+ foreach ($post->tagsWithCustomExtraPivot as $tag) {\n+ $this->assertEquals('exclude', $tag->pivot->flag);\n+ }\n+\n+ // Test on non-existent pivot\n+ $this->assertEquals(\n+ 0,\n+ $post->tagsWithCustomExtraPivot()->updateExistingPivot(0, ['flag' => 'exclude'])\n+ );\n+ }\n+\n public function test_attach_method()\n {\n $post = Post::create(['title' => Str::random()]);\n@@ -776,6 +803,14 @@ public function tagsWithCustomPivot()\n ->withTimestamps();\n }\n \n+ public function tagsWithCustomExtraPivot()\n+ {\n+ return $this->belongsToMany(TagWithCustomPivot::class, 'posts_tags', 'post_id', 'tag_id')\n+ ->using(PostTagPivot::class)\n+ ->withTimestamps()\n+ ->withPivot('flag');\n+ }\n+\n public function tagsWithCustomPivotClass()\n {\n return $this->belongsToMany(TagWithCustomPivot::class, PostTagPivot::class, 'post_id', 'tag_id');", "filename": "tests/Integration/Database/EloquentBelongsToManyTest.php", "status": "modified" }, { "diff": "@@ -68,7 +68,7 @@ public function testExpiredJobsArePopped($driver)\n /**\n * @dataProvider redisDriverProvider\n *\n- * @param $driver\n+ * @param mixed $driver\n *\n * @throws \\Exception\n */", "filename": "tests/Queue/RedisQueueIntegrationTest.php", "status": "modified" }, { "diff": "@@ -0,0 +1,88 @@\n+<?php\n+\n+namespace Illuminate\\Tests\\Redis;\n+\n+use PHPUnit\\Framework\\TestCase;\n+use Illuminate\\Redis\\RedisManager;\n+use Illuminate\\Foundation\\Application;\n+use Illuminate\\Contracts\\Redis\\Connector;\n+\n+class RedisManagerExtensionTest extends TestCase\n+{\n+ /**\n+ * Redis manager instance.\n+ *\n+ * @var RedisManager\n+ */\n+ protected $redis;\n+\n+ protected function setUp(): void\n+ {\n+ parent::setUp();\n+\n+ $this->redis = new RedisManager(new Application(), 'my_custom_driver', [\n+ 'default' => [\n+ 'host' => 'some-host',\n+ 'port' => 'some-port',\n+ 'database' => 5,\n+ 'timeout' => 0.5,\n+ ],\n+ 'clusters' => [\n+ 'my-cluster' => [\n+ [\n+ 'host' => 'some-host',\n+ 'port' => 'some-port',\n+ 'database' => 5,\n+ 'timeout' => 0.5,\n+ ],\n+ ],\n+ ],\n+ ]);\n+\n+ $this->redis->extend('my_custom_driver', function () {\n+ return new FakeRedisConnnector();\n+ });\n+ }\n+\n+ public function test_using_custom_redis_connector_with_single_redis_instance()\n+ {\n+ $this->assertEquals(\n+ 'my-redis-connection', $this->redis->resolve()\n+ );\n+ }\n+\n+ public function test_using_custom_redis_connector_with_redis_cluster_instance()\n+ {\n+ $this->assertEquals(\n+ 'my-redis-cluster-connection', $this->redis->resolve('my-cluster')\n+ );\n+ }\n+}\n+\n+class FakeRedisConnnector implements Connector\n+{\n+ /**\n+ * Create a new clustered Predis connection.\n+ *\n+ * @param array $config\n+ * @param array $options\n+ * @return \\Illuminate\\Contracts\\Redis\\Connection\n+ */\n+ public function connect(array $config, array $options)\n+ {\n+ return 'my-redis-connection';\n+ }\n+\n+ /**\n+ * Create a new clustered Predis connection.\n+ *\n+ * @param array $config\n+ * @param array $clusterOptions\n+ * @param array $options\n+ * @return \\Illuminate\\Contracts\\Redis\\Connection\n+ */\n+ public function connectToCluster(array $config, array $clusterOptions, array $options)\n+ {\n+ return 'my-redis-cluster-connection';\n+ }\n+}", "filename": "tests/Redis/RedisManagerExtensionTest.php", "status": "added" } ] }
{ "body": "- Laravel Version: 5.4\r\n- PHP Version:7.1\r\n- Database Driver & Version:\r\n\r\n### Description:\r\nWe're seeing a lot of issues with concurrent requests to the server where session information is lost. Seeing on other forums and discussions on the slack channels, I see a lot of use cases where concurrent requests cause for session data to be lost.\r\n\r\nMuch of the issues could in my opinion be prevented if not ALL session data is stored at the same time, but if laravel would only update session data for those keys that actually require update.\r\n\r\nIn our project, for instance, we are having a polling mechanism that asks the server for the current session state; each such request however SAVES the session data in its entirety. If - at the same time - the user is doing a rest request to authenticate, or to log out, or basically to do any action that might require session data to be updated, we're having a lot of risks of the requests to impact one another.\r\n\r\nrequest A: POST/auth/login\r\nrequest B: GET /session/state\r\n\r\nif both these requests are sent to the server, B updates the session because user logs in, but request A was already started, and saves the session after that, the authentication information is lost, and the user is logged out again, even though he just authenticated.\r\n\r\nI think it's a \"big\" change, but it would be better if only session data that is changed, is being saved. at this time, the entire session data is always being stored, which isn't desirable.\r\n\r\nAdding a key to the method that stores data will be breaking for all drivers, and may impact existing users that have implemented drivers. therefore, I believe it would be advisable that laravel checks the driver method using reflection to see if the driver already supports key-based storing, and if not should log a warning and fallback to old mechanism. In later laravel version (6?), we could deprecate the old way of dealing with it.\r\n\r\nAny thoughts?\r\n\r\n### Steps To Reproduce:\r\n", "comments": [ { "body": "Just wanted to add that I noticed the startSession middleware is terminable.\r\nThe terminate method is... storing session.\r\n\r\nSince the terminate is executed at the very end of a request (even after sending data to the client), it seems to be a potentially long time between the start of the session, and the storage at terminating middleware, and this definitely explains why I'm seeing such strange behaviour.\r\n\r\nI also see that it seems to be calling an ageing method of some sort for flash messages, which might explain why this has been done.\r\n\r\nI really think this needs to be tackled in some way :-)", "created_at": "2017-03-02T12:57:41Z" }, { "body": "This is a \"known\" issue since at least Laravel 5.1. https://github.com/laravel/framework/issues/14385", "created_at": "2017-03-02T13:40:56Z" }, { "body": "Hi @sisve!\r\nThanks for referencing that issue.\r\nI think mine is a bit different though. I'm not sure that the session is completely wiped out, and the suggested solution in that issue won't fix the real issue that we have.\r\n\r\nI'm mainly concerned that - when I checked the bits of code you sent me through slack - there is a small design issue that you won't be able to fix by migrating to database or to redis either.\r\nIf I understood correctly from what I briefly saw the session middleware that creates the session is terminable, meaning there is logic in the terminate() method of that middleware.\r\n\r\nIn that temination, the session data is saved (I'm thinking because they want to get rid of the flash messages, hence they wait for data to have been sent to the browser before they \"age\"/remove the flash messages from the session.\r\n\r\nThe big issue there is that - no matter what little piece of information the session you want to update, ALL session data is being saved again. So even data that we didn't want to update, is being saved. So no matter what driver you have behind that, I don't think this will be fixed.\r\n\r\nConsidering that it's in the terminate of the middleware, you are creating a big timeframe between the start of the request (in which session information is being retrieved), and the final save. If another concurrent request has meanwhile taken place, you might be saving outdated information to the session.\r\n\r\nI believe that when we can avoid the entire session being saved, but make saves key-based, a lot will be fixed, for many use cases. I understand that the flash messages need to be erased, but if we can achieve that by just updating the session.flash data, and not the entire session, it will be more secure.\r\n\r\nThe solution of not allowing multiple requests is theoretically a good suggestion; in practice it's not. I know a lot of users - including myself - tend to open multiple tabs of the same app because it makes switching easier if you need to compare stuff for instance; you can not and should never trust that you can control the number of requests that come in and in what order.\r\n\r\nFurthermore - the whole idea of sessions is that the information held by the session is available throughout... the session. I don't think it's wise to update session information that shouldn't be touched.\r\n\r\nI hope this makes sense. I LOVE Laravel, but this is a real issue that I think we should be able to tackle.\r\n\r\n\r\nCheers,\r\nDavid.", "created_at": "2017-03-02T15:24:02Z" }, { "body": "I'm also thinking it might be interesting to load the flash messages at the BEGINNING of the request, save the session there, and get rid of the terminate process. The flash messages are supposed to just live between two requests, right? So you could probably get them at the beginning, and try to eliminate the session save at the end. But that would be a workaround really. I still believe it's a minor design issue to save data that might have been already updated by another request, since it's supposed to be session-wide.\r\n\r\nThis whole issue reminds me again of why I always try to eliminate anything that goes into sessions :-)", "created_at": "2017-03-02T15:29:29Z" }, { "body": "Having the exact same issue. Our app is basically useless because of this, and the user experience is terrible, as in load the page (lots of concurrent requests), at the same time issue login request, and we loose the session, and the user is obviously not logged in, because stale session data is written to disc.\r\n\r\nThe obvious fix would be to stop using sessions and switch to a stateless token based scheme, but that would mean refactoring lots of application code, so another fix could be to change the terminate flow to something along the line of:\r\n1. Lock the session file\r\n2. Reload the data\r\n3. Merge in delta changes\r\n4. Write the file\r\n5. Release the lock\r\n\r\nObviously locking sucks, but what else could possible be done to fix this issue?\r\n\r\nThe biggest problem in this fix is that this would be really hard to implement into the session Store implementation as it is today, because it's decoupled from the FileSessionHandler. That makes a lot of sense, but it makes this hard to fix.", "created_at": "2017-08-31T10:43:11Z" }, { "body": "storing session data to files is a worst case if you don't use ram as storage. If resource can be modified by different software , always use locking of data , at least mutexes", "created_at": "2019-03-22T19:11:51Z" }, { "body": "I can implement a \"fix\" for this by simply extending the session expiration in storage if the session data is exactly the same as it was at the beginning of the request. However, this would only work for certain drivers. I think I could make it work for the following drivers: database, redis, memcached, DynamoDB (maybe)...\r\n\r\nI would have to add a `touch` method to the Cache contract, so it would be a breaking change.\r\n\r\nI know it will definitely not be possible on the file driver.\r\n\r\nI'm hesitant to implement it because this would not solve the \"problem\" of two concurrent requests modifying the session at the same time. Note this is also a \"problem\" in other web frameworks such as Rails as well. ", "created_at": "2020-04-30T20:17:08Z" }, { "body": "what if we allow the user to somehow mark some routes as \"concurrently\",\r\nSo the expiration time does not need to be updated on the cookie when a request hits that route.\r\nBasically this allows the server to respond without a cookie.(only on the routes which are marked as \"concurenty.\")\r\n\r\nThe user can accept this limitation (not updating cookie expiration time) to alleviate the problem quite a bit.\r\nI remember the solution I had in mind was impossible at last, because we had to include a cookie on each and every response.\r\n@taylorotwell ", "created_at": "2020-04-30T22:07:28Z" }, { "body": "> I can implement a \"fix\" for this by simply extending the session expiration in storage if the session data is exactly the same as it was at the beginning of the request. However, this would only work for certain drivers. I think I could make it work for the following drivers: database, redis, memcached, DynamoDB (maybe)...\n> \n> I would have to add a `touch` method to the Cache contract, so it would be a breaking change.\n> \n> I know it will definitely not be possible on the file driver.\n> \n> I'm hesitant to implement it because this would not solve the \"problem\" of two concurrent requests modifying the session at the same time. Note this is also a \"problem\" in other web frameworks such as Rails as well. \n\nI think we should have it for these driver as its possible it would be good", "created_at": "2020-05-01T04:43:00Z" }, { "body": "Could we go the ASP.NET way and implement session locking? When routes are marked for write access to sessions they take out an exclusive lock so that other requests that wants to write to the session are blocked until the first is done.\r\n\r\nThis would effectively execute all requests with write-access to the session one at a time.\r\n\r\nRef: https://docs.microsoft.com/en-us/dotnet/api/system.web.sessionstate.sessionstatebehavior\r\n", "created_at": "2020-05-01T05:22:06Z" }, { "body": "I agree with @sisve’s comment 👍", "created_at": "2020-05-01T07:20:52Z" }, { "body": "@sisve how do you recommend determining which requests have \"write access\" to the session?", "created_at": "2020-05-01T18:00:31Z" }, { "body": "https://github.com/laravel/framework/pull/32636\r\n\r\nLet's continue discussion here...", "created_at": "2020-05-01T19:18:25Z" }, { "body": "@taylorotwell by adding a route middleware?", "created_at": "2020-05-01T19:36:10Z" } ], "number": 18187, "title": "Store session data per key" }
{ "body": "This is a re submission of #29399 \r\nrelated issue : #18187 \r\n\r\nThis is a re submission of #29399 , With the difference that, now we always send the cookie to the client, no matter what.\r\nThis PR brings help to the issue, Only (and only) in cases where the session ID is not regenerated by the other concurrent request and only the session data is modified.\r\n\r\nAlso it may save an unnecessary I/O operation, at the end of the request.\r\n\r\nI thought a lot, but I was not able to find a better solution to cover more cases, unfortunately.", "number": 29407, "review_comments": [ { "body": "@imanghafoori1 The `isDirty` method should be added to the `Session` interface (which is a breaking change and should target master), otherwise this will break for all other session store implementations. If this fix must go into 5.8 too then we should add a `method_exists` check here before calling the `isDirty` method.", "created_at": "2019-08-04T12:05:45Z" }, { "body": "thank for mentioning that.\r\nI missed it", "created_at": "2019-08-04T12:38:54Z" } ], "title": "[5.8] Alleviate session race problem" }
{ "commits": [ { "message": "Alleviate session race problem." } ], "files": [ { "diff": "@@ -32,6 +32,13 @@ class Store implements Session\n */\n protected $attributes = [];\n \n+ /**\n+ * The session attributes when started.\n+ *\n+ * @var array\n+ */\n+ protected $originalAttributes = [];\n+\n /**\n * The session handler implementation.\n *\n@@ -84,7 +91,7 @@ public function start()\n */\n protected function loadSession()\n {\n- $this->attributes = array_merge($this->attributes, $this->readFromHandler());\n+ $this->originalAttributes = $this->attributes = array_merge($this->attributes, $this->readFromHandler());\n }\n \n /**\n@@ -123,11 +130,14 @@ protected function prepareForUnserialize($data)\n */\n public function save()\n {\n+ $isDirty = $this->isDirty();\n $this->ageFlashData();\n \n- $this->handler->write($this->getId(), $this->prepareForStorage(\n- serialize($this->attributes)\n- ));\n+ if ($isDirty) {\n+ $this->handler->write($this->getId(), $this->prepareForStorage(\n+ serialize($this->attributes)\n+ ));\n+ }\n \n $this->started = false;\n }\n@@ -669,4 +679,14 @@ public function setRequestOnHandler($request)\n $this->handler->setRequest($request);\n }\n }\n+\n+ /**\n+ * Determine if the session data has changed since loaded.\n+ *\n+ * @return bool\n+ */\n+ protected function isDirty()\n+ {\n+ return $this->originalAttributes !== $this->attributes;\n+ }\n }", "filename": "src/Illuminate/Session/Store.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.6.39\r\n- PHP Version: 7.1.28\r\n- Database Driver & Version: mariadb 10.4\r\n\r\n### Description:\r\n\r\nI'm not 100% sure that this is a bug or intended behaviour but I've been validating an array of values as follows:\r\n\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 2],\r\n];\r\n$rules = [\r\n '*' => 'array',\r\n '*.id' => 'required',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```\r\n\r\nNow if I use the `distinct` rule on the '*.id' column it doesn't work. However if I put it into a non-top-level property, it does eg\r\n\r\n```\r\n$array = [\r\n 'items' => [\r\n ['id' => 1],\r\n ['id' => 2],\r\n ],\r\n];\r\n$rules = [\r\n 'items' => 'array',\r\n 'items.*.id' => 'required|distinct',\r\n];\r\n```\r\n\r\nI guess the question is, are top-level array validation rules supposed to work like this?\r\n\r\n### Steps To Reproduce:\r\n\r\nUsing the following code, the Validator instance will not fire a validation error.\r\n\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 1],\r\n];\r\n$rules = [\r\n '*' => 'array',\r\n '*.id' => 'required|distinct',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```", "comments": [ { "body": "@driesvints This is still an issue in 5.8.29.", "created_at": "2019-07-16T19:24:38Z" }, { "body": "I reproduced it in laravel 5.8 and without ` '*' => 'array', ` it works fine!\r\n\r\n```\r\n$array = [\r\n ['id' => 1],\r\n ['id' => 1],\r\n];\r\n$rules = [\r\n '*.id' => 'required|distinct',\r\n];\r\nValidator::make($array, $rules)->validate();\r\n```\r\nand also it works by changing the order of rules! :\r\n```\r\n$rules = [\r\n '*.id' => 'required|distinct',\r\n '*' => 'array',\r\n];\r\n```\r\n", "created_at": "2019-08-03T06:55:45Z" } ], "number": 29190, "title": "Distinct validation rule not working on top-level array" }
{ "body": "this pr fixes #29190 \r\n\r\nthere is a problem with in_array() in php.\r\nwhen using it without strict mode enabled, it will work in a way that cause unexpected result in laravel validation for distinct array values.\r\nexample :\r\nbelow code return true and makes bug:\r\n\r\n`in_array( \"0.id\", [ 0, 1] );`\r\n\r\nso in this pr i used strict mode just for string values.\r\nif needle is string we can use in_array() in strict mode so finally getPrimaryAttribute method will return primary attribute correctly.\r\nother way it will return \"*\" for all cases.\r\nif you reproduced it in laravel 5.8.30 with exactly values in the issue.\r\n", "number": 29402, "review_comments": [], "title": "[5.8] Fix distinct validation for top level wildcard" }
{ "commits": [ { "message": "this pr fix distinct validation for top level wildcard" } ], "files": [ { "diff": "@@ -443,7 +443,10 @@ protected function getExplicitKeys($attribute)\n protected function getPrimaryAttribute($attribute)\n {\n foreach ($this->implicitAttributes as $unparsed => $parsed) {\n- if (in_array($attribute, $parsed)) {\n+ if (\n+ is_numeric($attribute) ?\n+ in_array($attribute, $parsed) :\n+ in_array($attribute, $parsed, true)) {\n return $unparsed;\n }\n }", "filename": "src/Illuminate/Validation/Validator.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8 (Irrelevant)\r\n- PHP Version: 7.2 (Irrelevant)\r\n- Database Driver & Version: MySql (Irrelevant)\r\n\r\n### Description:\r\nLogging out via `Illuminate\\Auth\\SessionGuard::logout()` updates the user's remember token to a random string, therefore logs the user out in all other devices as well. I guess it is not the intention of the user to logout from other devices as well when they hit logout.\r\n\r\n### Steps To Reproduce:\r\n* log-in to a Laravel app with remember me option in a trusted browser.\r\n* log-in to the same Laravel app in a second browser.\r\n* log-out in the second browser.\r\n* Close the trusted browser and wait for config('session.lifetime').\r\n* Reopen Laravel app in trusted browser. You should be logged in, but you are not.\r\n\r\nTo me it is a bug that logout somehow acts like a \"Logout from all devices\" feature. If there is a reason behind it, it should be documented and letting us know how safely disable it.\r\n\r\n### Reset password\r\nReset password changes remember token as well. It is not that bad though.", "comments": [ { "body": "It must be an intended behaviour because the `SessionGuard` hasn't changed much these past years, and it is actually tested in `\\Illuminate\\Tests\\Integration\\Auth\\AuthenticationTest::test_logging_in_out_via_attempt_remembering()`\r\n\r\n```php\r\n public function test_logging_in_out_via_attempt_remembering()\r\n {\r\n $this->assertTrue(\r\n $this->app['auth']->attempt(['email' => 'email', 'password' => 'password'], true)\r\n );\r\n $this->assertInstanceOf(AuthenticationTestUser::class, $this->app['auth']->user());\r\n $this->assertTrue($this->app['auth']->check());\r\n $this->assertNotNull($this->app['auth']->user()->getRememberToken());\r\n\r\n $oldToken = $this->app['auth']->user()->getRememberToken();\r\n $user = $this->app['auth']->user();\r\n\r\n $this->app['auth']->logout();\r\n\r\n $this->assertNotNull($user->getRememberToken());\r\n $this->assertNotEquals($oldToken, $user->getRememberToken());\r\n }\r\n```\r\n\r\n**But I definitely agree with you that login out (or in) shouldn't cycle the remember token.**\r\n\r\n--- \r\n\r\nThe method `\\Illuminate\\Auth\\EloquentUserProvider::retrieveByToken()` return null if the user exists but its token (in the DB) is not the one from the remember cookie.\r\n\r\nSo, yeah, _changing the remember token effectively log-out from all devices where the user has an obsolete session_.\r\n\r\nBut funny thing (but also an unintended behavior ?): the `SessionGuard::logoutOtherDevices()` method do not change the remember token, just the password. \r\nIt means that if you have a remember cookie, with the old password but the right user id and remember token _and that you do not use the `AuthenticateSession` middleware_ you will still be considered as logged-in.\r\n\r\nThe `\\Illuminate\\Auth\\Middleware\\Authenticate` middleware and the Session guard do not check the password from the remember cookie: the existence of the user id, and the match of the remember tokens is enough to log the user in.\r\n\r\n---\r\n\r\nIf someone from the Laravel team could confirm that the current behaviour is indeed bogus, my suggestion for a fix (of both behaviours described) would be simply to cycle the remember token in `logoutOtherDevices()` but not in `logout()`.", "created_at": "2019-07-27T20:36:24Z" }, { "body": "I agree that this probably is a bug. Welcoming help with figuring this out.", "created_at": "2019-08-01T14:56:24Z" }, { "body": "> Laravel also provides a mechanism for invalidating and \"logging out\" a user's sessions that are active on other devices without invalidating the session on their current device. \r\n\r\nJust realized that the current behavior is indeed the correct one and this isn't a bug. \r\n\r\nUse `logout` => logs you out from all devices.\r\nUse `logoutOtherDevices` logs you out from all devices but the current one.\r\n\r\nMaybe the docs could be updated on this though.", "created_at": "2019-08-01T15:12:06Z" }, { "body": "`logoutOtherDevices` requires the user entering their password though. \r\n\r\n`logout` does it across all devices from really doesn't seem like the expected behaviour here - what other website do you log out from then then logs you out across all other devices?\r\n\r\nIs there a sanctioned way to log the user out on just their current device?", "created_at": "2019-08-01T16:03:10Z" }, { "body": "@dwightwatson no, don't think so. Maybe this could be a good new feature as a `logoutCurrentDevice` method?", "created_at": "2019-08-01T16:08:49Z" }, { "body": "@driesvints I am a little confused about why this issue is closed.", "created_at": "2019-08-01T20:18:51Z" }, { "body": "@halaei you said: \r\n\r\n> I guess it is not the intention of the user to logout from other devices as well when they hit logout.\r\n\r\nBut it is. Hence is why the issue was closed.", "created_at": "2019-08-02T08:04:40Z" }, { "body": "@driesvints Have you even checked out how logout button works in either of Google, Facebook, Instagram, Telegram, WhatsApp, GitHub, Gitlab, Bitbucket, Trellto, ...?\r\n\r\nI hope it is a soon to be fixed issue no matter the disagreement. But it is not my first time I bring an issue regarding auth and it gets closed without being fixed. I need a chance to discuss it in a constructive way, but I don't see enough interest :(", "created_at": "2019-08-02T08:50:32Z" }, { "body": "@halei again: this isn't a bug but the expected behavior. Also see the discussion on the PR by @dwightwatson here: https://github.com/laravel/framework/pull/29376", "created_at": "2019-08-02T08:56:05Z" }, { "body": "@driesvints Having a wrong expected behaviour is a bug. Your exception is against all the majority of popular applications, sites and games.", "created_at": "2019-08-02T09:10:16Z" }, { "body": "> Having a wrong expected behaviour is a bug.\r\n\r\nThe behaviour was introduce in `v5.0.30` and has gone through 2 LTS and 6 major releases (See commit <https://github.com/laravel/framework/commit/c5ac19e1eb809c486b04e0f6867aeaf0e81e7afd>). It was introduced based on proposal <https://github.com/laravel/framework/issues/2444>. \r\n\r\nIt's not a bug because it was changed to cover specific behaviour. What you are asking is a different behaviour to be covered as well because you have a requirement for it.", "created_at": "2019-08-02T09:33:06Z" }, { "body": "@crynobone I seems the behaviour exists in prior versions as well:\r\nLaravel 4.0:\r\n```php\r\nclass Guard {...\r\n\tpublic function logout()\r\n\t{\r\n\t\t$user = $this->user();\r\n\t\t// If we have an event dispatcher instance, we can fire off the logout event\r\n\t\t// so any further processing can be done. This allows the developer to be\r\n\t\t// listening for anytime a user signs out of this application manually.\r\n\t\t$this->clearUserDataFromStorage();\r\n\t\tif ( ! is_null($this->user))\r\n\t\t{\r\n\t\t\t$this->refreshRememberToken($user);\r\n\t\t}\r\n...\r\n```\r\nEven if you are right about when this behaviour was introduced, it is still a bug introduced by wrong understandings about how logout button should work.\r\n\r\nI don't know why you make it so difficult and why you are so attached to this bug. What do you like about this bug:\r\n1. When you login to your google account on your friends computer and then you log out when you are done, do you expect to be logged out on your own mobile as well?\r\n2. If someone tells you Laravel Auth is terrible because it has inconvenient behaviours and you shouldn't use it in your projects, referring to issues like this one, how can you defend Laravel?\r\n\r\nAgain this is not my first time I bring such issues about Auth and the core team closes the issue without any fix. As an occasional contributor to Laravel source code I am telling you it is a terrible attitude and it hurts a lot.", "created_at": "2019-08-02T10:14:43Z" }, { "body": "> @driesvints Having a wrong expected behaviour is a bug. Your exception is against all the majority of popular applications, sites and games.\r\n\r\nLike @crynobone said, this behavior has been in the core for quite a while already. If we would change it now it would be too much of a breaking change for everyone relying on this behavior.\r\n\r\n> wrong understandings about how logout button should work\r\n\r\nYou're basically saying here that your way is the only correct way.\r\n\r\n> it is a terrible attitude and it hurts a lot.\r\n\r\nWe need to account for more people than just you. There's so many people using the framework. If we change this default behavior then it'll break someone else's app. \r\n\r\nLet's see how the PR from above goes. At least you'll then have a method which you can use for your use-case.", "created_at": "2019-08-02T11:26:22Z" }, { "body": "> You're basically saying here that your way is the only correct way.\r\n\r\nYes exactly. I am 100% against any other ways regarding how logout button should work.\r\n\r\n> We need to account for more people than just you.\r\n\r\nI understand the value of your job. You are doing amazing and I am thankful. What I am trying to say is to give feedback about an aspect that I believe needs change: the way you close issues like this. Again if we can't understand each other regarding this, it is still fine.\r\n\r\n> There's so many people using the framework. If we change this default behavior then it'll break someone else's app.\r\n\r\nWe shouldn't consider breaking changes between major releases when fixing a bug or improving a behaviour. We need to ensure smooth upgrade process though.\r\n\r\n> Let's see how the PR from above goes. At least you'll then have a method which you can use for your use-case.\r\n\r\nI hope the PR goes well. Also please consider a chance for my use-case being the default one, because it is not really only \"my\" use-case.\r\nSorry for all the trouble.\r\n\r\n", "created_at": "2019-08-02T11:53:23Z" }, { "body": "> the way you close issues like this. \r\n\r\nBut this issue tracker isn't for feature requests or if you want to change additional behavior. It's only for tracking bugs. That's clearly indicated when you open up an issue with the issue templates. That's why I closed it. I understand that you opened the issue first because you thought it was a bug. But it's better now if you take this up in an issue on the ideas repo for further discussion.\r\n\r\n> We shouldn't consider breaking changes between major releases when fixing a bug or improving a behaviour. We need to ensure smooth upgrade process though.\r\n\r\nWe should definitely do so. Letting people upgrade without too much hassle is always a better choice unless a breaking change is really warranted. The next Cashier release, for example, will have lots of breaking changes but that's because the underlying Stripe API also changed a lot so it was warranted.\r\n\r\n> I hope the PR goes well. Also please consider a chance for my use-case being the default one, because it is not really only \"my\" use-case.\r\n\r\nYou can always attempt a new pr at the same time and let Taylor choose which one he thinks is the better approach.\r\n\r\n> Sorry for all the trouble.\r\n\r\nNo worries. We're all adults. It's good that you brought this to our attention because I wasn't aware of the default behavior either. We all learned something. Overall I really like your comments and replies on the Laravel repositories. You're always a great help 👍", "created_at": "2019-08-02T12:21:08Z" } ], "number": 29244, "title": "Logout cycles remember token" }
{ "body": "This PR resolves the issue described in #29244 where logging out on one device will actually log you out on all devices. This seems like unexpected behaviour to me - most sites wouldn't log you out everywhere like this.\r\n\r\nThis changes the `logout` method to not cycle the remember token, and adds another method `logoutAllDevices` (which sits alongside `logoutOtherDevices`) so that developers can opt-in to this behaviour if that is what they are after.\r\n\r\nIn the linked issue Dries suggested adding `logoutCurrentDevice` instead - I'm happy to make that alternative PR if that's what you guys prefer - but I did want to suggest initially that I think this should be the default behaviour of `logout`.", "number": 29376, "review_comments": [], "title": "[6.0] Split out logoutAllDevices method" }
{ "commits": [ { "message": "Split out logoutAllDevices method" }, { "message": "Update integration tests" } ], "files": [ { "diff": "@@ -487,10 +487,6 @@ public function logout()\n // listening for anytime a user signs out of this application manually.\n $this->clearUserDataFromStorage();\n \n- if (! is_null($this->user) && ! empty($user->getRememberToken())) {\n- $this->cycleRememberToken($user);\n- }\n-\n if (isset($this->events)) {\n $this->events->dispatch(new Events\\Logout($this->name, $user));\n }\n@@ -503,6 +499,22 @@ public function logout()\n $this->loggedOut = true;\n }\n \n+ /**\n+ * Log the user out of the application on all devices.\n+ *\n+ * @return void\n+ */\n+ public function logoutAllDevices()\n+ {\n+ $user = $this->user();\n+\n+ if (! is_null($user) && ! empty($user->getRememberToken())) {\n+ $this->cycleRememberToken($user);\n+ }\n+\n+ $this->logout();\n+ }\n+\n /**\n * Remove the user data from the session and cookies.\n *", "filename": "src/Illuminate/Auth/SessionGuard.php", "status": "modified" }, { "diff": "@@ -259,18 +259,15 @@ public function testUserIsSetToRetrievedUser()\n $this->assertSame($user, $mock->getUser());\n }\n \n- public function testLogoutRemovesSessionTokenAndRememberMeCookie()\n+ public function testLogoutRemovesRememberMeCookie()\n {\n [$session, $provider, $request, $cookie] = $this->getMocks();\n $mock = $this->getMockBuilder(SessionGuard::class)->setMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();\n $mock->setCookieJar($cookies = m::mock(CookieJar::class));\n $user = m::mock(Authenticatable::class);\n- $user->shouldReceive('getRememberToken')->once()->andReturn('a');\n- $user->shouldReceive('setRememberToken')->once();\n $mock->expects($this->once())->method('getName')->will($this->returnValue('foo'));\n $mock->expects($this->once())->method('getRecallerName')->will($this->returnValue('bar'));\n $mock->expects($this->once())->method('recaller')->will($this->returnValue('non-null-cookie'));\n- $provider->shouldReceive('updateRememberToken')->once();\n \n $cookie = m::mock(Cookie::class);\n $cookies->shouldReceive('forget')->once()->with('bar')->andReturn($cookie);\n@@ -325,6 +322,42 @@ public function testLogoutDoesNotSetRememberTokenIfNotPreviouslySet()\n $mock->logout();\n }\n \n+ public function testLogoutAllDevicesRemovesSessionTokenAndRememberMeCookie()\n+ {\n+ [$session, $provider, $request, $cookie] = $this->getMocks();\n+ $mock = $this->getMockBuilder(SessionGuard::class)->setMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();\n+ $mock->setCookieJar($cookies = m::mock(CookieJar::class));\n+ $user = m::mock(Authenticatable::class);\n+ $user->shouldReceive('getRememberToken')->once()->andReturn('a');\n+ $user->shouldReceive('setRememberToken')->once();\n+ $mock->expects($this->once())->method('getName')->will($this->returnValue('foo'));\n+ $mock->expects($this->once())->method('getRecallerName')->will($this->returnValue('bar'));\n+ $mock->expects($this->once())->method('recaller')->will($this->returnValue('non-null-cookie'));\n+ $provider->shouldReceive('updateRememberToken')->once();\n+\n+ $cookie = m::mock(Cookie::class);\n+ $cookies->shouldReceive('forget')->once()->with('bar')->andReturn($cookie);\n+ $cookies->shouldReceive('queue')->once()->with($cookie);\n+ $mock->getSession()->shouldReceive('remove')->once()->with('foo');\n+ $mock->setUser($user);\n+ $mock->logoutAllDevices();\n+ $this->assertNull($mock->getUser());\n+ }\n+\n+ public function testLogoutAllDevicesFiresLogoutEvent()\n+ {\n+ [$session, $provider, $request, $cookie] = $this->getMocks();\n+ $mock = $this->getMockBuilder(SessionGuard::class)->setMethods(['clearUserDataFromStorage'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();\n+ $mock->expects($this->once())->method('clearUserDataFromStorage');\n+ $mock->setDispatcher($events = m::mock(Dispatcher::class));\n+ $user = m::mock(Authenticatable::class);\n+ $user->shouldReceive('getRememberToken')->andReturn(null);\n+ $events->shouldReceive('dispatch')->once()->with(m::type(Authenticated::class));\n+ $mock->setUser($user);\n+ $events->shouldReceive('dispatch')->once()->with(m::type(Logout::class));\n+ $mock->logoutAllDevices();\n+ }\n+\n public function testLoginMethodQueuesCookieWhenRemembering()\n {\n [$session, $provider, $request, $cookie] = $this->getMocks();", "filename": "tests/Auth/AuthGuardTest.php", "status": "modified" }, { "diff": "@@ -220,11 +220,26 @@ public function test_logging_in_out_via_attempt_remembering()\n $this->assertTrue($this->app['auth']->check());\n $this->assertNotNull($this->app['auth']->user()->getRememberToken());\n \n+ $this->app['auth']->logout();\n+\n+ $this->assertFalse($this->app['auth']->check());\n+ }\n+\n+ public function test_logging_in_out_all_devices_via_attempt_remembering()\n+ {\n+ $this->assertTrue(\n+ $this->app['auth']->attempt(['email' => 'email', 'password' => 'password'], true)\n+ );\n+ $this->assertInstanceOf(AuthenticationTestUser::class, $this->app['auth']->user());\n+ $this->assertTrue($this->app['auth']->check());\n+ $this->assertNotNull($this->app['auth']->user()->getRememberToken());\n+\n $oldToken = $this->app['auth']->user()->getRememberToken();\n $user = $this->app['auth']->user();\n \n- $this->app['auth']->logout();\n+ $this->app['auth']->logoutAllDevices();\n \n+ $this->assertFalse($this->app['auth']->check());\n $this->assertNotNull($user->getRememberToken());\n $this->assertNotEquals($oldToken, $user->getRememberToken());\n }", "filename": "tests/Integration/Auth/AuthenticationTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.29\r\n- PHP Version: 7.2.20\r\n- Database Driver & Version: mysql Ver 15.1 Distrib 10.1.38-MariaDB\r\n\r\n### Description:\r\nWhenever `php artisan serve` command is run `Laravel development server started: <http://127.0.0.1:8000>` message is shown no matter if the default port is open or closed, either it should show the error message first and then connect to the open port or just connects to the next available port without showing any error.\r\n\r\n\r\n\r\n### Steps To Reproduce:\r\n\r\n- Make sure the default port(8000) is already in use.\r\n- Install the laravel if not already installed, run `php artisan serve` in the console under the root directory.\r\n- The console will show the `Laravel development server started: <http://127.0.0.1:8000>` message\r\n![laravel](https://user-images.githubusercontent.com/35100967/61519220-f954aa80-aa28-11e9-8d6e-5298de90ad2d.png)\r\n\r\n", "comments": [ { "body": "The problem is that we can't put the info message after we've attempted the serve because then the message isn't even shown:\r\n\r\n![Screen Shot 2019-07-19 at 12 27 34](https://user-images.githubusercontent.com/594614/61529044-a24ad780-aa20-11e9-9ac7-8fac14c1b44f.png)\r\n\r\nHere's the handle method:\r\n\r\nhttps://github.com/laravel/framework/blob/1003c27b73f11472c1ebdb9238b839aefddfb048/src/Illuminate/Foundation/Console/ServeCommand.php#L40-L55\r\n\r\nI don't think there's any way to solve this really. Sorry.", "created_at": "2019-07-19T10:28:30Z" }, { "body": "We can use \r\n```php\r\n$connection = @fsockopen($this->host(), $this->port());\r\n\r\n if (is_resource($connection)) {\r\n fclose($connection);\r\n $this->portOffset += 1;\r\n return $this->handle();\r\n } else {\r\n $this->line(\"<info>Laravel development server started:</info> <http://{$this->host()}:{$this->port()}>\");\r\n passthru($this->serverCommand(), $status);\r\n }\r\n\r\n```\r\ncode to fix the issue you are saying.\r\n\r\nIf you want I can send a pull request for this?", "created_at": "2019-07-19T10:33:26Z" }, { "body": "@gopalvirat that works! Feel free to send in a PR. Thanks!", "created_at": "2019-07-19T10:47:42Z" }, { "body": "@driesvints on which branch should I send a pull request?", "created_at": "2019-07-19T11:00:11Z" }, { "body": "This can be sent to 5.8 because I don't see any breaking changes afaik.", "created_at": "2019-07-19T11:08:31Z" }, { "body": "Taylor considers this a no-fix so closing this. Sorry.", "created_at": "2019-07-19T14:58:26Z" }, { "body": "this because of multiple server is running in your device \r\nfor example: 2SERVERS 1.XAMMP AND File Zeila\r\nSolution\r\nClose The ServerOne Of The Server Except YOU Currently Using Server", "created_at": "2023-01-17T20:23:46Z" } ], "number": 29231, "title": "`php artisan serve` showing server started but failed and then connects" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nThis will fix the #29231\r\n\r\n\r\nAs `passthru ( string $command [, int &$return_var ] ) : void` does not return any value on success, there seems to be currently no way to check if the server is failed to start based on the port number. This PR fixes the same by first checking if the port is occupied, if yes, try with another port until it connects and then displays the success message.", "number": 29236, "review_comments": [ { "body": "```suggestion\r\n\r\n return $this->handle();\r\n```", "created_at": "2019-07-19T11:40:25Z" } ], "title": "[5.8] Fixed server started message for invalid port" }
{ "commits": [ { "message": "Fixed server started message for invalid port" }, { "message": "Fixed new line" }, { "message": "Update src/Illuminate/Foundation/Console/ServeCommand.php\n\nCo-Authored-By: Dries Vints <dries.vints@gmail.com>" } ], "files": [ { "diff": "@@ -40,15 +40,16 @@ class ServeCommand extends Command\n public function handle()\n {\n chdir(public_path());\n+ $connection = @fsockopen($this->host(), $this->port());\n \n- $this->line(\"<info>Laravel development server started:</info> <http://{$this->host()}:{$this->port()}>\");\n-\n- passthru($this->serverCommand(), $status);\n-\n- if ($status && $this->canTryAnotherPort()) {\n+ if (is_resource($connection)) {\n+ fclose($connection);\n $this->portOffset += 1;\n \n return $this->handle();\n+ } else {\n+ $this->line(\"<info>Laravel development server started:</info> <http://{$this->host()}:{$this->port()}>\");\n+ passthru($this->serverCommand(), $status);\n }\n \n return $status;", "filename": "src/Illuminate/Foundation/Console/ServeCommand.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.19\r\n- PHP Version: 7.2.12\r\n- Database Driver & Version: -\r\n\r\n### Description:\r\nWhen validating a static key (without wildcard), I cannot use a wildcard a parameter for the required_with rule.\r\n\r\n### Steps To Reproduce:\r\n2 POST data:\r\n- user.*.email => 'email'\r\n- emailContent => 'required_with:user.*.email|string'\r\n\r\n### Test Method:\r\n\r\n public function testRequiredWithWildcard()\r\n {\r\n $trans = $this->getIlluminateArrayTranslator();\r\n $v = new Validator($trans, ['names' => [['first' => 'Taylor']], 'foo' => 'bar'], ['foo' => 'required_with:names.*.first']);\r\n $this->assertTrue($v->passes());\r\n\r\n $v = new Validator($trans, ['names' => [['first' => 'Taylor']]], ['foo' => 'required_with:names.*.first']);\r\n $this->assertFalse($v->passes());\r\n }\r\n\r\nThe second assertion fails as the data \"names.*.first\" does not exists and so the validation passes.", "comments": [ { "body": "Might be related to https://github.com/laravel/framework/issues/26179", "created_at": "2019-01-02T14:32:23Z" }, { "body": "When using the `*` in required_with you the field you're validating also needs to be within in array like the documentation shows:\r\n\r\n![image](https://user-images.githubusercontent.com/463230/80748678-ecea9b80-8aea-11ea-8624-163d81a3a33e.png)\r\n\r\nWhat your code example would do is currently undefined behavior in Laravel. It's undefined in the sense of we do not know if you mean that at least one first name must be present... every element in the array must have one? \r\n\r\nThis is more of a feature request or idea that should be discussed in laravel/ideas where the behavior can actually be defined.", "created_at": "2020-04-30T19:01:10Z" } ], "number": 26957, "title": "Cannot use required_with with a wildcard on a static key" }
{ "body": "This PR – probably – solves #26957 and #26179. In brief:\r\n\r\nUsing wildcard attributes when validating with `require_with`, `require_with_all`, `require_without` and `require_without_all` rules, the validation passes, even the if requested attributes should not pass the truth test.\r\n\r\n------------\r\n\r\n**This PR's concept is valid only if the following rules should work like the description below**. This is my perception based on the tests and the documentation. The documentation is clear about normal fields, but the wildcard fields are hard to deduct.\r\n\r\n**Note**: Also, I assume that keys could be spread between the subsets. It means the rules should examine the subsets together and not one by one.\r\n\r\n#### [`required_with`](https://laravel.com/docs/master/validation#rule-required-with):\r\nIf in any subset the given key is present at least once then the value is required. For example:\r\n\r\n**Rule**: `'foo' => 'required_with:names.*.first'`\r\n**Value**: `'names' => [['first' => 'Taylor'], ['nick' => 'Jeff']]`\r\n**Result**: `foo` should be required.\r\n\r\n#### [`required_with_all`](https://laravel.com/docs/master/validation#rule-required-with-all): \r\nWhen mapping through the subsets and all the specified keys are present least once then the value is required. For example:\r\n\r\n**Rule**: `'foo' => 'required_with_all:names.*.first,names.*.last'`\r\n**Value**: `'names' => [['first' => 'Taylor'], ['last' => 'Jeff']]`\r\n**Result**: `foo` should be required.\r\n\r\n#### [`required_without`](https://laravel.com/docs/master/validation#rule-required-without):\r\nIf at least one key is not present when mapping through subsets, then the value is required. For example:\r\n\r\n**Rule**: `'foo' => 'required_without:names.*.first,names.*.last'`\r\n**Value**: `'names' => [['first' => 'Taylor'], ['nick' => 'Jeff']]`\r\n**Result**: `foo` should be required.\r\n\r\n#### [`required_without_all`](https://laravel.com/docs/master/validation#rule-required-without-all):\r\nWhen mapping through the subsets and found non of the specified keys the value is required. For example:\r\n\r\n**Rule**: `'foo' => 'required_without_all:names.*.first,names.*.last'`\r\n**Value**: `'names' => [['nick' => 'Taylor'], ['alias' => 'Jeff']]`\r\n**Result**: `foo` should be required.\r\n\r\nThere are more descriptive checks in the tests.\r\n\r\n------------\r\n\r\n**Also, I think this can be considered as a breaking change** since it can change the result of these validation rules in currently running applications.\r\n\r\n**I'm up to any notices/ideas**, since describing how these validation rules should work in some situations can be quite tricky, so it's good to hear another point of views as well.", "number": 29203, "review_comments": [], "title": "[5.9] Handle wildcard values in required_with* rules" }
{ "commits": [ { "message": "Handle wildcard values in required_with* rules" }, { "message": "Update tests, fix logic for anyFailingRequired" } ], "files": [ { "diff": "@@ -1458,7 +1458,17 @@ public function validateRequiredWithoutAll($attribute, $value, $parameters)\n protected function anyFailingRequired(array $attributes)\n {\n foreach ($attributes as $key) {\n- if (! $this->validateRequired($key, $this->getValue($key))) {\n+ if (Str::contains($key, '*')) {\n+ $data = ValidationData::initializeAndGatherData($key, $this->data);\n+\n+ $data = array_filter($data, function ($item, $attribute) use ($key) {\n+ return Str::is($key, $attribute) && $this->validateRequired($attribute, $item);\n+ }, ARRAY_FILTER_USE_BOTH);\n+\n+ if (empty($data)) {\n+ return true;\n+ }\n+ } elseif (! $this->validateRequired($key, $this->getValue($key))) {\n return true;\n }\n }\n@@ -1475,7 +1485,15 @@ protected function anyFailingRequired(array $attributes)\n protected function allFailingRequired(array $attributes)\n {\n foreach ($attributes as $key) {\n- if ($this->validateRequired($key, $this->getValue($key))) {\n+ if (Str::contains($key, '*')) {\n+ $data = ValidationData::initializeAndGatherData($key, $this->data);\n+\n+ foreach ($data as $attribute => $item) {\n+ if (Str::is($key, $attribute) && $this->validateRequired($attribute, $item)) {\n+ return false;\n+ }\n+ }\n+ } elseif ($this->validateRequired($key, $this->getValue($key))) {\n return false;\n }\n }", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -757,6 +757,12 @@ public function testValidateRequiredWith()\n $foo = new File('', false);\n $v = new Validator($trans, ['file' => $file, 'foo' => $foo], ['foo' => 'required_with:file']);\n $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['foo' => 'Taylor']]], ['foo' => 'required_with:names.*.first']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['first' => 'Taylor']]], ['foo' => 'required_with:names.*.first']);\n+ $this->assertFalse($v->passes());\n }\n \n public function testRequiredWithAll()\n@@ -767,6 +773,12 @@ public function testRequiredWithAll()\n \n $v = new Validator($trans, ['first' => 'foo'], ['last' => 'required_with_all:first']);\n $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['first' => 'Taylor'], ['foo' => 'Otwell']]], ['foo' => 'required_with_all:names.*.first,names.*.last']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['first' => 'Taylor'], ['last' => 'Otwell']]], ['foo' => 'required_with_all:names.*.first,names.*.last']);\n+ $this->assertFalse($v->passes());\n }\n \n public function testValidateRequiredWithout()\n@@ -821,6 +833,12 @@ public function testValidateRequiredWithout()\n $foo = new File('', false);\n $v = new Validator($trans, ['file' => $file, 'foo' => $foo], ['foo' => 'required_without:file']);\n $this->assertFalse($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['first' => 'Taylor']]], ['foo' => 'required_without:names.*.first']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['foo' => 'Taylor']]], ['foo' => 'required_without:names.*.first']);\n+ $this->assertFalse($v->passes());\n }\n \n public function testRequiredWithoutMultiple()\n@@ -891,6 +909,12 @@ public function testRequiredWithoutAll()\n \n $v = new Validator($trans, ['f1' => 'foo', 'f2' => 'bar', 'f3' => 'baz'], $rules);\n $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['first' => 'Taylor']]], ['foo' => 'required_without_all:names.*.first,names.*.last']);\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator($trans, ['names' => [['foo' => 'Taylor']]], ['foo' => 'required_without_all:names.*.first,names.*.last']);\n+ $this->assertFalse($v->passes());\n }\n \n public function testRequiredIf()", "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": "Elaborate entry not found exception with which entry that could not be found. Working in a CLI environment then the `EntryNotFoundException` gives you very poor information. Currently, this is what I get in the console:\r\n\r\n```bash\r\nPHP Fatal error: Uncaught Illuminate\\Container\\EntryNotFoundException in /app/vendor/illuminate/container/Container.php:630\r\nStack trace:\r\n#0 /app/src/scripts/AddAllDeliveryTerm/AddAllDeliveryTermServiceProvider.php(74): Illuminate\\Container\\Container->get('Stockfiller\\\\Scr...')\r\n#1 /app/vendor/illuminate/container/Container.php(787): Stockfiller\\Scripts\\AddAllDeliveryTerm\\AddAllDeliveryTermServiceProvider->Stockfiller\\Scripts\\AddAllDeliveryTerm\\{closure}(Object(Illuminate\\Container\\Container), Array)\r\n#2 /app/vendor/illuminate/container/Container.php(667): Illuminate\\Container\\Container->build(Object(Closure))\r\n#3 /app/vendor/illuminate/container/Container.php(624): Illuminate\\Container\\Container->resolve('Stockfiller\\\\Scr...')\r\n#4 /app/src/scripts/AddAllDeliveryTerm/AddAllDeliveryTermServiceProvider.php(63): Illuminate\\Container\\Container->get('Stockfiller\\\\Scr...')\r\n#5 /app/vendor/illuminate/container/Container.php(787): Stockfiller\\Scripts\\AddAllDeliveryTerm\\AddAllDeliveryTermServiceProvider->Stockfiller\\Scripts\\AddAllDeliveryTe in /app/vendor/illuminate/container/Container.php on line 630\r\n```\r\n\r\nThis minor change will help tremendously in these kinds of situations.", "number": 29114, "review_comments": [], "title": "[5.8] Elaborate entry not found exception" }
{ "commits": [ { "message": "Elaborate entry not found exception\n\nElaborate entry not found exception with which entry that could not be found." } ], "files": [ { "diff": "@@ -627,7 +627,7 @@ public function get($id)\n throw $e;\n }\n \n- throw new EntryNotFoundException;\n+ throw new EntryNotFoundException($id);\n }\n }\n ", "filename": "src/Illuminate/Container/Container.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.26\r\n- PHP Version: 7.2.19\r\n- Database Driver & Version: MySQL 5.7.26\r\n\r\n### Description:\r\n`mergeConfigFrom` in `Illuminate\\Support\\ServiceProvider` does not respect cached configs and merges irrespective on whether Laravel is using a cached config or not.\r\n`loadRoutesFrom` correctly checks whether the app routes are cached prior to loading routes, `mergeConfigFrom` should follow the same pattern.\r\n\r\n### Steps To Reproduce:\r\ninclude a Service Provider that calls `mergeConfigFrom` (e.g., TinkerServiceProvider)\r\ncall the artisan command `config:cache` (`php artisan config:cache`)\r\nsee that the tinker configs are merged from the 3rd party package\r\n", "comments": [ { "body": "This issue has been solved, we can close it.", "created_at": "2019-07-08T01:44:37Z" } ], "number": 28997, "title": "ServiceProvider::mergeConfigFrom ignores cached configs generated via the config:cache command" }
{ "body": "Fixes #28997\r\n\r\n`mergeConfigFrom` should follow the same pattern as `loadRoutesFrom` in that it checks the config cache prior to loading.\r\n\r\nMerging configs on each request partially defeats the purpose of config caching.\r\n", "number": 29004, "review_comments": [], "title": "[5.9] ServiceProvider::mergeConfigFrom check if cached" }
{ "commits": [ { "message": "ServiceProvider::mergeConfigFrom check App::configurationIsCached" } ], "files": [ { "diff": "@@ -67,9 +67,11 @@ public function register()\n */\n protected function mergeConfigFrom($path, $key)\n {\n- $config = $this->app['config']->get($key, []);\n+ if (! $this->app->configurationIsCached()) {\n+ $config = $this->app['config']->get($key, []);\n \n- $this->app['config']->set($key, array_merge(require $path, $config));\n+ $this->app['config']->set($key, array_merge(require $path, $config));\n+ }\n }\n \n /**", "filename": "src/Illuminate/Support/ServiceProvider.php", "status": "modified" } ] }
{ "body": "The filename fallback is turned to ASCII, because only ASCII is allowed. But there are 2 more checks:\n- check for `%` in the fallback\n- check for slashes in the filename and the fallback.\n\n(See https://github.com/symfony/symfony/blob/v2.5.5/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php#L264-L277)\n\nI think we can skip the slashes, because they are also checked in the filename itself. But we should probably remove the % sign. Downloads work when files have a `%` in them, just the fallback doesn't.\n\nI propose removing the % from the fallback.\n", "comments": [ { "body": ":+1:\n", "created_at": "2014-10-15T21:23:55Z" } ], "number": 6097, "title": "[4.2] Remove % From filenameFallback In Response::download" }
{ "body": "This is a follow-up to #28551, and similar to #6097 and how it's done in the current ResponseFactory:\r\nhttps://github.com/laravel/framework/blob/7ac7818dbcfd69417c2f6fe61ef7176cf375863a/src/Illuminate/Routing/ResponseFactory.php#L159-L179\r\n\r\nThe fallback can't include a percentage sign, so this check is added.", "number": 28947, "review_comments": [], "title": "[5.8] Convert percentage sign in filename fallback" }
{ "commits": [ { "message": "Test for Percent In Filename" }, { "message": "Convert percentage sign in fallback filename" }, { "message": "CS" }, { "message": "CS" } ], "files": [ { "diff": "@@ -141,7 +141,7 @@ public function response($path, $name = null, array $headers = [], $disposition\n $filename = $name ?? basename($path);\n \n $disposition = $response->headers->makeDisposition(\n- $disposition, $filename, Str::ascii($filename)\n+ $disposition, $filename, $this->fallbackName($filename)\n );\n \n $response->headers->replace($headers + [\n@@ -172,6 +172,17 @@ public function download($path, $name = null, array $headers = [])\n return $this->response($path, $name, $headers, 'attachment');\n }\n \n+ /**\n+ * Convert the string to ASCII characters that are equivalent to the given name.\n+ *\n+ * @param string $name\n+ * @return string\n+ */\n+ protected function fallbackName($name)\n+ {\n+ return str_replace('%', '', Str::ascii($name));\n+ }\n+\n /**\n * Write the contents of a file.\n *", "filename": "src/Illuminate/Filesystem/FilesystemAdapter.php", "status": "modified" }, { "diff": "@@ -70,6 +70,15 @@ public function testDownloadNonAsciiEmptyFilename()\n $this->assertEquals('attachment; filename=pizdyuk.txt; filename*=utf-8\\'\\'%D0%BF%D0%B8%D0%B7%D0%B4%D1%8E%D0%BA.txt', $response->headers->get('content-disposition'));\n }\n \n+ public function testDownloadPercentInFilename()\n+ {\n+ $this->filesystem->write('Hello%World.txt', 'Hello World');\n+ $files = new FilesystemAdapter($this->filesystem);\n+ $response = $files->download('Hello%World.txt', 'Hello%World.txt');\n+ $this->assertInstanceOf(StreamedResponse::class, $response);\n+ $this->assertEquals('attachment; filename=HelloWorld.txt; filename*=utf-8\\'\\'Hello%25World.txt', $response->headers->get('content-disposition'));\n+ }\n+\n public function testExists()\n {\n $this->filesystem->write('file.txt', 'Hello World');", "filename": "tests/Filesystem/FilesystemAdapterTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.*\r\n- PHP Version: 7.1\r\n\r\n### Description:\r\nWhen passing the name param to the `make:migration` call, the passed value isn't validated to ensure that an invalid class name cannot be created\r\n\r\n### Steps To Reproduce:\r\n\r\nRunning the following artisan command:\r\n\r\n`php artisan make:migration username_stea,` (note the comma on the end as a result of missing the m key)\r\n\r\nGenerates a migration with the following classname:\r\n\r\n`class UsernameStea, extends Migration`\r\n\r\n### Expected Behaviour\r\n\r\nValidation to ensure only allowable characters are used, or otherwise to omit these characters from the classname (defined in https://www.php.net/manual/en/language.oop5.basic.php)\r\n\r\n\r\n\r\n", "comments": [ { "body": "Something along the lines of:\r\n\r\n```php\r\n if (!(bool)preg_match(\"%^[a-zA-Z_\\x80-\\xff][a-zA-Z0-9_\\x80-\\xff]*$%\", $name)) {\r\n throw new \\InvalidArgumentException(\"Invalid characters present in proposed classname {$name}\");\r\n }\r\n```\r\n\r\nWould do the trick", "created_at": "2019-06-24T13:54:04Z" }, { "body": "Thanks. Feel free to send in a PR with a test.", "created_at": "2019-06-24T15:12:49Z" } ], "number": 28938, "title": "`make:migration` doesn't validate the class name to be generated" }
{ "body": "Reference: #28938 \r\n\r\nThe name passed to the `make:migration` command forms the base of the classname of the generated migration file. Currently this `name` param isn't validated, meaning classes can be created with invalid class names.\r\n\r\nThis PR adds a simple check to confirm there are no unsupported characters (using the RegEx defined in the PHP docs at https://www.php.net/manual/en/language.oop5.basic.php), and throws an InvalidArgumentException should such characters be found.\r\n", "number": 28942, "review_comments": [ { "body": "Please don't double space after a period.", "created_at": "2019-06-24T20:24:59Z" }, { "body": "Please don't double space after a period.", "created_at": "2019-06-24T20:25:27Z" }, { "body": "Please import the exception class rather than prefixing it with a slash.", "created_at": "2019-06-24T20:25:32Z" }, { "body": "Same as above.", "created_at": "2019-06-24T20:25:47Z" } ], "title": "[5.8] Validate the characters passed to $name on MigrationMakeCommand" }
{ "commits": [ { "message": "Validate the characters passed to on MigrationMakeCommand" }, { "message": "Fix CS violation" }, { "message": "Requested changes" }, { "message": "Resolve CS violation" } ], "files": [ { "diff": "@@ -3,6 +3,7 @@\n namespace Illuminate\\Database\\Console\\Migrations;\n \n use Illuminate\\Support\\Str;\n+use InvalidArgumentException;\n use Illuminate\\Support\\Composer;\n use Illuminate\\Database\\Migrations\\MigrationCreator;\n \n@@ -68,6 +69,13 @@ public function handle()\n // to be freshly created so we can create the appropriate migrations.\n $name = Str::snake(trim($this->input->getArgument('name')));\n \n+ // Later on we're going to convert $name into a classname for the\n+ // migration. As such, we need to confirm that there are no characters\n+ // that are not allowed in a classname\n+ if (! (bool) preg_match(\"%^[a-zA-Z_\\x80-\\xff][a-zA-Z0-9_\\x80-\\xff]*$%\", $name)) {\n+ throw new InvalidArgumentException(\"Invalid characters present in proposed classname {$name}\");\n+ }\n+\n $table = $this->input->getOption('table');\n \n $create = $this->input->getOption('create') ?: false;", "filename": "src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php", "status": "modified" }, { "diff": "@@ -3,6 +3,7 @@\n namespace Illuminate\\Tests\\Database;\n \n use Mockery as m;\n+use InvalidArgumentException;\n use PHPUnit\\Framework\\TestCase;\n use Illuminate\\Support\\Composer;\n use Illuminate\\Foundation\\Application;\n@@ -18,6 +19,20 @@ protected function tearDown(): void\n m::close();\n }\n \n+ public function testBasicCreateWithInvalidCharsThrowsException()\n+ {\n+ $command = new MigrateMakeCommand(\n+ $creator = m::mock(MigrationCreator::class),\n+ $composer = m::mock(Composer::class)\n+ );\n+ $app = new Application;\n+ $app->useDatabasePath(__DIR__);\n+ $command->setLaravel($app);\n+ $this->expectException(InvalidArgumentException::class);\n+\n+ $this->runCommand($command, ['name' => 'invalid,classname!']);\n+ }\n+\n public function testBasicCreateDumpsAutoload()\n {\n $command = new MigrateMakeCommand(", "filename": "tests/Database/DatabaseMigrationMakeCommandTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.21\r\n- PHP Version: 7.3.5\r\n- Database Driver & Version: N/A\r\n\r\n### Description:\r\n\r\nThe Symfony console component that is used by the Artisan console [allows separating option names and values with either a space or an equals (`=`) sign](https://symfony.com/doc/current/components/console/console_arguments.html). For example:\r\n\r\n```\r\n$ php artisan serve --port=9090 \r\nLaravel development server started: <http://127.0.0.1:9090>\r\n$ php artisan serve --port 9090 \r\nLaravel development server started: <http://127.0.0.1:9090>\r\n```\r\n\r\nHowever, the `--env` option is only parsed correctly if you use an equals sign. If you use a space `app()->environment()` will return false.\r\n\r\nThis inconsistency is pretty confusing and difficult to debug. If you dump `$this->option('env')` in a command it will return the expected value but `$app()->environment()` will return false.\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Pass the `--env` flag to `tinker`, i.e. `php artisan tinker --env testing\r\n2. Execute `app()->environment()` in the tinker shell\r\n\r\n```\r\n$ php artisan tinker --env=testing\r\nPsy Shell v0.9.8 (PHP 7.3.5 — cli) by Justin Hileman\r\n>>> app()->environment()\r\n=> \"testing\"\r\n>>> \r\n```\r\n\r\n```\r\n$ php artisan tinker --env testing \r\nPsy Shell v0.9.8 (PHP 7.3.5 — cli) by Justin Hileman\r\n>>> app()->environment()\r\n=> false\r\n>>> \r\n```\r\n\r\nThis appears to be happening because the environment detector uses `$_SERVER['argv']` and `$_SERVER['argv']` splits the options into two separate array elements if you use a space instead of an equals sign, and the `EnvironmentDetector` [expects a single element](https://github.com/laravel/framework/blob/f0448d4df91dcec7c49b580d3fb96c21523c3b74/src/Illuminate/Foundation/EnvironmentDetector.php#L51) to contain both the name and the value.\r\n\r\n```\r\n$ php artisan tinker --env testing \r\nPsy Shell v0.9.8 (PHP 7.3.5 — cli) by Justin Hileman\r\n>>> $_SERVER['argv']\r\n=> [\r\n \"artisan\",\r\n \"tinker\",\r\n \"--env\",\r\n \"testing\",\r\n ]\r\n```\r\n\r\n```\r\n$ php artisan tinker --env=testing \r\nPsy Shell v0.9.8 (PHP 7.3.5 — cli) by Justin Hileman\r\n>>> $_SERVER['argv']\r\n=> [\r\n \"artisan\",\r\n \"tinker\",\r\n \"--env=testing\",\r\n ]\r\n```", "comments": [ { "body": "Thanks for reporting. Welcoming any help with this.", "created_at": "2019-06-13T20:37:44Z" } ], "number": 28831, "title": "EnvironmentDetector doesn't parse options separated with a space" }
{ "body": "Following explanations are from @matt-allan in the issue #28831:\r\n\r\nThe Symfony console component that is used by the Artisan console allows separating option names and values with either a space or an equals (=) sign. For example:\r\n\r\n```\r\n$ php artisan serve --port=9090 \r\nLaravel development server started: <http://127.0.0.1:9090>\r\n$ php artisan serve --port 9090 \r\nLaravel development server started: <http://127.0.0.1:9090>\r\n```\r\n\r\nHowever, the `--env` option is only parsed correctly if you use an equals sign. If you use a space `app()->environment()` will return false.\r\n\r\nThis inconsistency is pretty confusing and difficult to debug. If you dump `$this->option('env')` in a command it will return the expected value but `app()->environment()` will return false.\r\n\r\nFixes #28831", "number": 28869, "review_comments": [], "title": "[5.8] Allow console environment argument to be separated with a space" }
{ "commits": [ { "message": "Allow console environment argument to be separated with a space" } ], "files": [ { "diff": "@@ -3,7 +3,6 @@\n namespace Illuminate\\Foundation;\n \n use Closure;\n-use Illuminate\\Support\\Arr;\n use Illuminate\\Support\\Str;\n \n class EnvironmentDetector\n@@ -48,7 +47,7 @@ protected function detectConsoleEnvironment(Closure $callback, array $args)\n // and if it was that automatically overrides as the environment. Otherwise, we\n // will check the environment as a \"web\" request like a typical HTTP request.\n if (! is_null($value = $this->getEnvironmentArgument($args))) {\n- return head(array_slice(explode('=', $value), 1));\n+ return $value;\n }\n \n return $this->detectWebEnvironment($callback);\n@@ -62,8 +61,14 @@ protected function detectConsoleEnvironment(Closure $callback, array $args)\n */\n protected function getEnvironmentArgument(array $args)\n {\n- return Arr::first($args, function ($value) {\n- return Str::startsWith($value, '--env');\n- });\n+ foreach ($args as $i => $value) {\n+ if ($value === '--env') {\n+ return $args[$i + 1] ?? null;\n+ }\n+\n+ if (Str::startsWith($value, '--env')) {\n+ return head(array_slice(explode('=', $value), 1));\n+ }\n+ }\n }\n }", "filename": "src/Illuminate/Foundation/EnvironmentDetector.php", "status": "modified" }, { "diff": "@@ -32,4 +32,24 @@ public function testConsoleEnvironmentDetection()\n }, ['--env=local']);\n $this->assertEquals('local', $result);\n }\n+\n+ public function testConsoleEnvironmentDetectionSeparatedWithSpace()\n+ {\n+ $env = new EnvironmentDetector;\n+\n+ $result = $env->detect(function () {\n+ return 'foobar';\n+ }, ['--env', 'local']);\n+ $this->assertEquals('local', $result);\n+ }\n+\n+ public function testConsoleEnvironmentDetectionWithNoValue()\n+ {\n+ $env = new EnvironmentDetector;\n+\n+ $result = $env->detect(function () {\n+ return 'foobar';\n+ }, ['--env']);\n+ $this->assertEquals('foobar', $result);\n+ }\n }", "filename": "tests/Foundation/FoundationEnvironmentDetectorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.19\r\n- PHP Version: 7.2.12\r\n- Database Driver & Version: -\r\n\r\n### Description:\r\nWhen validating a static key (without wildcard), I cannot use a wildcard a parameter for the required_with rule.\r\n\r\n### Steps To Reproduce:\r\n2 POST data:\r\n- user.*.email => 'email'\r\n- emailContent => 'required_with:user.*.email|string'\r\n\r\n### Test Method:\r\n\r\n public function testRequiredWithWildcard()\r\n {\r\n $trans = $this->getIlluminateArrayTranslator();\r\n $v = new Validator($trans, ['names' => [['first' => 'Taylor']], 'foo' => 'bar'], ['foo' => 'required_with:names.*.first']);\r\n $this->assertTrue($v->passes());\r\n\r\n $v = new Validator($trans, ['names' => [['first' => 'Taylor']]], ['foo' => 'required_with:names.*.first']);\r\n $this->assertFalse($v->passes());\r\n }\r\n\r\nThe second assertion fails as the data \"names.*.first\" does not exists and so the validation passes.", "comments": [ { "body": "Might be related to https://github.com/laravel/framework/issues/26179", "created_at": "2019-01-02T14:32:23Z" }, { "body": "When using the `*` in required_with you the field you're validating also needs to be within in array like the documentation shows:\r\n\r\n![image](https://user-images.githubusercontent.com/463230/80748678-ecea9b80-8aea-11ea-8624-163d81a3a33e.png)\r\n\r\nWhat your code example would do is currently undefined behavior in Laravel. It's undefined in the sense of we do not know if you mean that at least one first name must be present... every element in the array must have one? \r\n\r\nThis is more of a feature request or idea that should be discussed in laravel/ideas where the behavior can actually be defined.", "created_at": "2020-04-30T19:01:10Z" } ], "number": 26957, "title": "Cannot use required_with with a wildcard on a static key" }
{ "body": "reopened: #28813\r\nissue: #26957\r\n\r\nrequired_with didn't work with wildcard, see source issue for more details", "number": 28821, "review_comments": [ { "body": "```suggestion\r\n if (strpos($parameters[0], '*') !== false || ! $this->allFailingRequired($parameters)) {\r\n```", "created_at": "2019-06-12T20:03:44Z" } ], "title": "[5.8] fixed required_with with wildcard" }
{ "commits": [ { "message": "fixed required_with with wildcard" }, { "message": "StyleCI fix" }, { "message": "replaced stristr with strpos\n\nSigned-off-by: Max Kovalenko <mxss1998@yandex.ru>" }, { "message": "replaced strpos with strpos !== false\n\nCo-Authored-By: Marek Szymczuk <marek@osiemsiedem.com>" }, { "message": "additional null check to prevent empty required_with from failing\n\nSigned-off-by: Max Kovalenko <mxss1998@yandex.ru>" }, { "message": "quick fix\n\nSigned-off-by: Max Kovalenko <mxss1998@yandex.ru>" } ], "files": [ { "diff": "@@ -1391,7 +1391,9 @@ public function validateRequiredUnless($attribute, $value, $parameters)\n */\n public function validateRequiredWith($attribute, $value, $parameters)\n {\n- if (! $this->allFailingRequired($parameters)) {\n+ if (\n+ (strpos($parameters[0], '*') !== false && $value === null) || ! $this->allFailingRequired($parameters)\n+ ) {\n return $this->validateRequired($attribute, $value);\n }\n ", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -4441,6 +4441,40 @@ public function testValidateWithInvalidUuid($uuid)\n $this->assertFalse($v->passes());\n }\n \n+ public function testRequiredWithWildcard()\n+ {\n+ $trans = $this->getIlluminateArrayTranslator();\n+\n+ $v = new Validator(\n+ $trans,\n+ [\n+ 'names' => [['second' => 'Otwell']],\n+ 'foo' => '',\n+ ],\n+ ['foo' => 'required_with:names.*.first']\n+ );\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator(\n+ $trans,\n+ [\n+ 'names' => [['first' => 'Taylor']],\n+ 'foo' => 'bar',\n+ ],\n+ ['foo' => 'required_with:names.*.first']\n+ );\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator(\n+ $trans,\n+ [\n+ 'names' => [['first' => 'Taylor']],\n+ ],\n+ ['foo' => 'required_with:names.*.first']\n+ );\n+ $this->assertFalse($v->passes());\n+ }\n+\n public function validUuidList()\n {\n return [", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.19\r\n- PHP Version: 7.2.12\r\n- Database Driver & Version: -\r\n\r\n### Description:\r\nWhen validating a static key (without wildcard), I cannot use a wildcard a parameter for the required_with rule.\r\n\r\n### Steps To Reproduce:\r\n2 POST data:\r\n- user.*.email => 'email'\r\n- emailContent => 'required_with:user.*.email|string'\r\n\r\n### Test Method:\r\n\r\n public function testRequiredWithWildcard()\r\n {\r\n $trans = $this->getIlluminateArrayTranslator();\r\n $v = new Validator($trans, ['names' => [['first' => 'Taylor']], 'foo' => 'bar'], ['foo' => 'required_with:names.*.first']);\r\n $this->assertTrue($v->passes());\r\n\r\n $v = new Validator($trans, ['names' => [['first' => 'Taylor']]], ['foo' => 'required_with:names.*.first']);\r\n $this->assertFalse($v->passes());\r\n }\r\n\r\nThe second assertion fails as the data \"names.*.first\" does not exists and so the validation passes.", "comments": [ { "body": "Might be related to https://github.com/laravel/framework/issues/26179", "created_at": "2019-01-02T14:32:23Z" }, { "body": "When using the `*` in required_with you the field you're validating also needs to be within in array like the documentation shows:\r\n\r\n![image](https://user-images.githubusercontent.com/463230/80748678-ecea9b80-8aea-11ea-8624-163d81a3a33e.png)\r\n\r\nWhat your code example would do is currently undefined behavior in Laravel. It's undefined in the sense of we do not know if you mean that at least one first name must be present... every element in the array must have one? \r\n\r\nThis is more of a feature request or idea that should be discussed in laravel/ideas where the behavior can actually be defined.", "created_at": "2020-04-30T19:01:10Z" } ], "number": 26957, "title": "Cannot use required_with with a wildcard on a static key" }
{ "body": "issue: #26957\r\n\r\nrequired_with didn't work with wildcard, see source issue for more details", "number": 28813, "review_comments": [ { "body": "Can you replace `stristr` with `strpos`?", "created_at": "2019-06-12T09:19:57Z" } ], "title": "[5.8] fixed required_with with wildcard" }
{ "commits": [ { "message": "fixed required_with with wildcard" }, { "message": "StyleCI fix" }, { "message": "replaced stristr with strpos\n\nSigned-off-by: Max Kovalenko <mxss1998@yandex.ru>" } ], "files": [ { "diff": "@@ -1391,7 +1391,7 @@ public function validateRequiredUnless($attribute, $value, $parameters)\n */\n public function validateRequiredWith($attribute, $value, $parameters)\n {\n- if (! $this->allFailingRequired($parameters)) {\n+ if (strpos($parameters[0], '*') || ! $this->allFailingRequired($parameters)) {\n return $this->validateRequired($attribute, $value);\n }\n ", "filename": "src/Illuminate/Validation/Concerns/ValidatesAttributes.php", "status": "modified" }, { "diff": "@@ -4441,6 +4441,29 @@ public function testValidateWithInvalidUuid($uuid)\n $this->assertFalse($v->passes());\n }\n \n+ public function testRequiredWithWildcard()\n+ {\n+ $trans = $this->getIlluminateArrayTranslator();\n+ $v = new Validator(\n+ $trans,\n+ [\n+ 'names' => [['first' => 'Taylor']],\n+ 'foo' => 'bar',\n+ ],\n+ ['foo' => 'required_with:names.*.first']\n+ );\n+ $this->assertTrue($v->passes());\n+\n+ $v = new Validator(\n+ $trans,\n+ [\n+ 'names' => [['first' => 'Taylor']],\n+ ],\n+ ['foo' => 'required_with:names.*.first']\n+ );\n+ $this->assertFalse($v->passes());\n+ }\n+\n public function validUuidList()\n {\n return [", "filename": "tests/Validation/ValidationValidatorTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.+\r\n- PHP Version: 7.2.11\r\n- Database Driver & Version:\r\nPECL redis 4.1.1\r\n### Description:\r\nCant set Redis::OPT_SERIALIZER to any value, thats because of:\r\n[serialize](https://github.com/laravel/framework/blob/c3b7a12f36b3eec1bdd7633c61a2dc1b7d6043f3/src/Illuminate/Cache/RedisStore.php#L276src/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php:287)\r\nand\r\n[unserialize](https://github.com/laravel/framework/blob/c3b7a12f36b3eec1bdd7633c61a2dc1b7d6043f3/src/Illuminate/Cache/RedisStore.php#L287)\r\nmethods in RedisStore.\r\n\r\nStore needs refactor, to accept Redis::SERIALIZER_IGBINARY", "comments": [ { "body": "This needs a little more info. What are you actually trying to do? Can you provide some code examples? How do the Redis options affect the linked code?", "created_at": "2018-11-09T15:52:59Z" }, { "body": "Laravel RedisStore implementation has php serialize() / unserialize() hardcoded. This prevents igbinary serialization of strings if option passed to phpredis", "created_at": "2018-11-09T16:28:18Z" }, { "body": "Ah I see. Yeah that should be made possible. Feel free to send in a PR if you know how to fix this.", "created_at": "2018-11-09T16:29:59Z" }, { "body": "https://github.com/laravel/framework/pull/31182 has been merged so you can now set custom serializers.", "created_at": "2020-01-21T17:01:34Z" } ], "number": 26186, "title": "RedisStore, cant set Redis::OPT_SERIALIZER to Redis::SERIALIZER_IGBINARY because of hardcoded serialization" }
{ "body": "This PR aims to fix #26186 adding the ability to configure the PhpRedis module to use any of its supported [custom serializers ](https://github.com/phpredis/phpredis#example-6) (php-builtin, igBinary, msgpack).\r\n\r\nPredisConnection will use PHP's default `serialize` & `unserialize`", "number": 28699, "review_comments": [], "title": "[5.8] Fix 26186 allow serialize igbinary" }
{ "commits": [ { "message": "Adds serialize method per redisConnection so predis can use igBinary serialization" }, { "message": "Updates test to use redisConnectors' serialize method" }, { "message": "Fixes serialize/unserialize method visibility scope" }, { "message": "Fixes visibility on PHPRedisConnection serialize/unserialize methods" }, { "message": "Applies styleCI fixes" } ], "files": [ { "diff": "@@ -0,0 +1 @@\n+ \n\\ No newline at end of file", "filename": " ", "status": "added" }, { "diff": "@@ -292,7 +292,7 @@ public function setPrefix($prefix)\n */\n protected function serialize($value)\n {\n- return is_numeric($value) ? $value : serialize($value);\n+ return is_numeric($value) ? $value : $this->connection()->serialize($value);\n }\n \n /**\n@@ -303,6 +303,6 @@ protected function serialize($value)\n */\n protected function unserialize($value)\n {\n- return is_numeric($value) ? $value : unserialize($value);\n+ return is_numeric($value) ? $value : $this->connection()->unserialize($value);\n }\n }", "filename": "src/Illuminate/Cache/RedisStore.php", "status": "modified" }, { "diff": "@@ -450,4 +450,26 @@ public function __call($method, $parameters)\n {\n return parent::__call(strtolower($method), $parameters);\n }\n+\n+ /**\n+ * Serialize the value. Using PhpRedis's native serialize methods.\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ public function serialize($value)\n+ {\n+ return $this->client->_serialize($value);\n+ }\n+\n+ /**\n+ * Unserialize the value. Using PhpRedis's native serialize methods.\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ public function unserialize($value)\n+ {\n+ return $this->client->_unserialize($value);\n+ }\n }", "filename": "src/Illuminate/Redis/Connections/PhpRedisConnection.php", "status": "modified" }, { "diff": "@@ -61,4 +61,26 @@ public function flushdb()\n $node->executeCommand(new ServerFlushDatabase);\n }\n }\n+\n+ /**\n+ * Serialize the value.\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ public function serialize($value)\n+ {\n+ return serialize($value);\n+ }\n+\n+ /**\n+ * Unserialize the value.\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ public function unserialize($value)\n+ {\n+ return unserialize($value);\n+ }\n }", "filename": "src/Illuminate/Redis/Connections/PredisConnection.php", "status": "modified" }, { "diff": "@@ -80,6 +80,10 @@ protected function createClient(array $config)\n if (! empty($config['read_timeout'])) {\n $client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']);\n }\n+\n+ if (! empty($config['serializer'])) {\n+ $client->setOption(Redis::OPT_SERIALIZER, $config['serializer']);\n+ }\n });\n }\n ", "filename": "src/Illuminate/Redis/Connectors/PhpRedisConnector.php", "status": "modified" }, { "diff": "@@ -25,15 +25,16 @@ public function testGetReturnsNullWhenNotFound()\n public function testRedisValueIsReturned()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('connection')->twice()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('foo'));\n+ $redis->getRedis()->shouldReceive('unserialize')->once()->with(serialize('foo'))->andReturn('foo');\n $this->assertEquals('foo', $redis->get('foo'));\n }\n \n public function testRedisMultipleValuesAreReturned()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('connection')->times(4)->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('mget')->once()->with(['prefix:foo', 'prefix:fizz', 'prefix:norf', 'prefix:null'])\n ->andReturn([\n serialize('bar'),\n@@ -42,6 +43,10 @@ public function testRedisMultipleValuesAreReturned()\n null,\n ]);\n \n+ $redis->getRedis()->shouldReceive('unserialize')->with(serialize('bar'))->andReturn('bar');\n+ $redis->getRedis()->shouldReceive('unserialize')->with(serialize('buzz'))->andReturn('buzz');\n+ $redis->getRedis()->shouldReceive('unserialize')->with(serialize('quz'))->andReturn('quz');\n+\n $results = $redis->many(['foo', 'fizz', 'norf', 'null']);\n \n $this->assertEquals('bar', $results['foo']);\n@@ -61,8 +66,10 @@ public function testRedisValueIsReturnedForNumerics()\n public function testSetMethodProperlyCallsRedis()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('serialize')->andReturn(serialize('foo'));\n+ $redis->getRedis()->shouldReceive('connection')->twice()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('foo'))->andReturn('OK');\n+ $redis->getRedis()->shouldReceive('serialize');\n $result = $redis->put('foo', 'foo', 60);\n $this->assertTrue($result);\n }\n@@ -77,6 +84,11 @@ public function testSetMultipleMethodProperlyCallsRedis()\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('bar'))->andReturn('OK');\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:baz', 60, serialize('qux'))->andReturn('OK');\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:bar', 60, serialize('norf'))->andReturn('OK');\n+\n+ $redis->getRedis()->shouldReceive('serialize')->with('bar')->andReturn(serialize('bar'));\n+ $redis->getRedis()->shouldReceive('serialize')->with('qux')->andReturn(serialize('qux'));\n+ $redis->getRedis()->shouldReceive('serialize')->with('norf')->andReturn(serialize('norf'));\n+\n $connection->shouldReceive('exec')->once();\n \n $result = $redis->putMany([\n@@ -115,8 +127,9 @@ public function testDecrementMethodProperlyCallsRedis()\n public function testStoreItemForeverProperlyCallsRedis()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('connection')->twice()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('set')->once()->with('prefix:foo', serialize('foo'))->andReturn('OK');\n+ $redis->getRedis()->shouldReceive('serialize')->with('foo')->andReturn(serialize('foo'));\n $result = $redis->forever('foo', 'foo', 60);\n $this->assertTrue($result);\n }", "filename": "tests/Cache/CacheRedisStoreTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.18\r\n- PHP Version: 7.3.2\r\n- Database Driver & Version: MySQL 5.7\r\n\r\n### Description:\r\nWhen creating / updating / deleting a child belonging to a parent through a `MorphTo` relation Eloquent tries to updated the parents `updated_at` column regardless of the parents `$timestamps` property when the parent is listed in `$touches`.\r\n\r\nBecause this is a polymorphic relation and not all parents may have timestamps I would expect that parents with `$timestamps = false` are ignored when touching.\r\n\r\n(I guess this may not only be relevant for `MorphTo` relations but others as well)\r\n\r\n### Steps To Reproduce:\r\n\r\nParent.php\r\n```\r\nclass Parent extends Model\r\n{\r\n public $timestamps = false;\r\n\r\n public function children(): MorphMany\r\n {\r\n return $this->morphMany(Child::class, 'children');\r\n }\r\n\r\n}\r\n```\r\n\r\nChild.php\r\n```\r\nclass Child extends Model\r\n{\r\n protected $touches = ['parent'];\r\n\r\n public function parent(): MorphTo\r\n {\r\n return $this->morphTo();\r\n }\r\n\r\n}\r\n```\r\n\r\n`$parent->children()->save(new Child());` throws `Illuminate\\Database\\QueryException: SQLSTATE[HY000]: General error: 1 no such column: updated_at (SQL: update \"parents\" set \"updated_at\" = 2019-05-28 11:02:21 where \"parents\".\"id\" = 1)`\r\n\r\n", "comments": [ { "body": "That indeed seems like a bug to me. Welcoming prs for this.", "created_at": "2019-05-28T11:35:19Z" }, { "body": "Pr for this was merged.", "created_at": "2019-06-05T19:40:24Z" } ], "number": 28638, "title": "MorphTo Relation ignores parent $timestamp when touching" }
{ "body": "Fixed bug with touching model which has $timestamps set to false resulting in Illuminate\\Database\\QueryException: SQLSTATE[HY000]: General error: 1 no such column: updated_at\r\n\r\nfor source issue and more details see #28638", "number": 28670, "review_comments": [ { "body": "I would prefer `(new $class)->usesTimestamps()` to be consistent with existing code.", "created_at": "2019-06-01T00:21:54Z" }, { "body": "> We also have to cover cases where timestamps are enabled, but UPDATED_AT is null:\r\n\r\njust added test", "created_at": "2019-06-01T07:19:30Z" }, { "body": "@staudenmeir in some cases we're getting abstract classes here for ex.\r\nhttps://github.com/laravel/framework/blob/5992f10116f612d51465385b0af11d778d975b87/tests/Database/DatabaseEloquentIntegrationTest.php#L1539", "created_at": "2019-06-01T07:19:58Z" }, { "body": "Yes, but only in the tests. You can't get an abstract class in a real application. Please adjust the test accordingly.", "created_at": "2019-06-01T13:51:45Z" }, { "body": "This case has to return `true`. You need to cover it by adjusting `isIgnoringTouch()`.", "created_at": "2019-06-01T13:53:31Z" }, { "body": "> Yes, but only in the tests. You can't get an abstract class in a real application.\r\n\r\nOK, but If I use `(new $class)->usesTimestamps()` 6 more test are failing (not including mine) - what to do with that?\r\nFor example this one:\r\nhttps://github.com/laravel/framework/blob/5992f10116f612d51465385b0af11d778d975b87/tests/Database/DatabaseEloquentIntegrationTest.php#L1539", "created_at": "2019-06-03T05:36:54Z" }, { "body": "done", "created_at": "2019-06-03T05:47:42Z" }, { "body": "I think we should move the new code to `Relation::touch()`. `Model::isIgnoringTouch()` is only about `$ignoreOnTouch`, not about timestamps.", "created_at": "2019-06-03T16:21:47Z" } ], "title": "[5.8] fix MorphTo Relation ignores parent $timestamp when touching " }
{ "commits": [ { "message": "added test" }, { "message": "relation touch ignores $timestamps fix" }, { "message": "added test to cover cases where $timestamps = true & UPDATED_AT is null" }, { "message": "StyleCI fix" }, { "message": "added UPDATED_AT constant check & updated test\n\nSigned-off-by: Max Kovalenko <mxss1998@yandex.ru>" } ], "files": [ { "diff": "@@ -294,6 +294,10 @@ public static function isIgnoringTouch($class = null)\n {\n $class = $class ?: static::class;\n \n+ if (! get_class_vars($class)['timestamps'] || ! $class::UPDATED_AT) {\n+ return true;\n+ }\n+\n foreach (static::$ignoreOnTouch as $ignoredClass) {\n if ($class === $ignoredClass || is_subclass_of($class, $ignoredClass)) {\n return true;", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -1896,6 +1896,27 @@ protected function addMockConnection($model)\n return new BaseBuilder($connection, $grammar, $processor);\n });\n }\n+\n+ public function testTouchingModelWithTimestamps()\n+ {\n+ $this->assertFalse(\n+ Model::isIgnoringTouch(Model::class)\n+ );\n+ }\n+\n+ public function testNotTouchingModelWithUpdatedAtNull()\n+ {\n+ $this->assertTrue(\n+ Model::isIgnoringTouch(EloquentModelWithUpdatedAtNull::class)\n+ );\n+ }\n+\n+ public function testNotTouchingModelWithoutTimestamps()\n+ {\n+ $this->assertTrue(\n+ Model::isIgnoringTouch(EloquentModelWithoutTimestamps::class)\n+ );\n+ }\n }\n \n class EloquentTestObserverStub\n@@ -2303,3 +2324,15 @@ class EloquentModelEventObjectStub extends Model\n 'saving' => EloquentModelSavingEventStub::class,\n ];\n }\n+\n+class EloquentModelWithoutTimestamps extends Model\n+{\n+ protected $table = 'stub';\n+ public $timestamps = false;\n+}\n+\n+class EloquentModelWithUpdatedAtNull extends Model\n+{\n+ protected $table = 'stub';\n+ const UPDATED_AT = null;\n+}", "filename": "tests/Database/DatabaseEloquentModelTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.18\r\n- PHP Version: 7.3.2\r\n- Database Driver & Version: MySQL 5.7\r\n\r\n### Description:\r\nWhen creating / updating / deleting a child belonging to a parent through a `MorphTo` relation Eloquent tries to updated the parents `updated_at` column regardless of the parents `$timestamps` property when the parent is listed in `$touches`.\r\n\r\nBecause this is a polymorphic relation and not all parents may have timestamps I would expect that parents with `$timestamps = false` are ignored when touching.\r\n\r\n(I guess this may not only be relevant for `MorphTo` relations but others as well)\r\n\r\n### Steps To Reproduce:\r\n\r\nParent.php\r\n```\r\nclass Parent extends Model\r\n{\r\n public $timestamps = false;\r\n\r\n public function children(): MorphMany\r\n {\r\n return $this->morphMany(Child::class, 'children');\r\n }\r\n\r\n}\r\n```\r\n\r\nChild.php\r\n```\r\nclass Child extends Model\r\n{\r\n protected $touches = ['parent'];\r\n\r\n public function parent(): MorphTo\r\n {\r\n return $this->morphTo();\r\n }\r\n\r\n}\r\n```\r\n\r\n`$parent->children()->save(new Child());` throws `Illuminate\\Database\\QueryException: SQLSTATE[HY000]: General error: 1 no such column: updated_at (SQL: update \"parents\" set \"updated_at\" = 2019-05-28 11:02:21 where \"parents\".\"id\" = 1)`\r\n\r\n", "comments": [ { "body": "That indeed seems like a bug to me. Welcoming prs for this.", "created_at": "2019-05-28T11:35:19Z" }, { "body": "Pr for this was merged.", "created_at": "2019-06-05T19:40:24Z" } ], "number": 28638, "title": "MorphTo Relation ignores parent $timestamp when touching" }
{ "body": "Fixed bug with touching model which has $timestamps set to false resulting in `Illuminate\\Database\\QueryException: SQLSTATE[HY000]: General error: 1 no such column: updated_at`\r\n\r\nfor source issue and more details see #28638 ", "number": 28658, "review_comments": [], "title": "[5.8] fix MorphTo Relation ignores parent $timestamp when touching" }
{ "commits": [ { "message": "fix touch ignoring $timestamps" }, { "message": "fix touching model with $timestamps = false - added tests" } ], "files": [ { "diff": "@@ -294,6 +294,10 @@ public static function isIgnoringTouch($class = null)\n {\n $class = $class ?: static::class;\n \n+ if (!get_class_vars($class)['timestamps']) {\n+ return true;\n+ }\n+\n foreach (static::$ignoreOnTouch as $ignoredClass) {\n if ($class === $ignoredClass || is_subclass_of($class, $ignoredClass)) {\n return true;", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -1886,6 +1886,18 @@ public function testWithoutTouchingOnCallback()\n $this->assertTrue($called);\n }\n \n+ public function testTouchingModelWithTimestamps() {\n+ $this->assertFalse(\n+ Model::isIgnoringTouch(Model::class)\n+ );\n+ }\n+\n+ public function testNotTouchingModelWithoutTimestamps() {\n+ $this->assertTrue(\n+ Model::isIgnoringTouch(EloquentModelWithoutTimestamps::class)\n+ );\n+ }\n+\n protected function addMockConnection($model)\n {\n $model->setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class));\n@@ -2303,3 +2315,9 @@ class EloquentModelEventObjectStub extends Model\n 'saving' => EloquentModelSavingEventStub::class,\n ];\n }\n+\n+class EloquentModelWithoutTimestamps extends Model\n+{\n+ protected $table = 'stub';\n+ public $timestamps = false;\n+}", "filename": "tests/Database/DatabaseEloquentModelTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.13\r\n- PHP Version: 7.2.15\r\n- Database Driver & Version: none\r\n\r\n### Description:\r\n\r\nYou can't run `composer update` and call `artisan` commands if add `Schema::defaultStringLength` calling to `AppServiceProvider` and you have `doctrine/dbal` package. \r\n\r\nOn running `composer require doctrine/dbal`:\r\n```\r\nIn PDOConnection.php line 31:\r\n \r\n SQLSTATE[HY000] [2002] Connection refused \r\n \r\n\r\nIn PDOConnection.php line 27:\r\n \r\n SQLSTATE[HY000] [2002] Connection refused \r\n```\r\n\r\nOn 5.8.12 works fine.\r\n\r\n### Steps To Reproduce:\r\n\r\n1. Create new project:\r\n```\r\ncomposer create-project --prefer-dist laravel/laravel blog\r\n```\r\n\r\n2. Fix `1071 Specified key was too long` error:\r\nUsing official documentation: https://laravel.com/docs/5.8/migrations#indexes\r\n\r\nAdd `Schema::defaultStringLength` calling to `AppServiceProvider`\r\n\r\n```\r\nuse Illuminate\\Support\\Facades\\Schema;\r\n\r\n/**\r\n * Bootstrap any application services.\r\n *\r\n * @return void\r\n */\r\npublic function boot()\r\n{\r\n Schema::defaultStringLength(191);\r\n}\r\n```\r\n\r\n3. Try to install `doctrine/dbal` package:\r\n```\r\ncomposer require doctrine/dbal\r\n```\r\n\r\nYou will get error:\r\n```\r\nIn PDOConnection.php line 31:\r\n \r\n SQLSTATE[HY000] [2002] Connection refused \r\n \r\n\r\nIn PDOConnection.php line 27:\r\n \r\n SQLSTATE[HY000] [2002] Connection refused \r\n \r\n\r\nScript @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1\r\n```", "comments": [ { "body": "This is caused by #28214. /cc @JacksonIV \r\n\r\nWe should only call `registerCustomDoctrineTypes()` when we are actually running migrations.", "created_at": "2019-04-20T15:15:44Z" }, { "body": "@staudenmeir I’ll look into this. 👍🏼", "created_at": "2019-04-20T18:42:11Z" }, { "body": "I have tried a few things but I can't seem to reproduce this on a new laravel installation. Could you please provide me with some more information as where you encounter this error? Are you sure your database credentials and settings are correct?\r\n\r\nAlso, please make sure you are running:\r\n\r\n`composer require doctrine/dbal`\r\n\r\ninstead of:\r\n\r\n`composer require docktrine/dbal`", "created_at": "2019-04-20T20:51:09Z" }, { "body": "The error only happens when a database connection is *not* available.\r\n\r\nSomething like `Schema::defaultStringLength(191);` doesn't access the database and should work without a connection. Even if a connection is available, the builder shouldn't unnecessarily open one.", "created_at": "2019-04-20T20:57:58Z" }, { "body": "@staudenmeir Everything seems to work fine here, even without a connection. Maybe i'm doing something wrong though. Can you reproduce this on your Laravel installation?\r\n\r\n`Schema::defaultStringLength();` is a static method, so the constructor will not be called. Thefore the custom types won't be registered, right?", "created_at": "2019-04-20T21:18:13Z" }, { "body": "Yes, I can reproduce it:\r\n\r\n- Laravel 5.8.13\r\n- `doctrine/dbal` installed\r\n- `Schema::defaultStringLength(191);` in `AppServiceProvider::boot()`\r\n- `DB_CONNECTION=mysql` in `.env`\r\n\r\nI can trigger the error with `composer dump` or `php artisan serve`.", "created_at": "2019-04-20T21:29:04Z" }, { "body": "The constructor does get called. Take a look at `Illuminate\\Support\\Facades::getFacadeAccessor()`.", "created_at": "2019-04-20T21:32:28Z" }, { "body": "@staudenmeir I still have a hard time understanding how this can happen since the connection is first instantiated there?", "created_at": "2019-04-22T12:33:03Z" }, { "body": "@driesvints When the custom DBAL types get registered in the builder’s constructor it tries to find a Doctrine connection. If there’s no Doctrine connection, it will try to instantiate one. But if the database credentials or settings are incorrect it will throw a PDO exception. \r\n\r\nIf the database settings and credentials are correct, there’s no problem though. This could indeed be fixed by moving the actual registration to the migrator. \r\n\r\nI will try to fix this as soon as i can, but unfortunately i’m a little short on time currently.", "created_at": "2019-04-22T14:02:10Z" }, { "body": "On the other hand, if you are calling the schema facade, you’d probably want a working database connection, right?", "created_at": "2019-04-22T14:18:24Z" }, { "body": "@driesvints The facade only instantiates an instance of the `Connection` class, but doesn't actually connect to the database. This happens in `getPdo()`.\r\n\r\nIs that what you mean?", "created_at": "2019-04-22T14:21:45Z" }, { "body": "@JacksonIV Probably, but not necessarily immediately. Only instantiating an instance of a class like `MySqlBuilder` (or any other class) should never open an actual database connection.", "created_at": "2019-04-22T14:26:09Z" }, { "body": "@staudenmeir I see what you mean. It's imperative that we get this fixed soon though. Otherwise it's best that we revert for now.", "created_at": "2019-04-22T14:44:44Z" }, { "body": "@driesvints Instead of reverting everything, i could make a PR which removes the registration of the custom DBAL types in the constructor of the MySQL builder. This way people can still call the `registerCustomDBALType` method manually without any problems.", "created_at": "2019-04-22T15:27:31Z" }, { "body": "I would revert it. Then we can take the time to fix this properly and also cover the other databases (https://github.com/laravel/framework/pull/28214#issuecomment-483012555).", "created_at": "2019-04-22T15:35:29Z" }, { "body": "@staudenmeir You're right, i'll start working on a proper fix as soon as possible. I'll also try to cover the other databases simultaneously!\r\n\r\nSorry for the hassle!", "created_at": "2019-04-22T15:39:55Z" }, { "body": "I've removed the method call in the constructor for now and this will be released tomorrow. Please send in a better solution as soon as you're able to, thanks!\r\n\r\nhttps://github.com/laravel/framework/pull/28301", "created_at": "2019-04-22T19:43:41Z" }, { "body": "@driesvints this also breaks the `package:discover` command that runs after `composer install`. I noticed this because our build process started failing as there is no `.env` and no database available yet at the `composer install` step in our build process.\r\n\r\nAfter applying your revert from https://github.com/laravel/framework/pull/28301 it started working again.\r\n\r\nHopefully this can be tagged soon and properly addressed later. :)", "created_at": "2019-04-23T10:11:58Z" }, { "body": "I also receive this error if I call getDoctrineSchemaManager() within my console command constructor with laravel 6.2 and doctrine/dbal ^2.10\r\n\r\n> Doctrine\\DBAL\\Driver\\PDOException : SQLSTATE[HY000] [2002] Connection refused\r\n\r\nAs soon as I move this call to the handle() method, it works as expected.", "created_at": "2020-04-14T13:19:41Z" }, { "body": "I receive this error when I call composer install!\r\nin which version did you fix this issue??", "created_at": "2020-09-01T18:59:20Z" } ], "number": 28282, "title": "[5.8.13] 'SQLSTATE[HY000] [2002] Connection refused' if docktrine/dbal installed" }
{ "body": "This PR removes the TinyInteger type from the core and allows the user to register their own custom Doctrine DBAL types. No connection wil be established by only instantiating the builder class, only as soon as you call the registerCustomDoctrineType method. Therefore it won't cause issues like #28282 anymore.", "number": 28375, "review_comments": [], "title": "[5.8] Fix the remaining issues with registering custom Doctrine types." }
{ "commits": [ { "message": "Fix the remaining issues with registering custom Doctrine types." }, { "message": "Fix a styling issue." } ], "files": [ { "diff": "@@ -4,6 +4,7 @@\n \n use Closure;\n use LogicException;\n+use RuntimeException;\n use Doctrine\\DBAL\\Types\\Type;\n use Illuminate\\Database\\Connection;\n \n@@ -297,16 +298,20 @@ protected function createBlueprint($table, Closure $callback = null)\n */\n public function registerCustomDoctrineType($class, $name, $type)\n {\n- if (Type::hasType($name)) {\n- return;\n+ if (! $this->connection->isDoctrineAvailable()) {\n+ throw new RuntimeException(\n+ 'Registering a custom Doctrine type requires Doctrine DBAL; install \"doctrine/dbal\".'\n+ );\n }\n \n- Type::addType($name, $class);\n+ if (! Type::hasType($name)) {\n+ Type::addType($name, $class);\n \n- $this->connection\n- ->getDoctrineSchemaManager()\n- ->getDatabasePlatform()\n- ->registerDoctrineTypeMapping($type, $name);\n+ $this->connection\n+ ->getDoctrineSchemaManager()\n+ ->getDatabasePlatform()\n+ ->registerDoctrineTypeMapping($type, $name);\n+ }\n }\n \n /**", "filename": "src/Illuminate/Database/Schema/Builder.php", "status": "modified" }, { "diff": "@@ -2,8 +2,6 @@\n \n namespace Illuminate\\Database\\Schema;\n \n-use Illuminate\\Database\\Schema\\Types\\TinyInteger;\n-\n class MySqlBuilder extends Builder\n {\n /**\n@@ -113,20 +111,4 @@ protected function getAllViews()\n $this->grammar->compileGetAllViews()\n );\n }\n-\n- /**\n- * Register the custom Doctrine mapping types for the MySQL builder.\n- *\n- * @return void\n- *\n- * @throws \\Doctrine\\DBAL\\DBALException\n- */\n- protected function registerCustomDoctrineTypes()\n- {\n- if ($this->connection->isDoctrineAvailable()) {\n- $this->registerCustomDoctrineType(\n- TinyInteger::class, TinyInteger::NAME, 'TINYINT'\n- );\n- }\n- }\n }", "filename": "src/Illuminate/Database/Schema/MySqlBuilder.php", "status": "modified" }, { "diff": "@@ -11,7 +11,7 @@\n * @method static void defaultStringLength(int $length)\n * @method static \\Illuminate\\Database\\Schema\\Builder disableForeignKeyConstraints()\n * @method static \\Illuminate\\Database\\Schema\\Builder enableForeignKeyConstraints()\n- * @method static void registerCustomDBALType(string $class, string $name, string $type)\n+ * @method static void registerCustomDoctrineType(string $class, string $name, string $type)\n *\n * @see \\Illuminate\\Database\\Schema\\Builder\n */", "filename": "src/Illuminate/Support/Facades/Schema.php", "status": "modified" }, { "diff": "@@ -6,9 +6,9 @@\n use Illuminate\\Support\\Facades\\DB;\n use Illuminate\\Support\\Facades\\Schema;\n use Illuminate\\Database\\Schema\\Blueprint;\n-use Illuminate\\Database\\Schema\\Types\\TinyInteger;\n use Illuminate\\Database\\Schema\\Grammars\\SQLiteGrammar;\n use Illuminate\\Tests\\Integration\\Database\\DatabaseTestCase;\n+use Illuminate\\Tests\\Integration\\Database\\Fixtures\\TinyInteger;\n \n /**\n * @group integration", "filename": "tests/Integration/Database/SchemaBuilderTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.7.+\r\n- PHP Version: 7.2.11\r\n- Database Driver & Version:\r\nPECL redis 4.1.1\r\n### Description:\r\nCant set Redis::OPT_SERIALIZER to any value, thats because of:\r\n[serialize](https://github.com/laravel/framework/blob/c3b7a12f36b3eec1bdd7633c61a2dc1b7d6043f3/src/Illuminate/Cache/RedisStore.php#L276src/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php:287)\r\nand\r\n[unserialize](https://github.com/laravel/framework/blob/c3b7a12f36b3eec1bdd7633c61a2dc1b7d6043f3/src/Illuminate/Cache/RedisStore.php#L287)\r\nmethods in RedisStore.\r\n\r\nStore needs refactor, to accept Redis::SERIALIZER_IGBINARY", "comments": [ { "body": "This needs a little more info. What are you actually trying to do? Can you provide some code examples? How do the Redis options affect the linked code?", "created_at": "2018-11-09T15:52:59Z" }, { "body": "Laravel RedisStore implementation has php serialize() / unserialize() hardcoded. This prevents igbinary serialization of strings if option passed to phpredis", "created_at": "2018-11-09T16:28:18Z" }, { "body": "Ah I see. Yeah that should be made possible. Feel free to send in a PR if you know how to fix this.", "created_at": "2018-11-09T16:29:59Z" }, { "body": "https://github.com/laravel/framework/pull/31182 has been merged so you can now set custom serializers.", "created_at": "2020-01-21T17:01:34Z" } ], "number": 26186, "title": "RedisStore, cant set Redis::OPT_SERIALIZER to Redis::SERIALIZER_IGBINARY because of hardcoded serialization" }
{ "body": "<!--\r\nPlease only send a pull request to branches which are currently supported: https://laravel.com/docs/releases#support-policy \r\n\r\nIf you are unsure which branch your pull request should be sent to, please read: https://laravel.com/docs/contributions#which-branch\r\n\r\nPull requests without a descriptive title, thorough description, or tests will be closed.\r\n\r\nIn addition, please describe the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.\r\n-->\r\n\r\nThis PR aims to fix #26186 adding the ability to configure the PredisConnector to use `igBinary` serializer.\r\n\r\n## Backward compatible\r\nIt is backward compatible, or at least does not brake anything, by moving the `serialize`/`unserialize` functionality into the Connectors. That way, any connector without it's own serializer can use the native PHP one. Predis itself will use the native serialization if no specific one is set.", "number": 28345, "review_comments": [], "title": "[5.8] Fix allow serialize igbinary" }
{ "commits": [ { "message": "Adds serialize method per redisConnection so predis can use igBinary serialization" }, { "message": "Updates test to use redisConnectors' serialize method" } ], "files": [ { "diff": "@@ -292,7 +292,7 @@ public function setPrefix($prefix)\n */\n protected function serialize($value)\n {\n- return is_numeric($value) ? $value : serialize($value);\n+ return is_numeric($value) ? $value : $this->connection()->serialize($value);\n }\n \n /**\n@@ -303,6 +303,6 @@ protected function serialize($value)\n */\n protected function unserialize($value)\n {\n- return is_numeric($value) ? $value : unserialize($value);\n+ return is_numeric($value) ? $value : $this->connection()->unserialize($value);\n }\n }", "filename": "src/Illuminate/Cache/RedisStore.php", "status": "modified" }, { "diff": "@@ -433,4 +433,26 @@ public function __call($method, $parameters)\n {\n return parent::__call(strtolower($method), $parameters);\n }\n+\n+ /**\n+ * Serialize the value. Using PhpRedis's native serialize methods\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ protected function serialize($value)\n+ {\n+ return $this->client->_serialize($value);\n+ }\n+\n+ /**\n+ * Unserialize the value. Using PhpRedis's native serialize methods\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ protected function unserialize($value)\n+ {\n+ return $this->client->_unserialize($value);\n+ }\n }", "filename": "src/Illuminate/Redis/Connections/PhpRedisConnection.php", "status": "modified" }, { "diff": "@@ -43,4 +43,26 @@ public function createSubscription($channels, Closure $callback, $method = 'subs\n \n unset($loop);\n }\n+\n+ /**\n+ * Serialize the value.\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ protected function serialize($value)\n+ {\n+ return serialize($value);\n+ }\n+\n+ /**\n+ * Unserialize the value.\n+ *\n+ * @param mixed $value\n+ * @return mixed\n+ */\n+ protected function unserialize($value)\n+ {\n+ return unserialize($value);\n+ }\n }", "filename": "src/Illuminate/Redis/Connections/PredisConnection.php", "status": "modified" }, { "diff": "@@ -80,6 +80,10 @@ protected function createClient(array $config)\n if (! empty($config['read_timeout'])) {\n $client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']);\n }\n+\n+ if (! empty($config['serializer'])) {\n+ $client->setOption(Redis::OPT_SERIALIZER, $config['serializer']);\n+ }\n });\n }\n ", "filename": "src/Illuminate/Redis/Connectors/PhpRedisConnector.php", "status": "modified" }, { "diff": "@@ -25,15 +25,16 @@ public function testGetReturnsNullWhenNotFound()\n public function testRedisValueIsReturned()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('connection')->twice()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('foo'));\n+ $redis->getRedis()->shouldReceive('unserialize')->once()->with(serialize('foo'))->andReturn('foo');\n $this->assertEquals('foo', $redis->get('foo'));\n }\n \n public function testRedisMultipleValuesAreReturned()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('connection')->times(4)->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('mget')->once()->with(['prefix:foo', 'prefix:fizz', 'prefix:norf', 'prefix:null'])\n ->andReturn([\n serialize('bar'),\n@@ -42,6 +43,10 @@ public function testRedisMultipleValuesAreReturned()\n null,\n ]);\n \n+ $redis->getRedis()->shouldReceive('unserialize')->with(serialize('bar'))->andReturn('bar');\n+ $redis->getRedis()->shouldReceive('unserialize')->with(serialize('buzz'))->andReturn('buzz');\n+ $redis->getRedis()->shouldReceive('unserialize')->with(serialize('quz'))->andReturn('quz');\n+\n $results = $redis->many(['foo', 'fizz', 'norf', 'null']);\n \n $this->assertEquals('bar', $results['foo']);\n@@ -61,8 +66,10 @@ public function testRedisValueIsReturnedForNumerics()\n public function testSetMethodProperlyCallsRedis()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('serialize')->andReturn(serialize('foo'));\n+ $redis->getRedis()->shouldReceive('connection')->twice()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('foo'))->andReturn('OK');\n+ $redis->getRedis()->shouldReceive('serialize');\n $result = $redis->put('foo', 'foo', 60);\n $this->assertTrue($result);\n }\n@@ -77,6 +84,11 @@ public function testSetMultipleMethodProperlyCallsRedis()\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('bar'))->andReturn('OK');\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:baz', 60, serialize('qux'))->andReturn('OK');\n $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:bar', 60, serialize('norf'))->andReturn('OK');\n+\n+ $redis->getRedis()->shouldReceive('serialize')->with('bar')->andReturn(serialize('bar'));\n+ $redis->getRedis()->shouldReceive('serialize')->with('qux')->andReturn(serialize('qux'));\n+ $redis->getRedis()->shouldReceive('serialize')->with('norf')->andReturn(serialize('norf'));\n+\n $connection->shouldReceive('exec')->once();\n \n $result = $redis->putMany([\n@@ -115,8 +127,9 @@ public function testDecrementMethodProperlyCallsRedis()\n public function testStoreItemForeverProperlyCallsRedis()\n {\n $redis = $this->getRedis();\n- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());\n+ $redis->getRedis()->shouldReceive('connection')->twice()->with('default')->andReturn($redis->getRedis());\n $redis->getRedis()->shouldReceive('set')->once()->with('prefix:foo', serialize('foo'))->andReturn('OK');\n+ $redis->getRedis()->shouldReceive('serialize')->with('foo')->andReturn(serialize('foo'));\n $result = $redis->forever('foo', 'foo', 60);\n $this->assertTrue($result);\n }", "filename": "tests/Cache/CacheRedisStoreTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8.12\r\n- PHP Version: 7.2.14\r\n- Database Driver & Version: MySQL 5.7.20\r\n\r\n### Description:\r\nJust this morning upgraded from 5.8.11 to 5.8.12 which completely broke my application on the wherePivot part.\r\n\r\n**Broken:**\r\n```php\r\n$variable = $user->books()->wherePivot('owner', true)->findOrFail($id);\r\n```\r\n\r\n**Fixed:**\r\n```php\r\n$variable = $user->books()->wherePivot('owner', '=', true)->findOrFail($id);\r\n```\r\n\r\nHas this been done intentionally? I cannot find anything regarding this change inside the core update. My code has not changed since the upgrade from 5.8.11 -> 5.8.12", "comments": [ { "body": "It seems to me like a unintentional change, because it's not regarding every other where statement where it's just assumed that '=' is the operator if no operator is specified. Could this possibly be related to the changes made to the where here: https://github.com/laravel/framework/pull/28192 ", "created_at": "2019-04-18T08:15:05Z" }, { "body": "Lucky i am using `withPivotValue()` method which internally uses\r\n```php\r\n$this->wherePivot($column, '=', $value)\r\n```", "created_at": "2019-04-18T10:21:23Z" }, { "body": "@ankurk91 I fail to see how this is contributing to this core issue.", "created_at": "2019-04-18T10:23:45Z" }, { "body": "Hey, the original PR was reverted (04a547ee25f78ddd738610cdbda2cb393c6795e9) and was released in 5.8.13. This issue is now solved. An additional test has been submitted to prevent future issues. #28260", "created_at": "2019-04-18T18:08:38Z" }, { "body": "This issue has arisen again in Laravel Version 5.8.23", "created_at": "2019-06-28T18:14:59Z" }, { "body": "@mjhorninger What query causes this error for you?", "created_at": "2019-06-28T18:19:57Z" }, { "body": "So it's a nested set of models, and needs to be refactored desperately.\r\nWe can query all the way down through three layers of models, but when we try to access a convenience method on the bottom layer that retrieves a non-related model, it breaks.", "created_at": "2019-06-28T18:25:03Z" }, { "body": "The bottom query that fails is: `Pair::whereIn('id', $groupOfPairIds)->get();`", "created_at": "2019-06-28T18:31:05Z" }, { "body": "What's the last working Laravel version?", "created_at": "2019-06-28T18:42:47Z" }, { "body": "What's the result of `dd($groupOfPairIds);`?", "created_at": "2019-06-28T18:45:47Z" }, { "body": "dd($groupOfPairIds) gives an array - \r\n`[\r\n0 => 32 \r\n1 => 34, \r\n2 => 36\r\n3 => 38\r\n]`", "created_at": "2019-06-28T18:48:25Z" }, { "body": "Did you see my other question?\r\n\r\n> What's the last working Laravel version?", "created_at": "2019-06-28T19:17:11Z" }, { "body": "I did. Unfortunately, I got sucked into a meeting. I'm peeling back the onion based on our upgrade path and testing with 5.8.13 now", "created_at": "2019-06-28T19:26:31Z" }, { "body": "I'm all the way back at 5.8.0 which means this piece of functionality does not get tested very often. I'm still seeing the issue. \r\nAt this point it had to be something peculiar to our stack. I have tested the call in tinker and it works all the way forward to the latest version (.26). It's not until the datatables get involved that it starts to fall apart.\r\nMea culpa - Sorry to send you on the wild goose chase.", "created_at": "2019-06-28T19:44:57Z" }, { "body": "j", "created_at": "2020-03-28T08:19:50Z" } ], "number": 28251, "title": "[5.8] Argument 1 passed to Illuminate\\Database\\Query\\Builder::cleanBindings() must be of the type array, null given" }
{ "body": "## Description\r\n\r\nFixes breaking change introduced in #28192, which used weak comparison which in turn caused searching for boolean values `belongsToManyRelation->wherePivot('primary', true)` (without specifying operator) (See #28251 for more details) in the pivot table to evaluate to true for the conditions [`$operator == 'in'`](https://github.com/laravel/framework/pull/28192/files#diff-cc3d43e01028390141596ae0da939930R622) / [`$operator == 'not in'`](https://github.com/laravel/framework/pull/28192/files#diff-cc3d43e01028390141596ae0da939930R626).\r\n\r\nSwitching to typed comparison takes care of this issue.", "number": 28252, "review_comments": [], "title": "[5.8] Fix belongsToMany->wherePivot condition for boolean columns" }
{ "commits": [ { "message": "Fix issue #28251" } ], "files": [ { "diff": "@@ -619,11 +619,11 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'\n // If the operator is a literal string 'in' or 'not in', we will assume that\n // the developer wants to use the \"whereIn / whereNotIn\" methods for this\n // operation and proxy the query through those methods from this point.\n- if ($operator == 'in') {\n+ if ($operator === 'in') {\n return $this->whereIn($column, $value, $boolean);\n }\n \n- if ($operator == 'not in') {\n+ if ($operator === 'not in') {\n return $this->whereNotIn($column, $value, $boolean);\n }\n ", "filename": "src/Illuminate/Database/Query/Builder.php", "status": "modified" }, { "diff": "@@ -604,6 +604,24 @@ public function test_global_scope_columns()\n \n $this->assertEquals(['id' => 1], $tags[0]->getAttributes());\n }\n+\n+ public function test_where_pivot_with_boolean_column_query()\n+ {\n+ Schema::table('posts_tags', function (Blueprint $table) {\n+ $table->boolean('primary')->default(false)->after('flag');\n+ });\n+\n+ $tag = Tag::create(['name' => Str::random()]);\n+ $post = Post::create(['title' => Str::random()]);\n+\n+ DB::table('posts_tags')->insert([\n+ ['post_id' => $post->id, 'tag_id' => $tag->id, 'primary' => true]\n+ ]);\n+\n+ $relationTag = $post->tags()->wherePivot('primary', true)->first();\n+\n+ $this->assertEquals($relationTag->getAttributes(), $tag->getAttributes());\n+ }\n }\n \n class Post extends Model", "filename": "tests/Integration/Database/EloquentBelongsToManyTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8\r\n- PHP Version: 7.3\r\n- Database Driver & Version: MySQL 5.7\r\n\r\n### Description:\r\nThe Model::is($other) method is used to check if two model objects refer to the same database record. This works fine when both models exist and have been assigned primary keys. But if neither model has been persisted, it will always return true since null === null.\r\n\r\n### Steps To Reproduce:\r\n\r\n```\r\n$modelA = new Foo();\r\n$modelB = new Foo();\r\nvar_dump($modelA->is($modelB));\r\n// returns true but should return false\r\n```\r\n\r\n### Proposed Fix:\r\n\r\nWithout primary keys to reference, there is no foolproof way to determine if the two model objects are really the same. However, we could make the test more accurate in this scenario by testing for identity with a === check in cases when the models don't exist.\r\n\r\n\r\n```\r\n /**\r\n * Determine if two models have the same ID and belong to the same table.\r\n *\r\n * @param \\Illuminate\\Database\\Eloquent\\Model|null $model\r\n * @return bool\r\n */\r\n public function is($model)\r\n {\r\n return !$this->exists ? \r\n $this === $model : \r\n ! is_null($model) &&\r\n $this->getKey() === $model->getKey() &&\r\n $this->getTable() === $model->getTable() &&\r\n $this->getConnectionName() === $model->getConnectionName();\r\n }\r\n\r\n```\r\n", "comments": [ { "body": "\"belong to the same table\" does it include their existence or just they are both related to the same table?", "created_at": "2019-04-11T13:53:49Z" }, { "body": "@akiyamaSM I'm not sure I understand your question. In both the existing and proposed versions of the method, the test includes checking for table/class, if that's what you mean. ", "created_at": "2019-04-11T14:46:16Z" }, { "body": "It was a question about the description of the method, what they mean by \"they blong to the same table\".\r\ndo they mean there is a record already? or just that they are under the same of table. Hope I didn't make it worse.", "created_at": "2019-04-11T14:54:30Z" }, { "body": "```is()``` doesn't provide an answer to \"does either model exist in the database\", just that the model 'belongs' to the same table and has the same id(even if null). With Eloquent, all models belong to a table that is either specified on the model class or inferred from the name of the class. \r\n\r\n```php\r\n$user = new User;\r\n$user2 = new User;\r\n$user->is($user2); //true\r\n\r\n$user = new User;\r\n$post = new Post;\r\n$user->is($post); //false\r\n```\r\nYou can use the ```exists``` property to check if the model is actually in the database.\r\n```php\r\n$user = new User;\r\n$user->exists; //false\r\n\r\n$user = User::find(1);\r\n$user->exists; //true (if indeed the 'find' call was successful.\r\n```", "created_at": "2019-04-16T15:18:56Z" }, { "body": "Yeah, I understand that. But is() should be testing to see if the two objects refer to the same record, which may or may not be the case, regardless of whether they've been persisted yet. ", "created_at": "2019-04-16T16:43:22Z" }, { "body": "@adamthehutt I guess that's the key, if they are not yet persisted or at least one of them we can't compare, can we?", "created_at": "2019-04-16T16:49:25Z" }, { "body": "Right, but at the very minimum it shouldn't be returning true automatically in that situation. I think testing for identity with === makes sense as a fallback.", "created_at": "2019-04-16T16:54:45Z" }, { "body": "FWIW, the real solution to this problem is to implement an Identity Map for Eloquent, which would be amazingly useful. ", "created_at": "2019-04-16T16:57:45Z" }, { "body": "Since the PR was rejected I'm going to close this. As suggested, please do the check in userland.", "created_at": "2019-04-19T13:30:36Z" } ], "number": 28172, "title": "Model::is() gives false positive when models don't exist" }
{ "body": "Following up from a #28240 which made this change against 5.8 this applies it to the next release. The commentary from the previous PR highlighted the breaking change of this bug fix and that perhaps it should be held off for now.\r\n\r\n> This fixes an issue with is() as described in #28172 where it would return true when given model instances that weren't actually persisted in the database. I think the expected functionality would be that it only returns true when comparing persisted database records.\r\n\r\nIn updating other tests that used `is()` without taking into considering actual database persistence I've just relaxed them to a simple ID comparison - I think that's probably a better compromise than having to set `$exists = true` to get them to pass.", "number": 28242, "review_comments": [], "title": "[5.9] Fix issue with is() and unpersisted models" }
{ "commits": [ { "message": "Fix issue with is() and unpersisted models" } ], "files": [ { "diff": "@@ -1189,6 +1189,8 @@ public function replicate(array $except = null)\n public function is($model)\n {\n return ! is_null($model) &&\n+ $this->exists &&\n+ $model->exists &&\n $this->getKey() === $model->getKey() &&\n $this->getTable() === $model->getTable() &&\n $this->getConnectionName() === $model->getConnectionName();", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -1513,7 +1513,7 @@ public function testReplicatingEventIsFiredWhenReplicatingModel()\n \n $model->setEventDispatcher($events = m::mock(Dispatcher::class));\n $events->shouldReceive('dispatch')->once()->with('eloquent.replicating: '.get_class($model), m::on(function ($m) use ($model) {\n- return $model->is($m);\n+ return $model->getKey() === $m->getKey();\n }));\n \n $model->replicate();\n@@ -1821,31 +1821,55 @@ public function testScopesMethod()\n public function testIsWithNull()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = null;\n \n $this->assertFalse($firstInstance->is($secondInstance));\n }\n \n+ public function testIsWithUnpersistedModelInstance()\n+ {\n+ $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n+ $secondInstance = new EloquentModelStub;\n+ $result = $firstInstance->is($secondInstance);\n+ $this->assertFalse($result);\n+ }\n+\n+ public function testIsWithUnpersistedModelInstances()\n+ {\n+ $firstInstance = new EloquentModelStub;\n+ $secondInstance = new EloquentModelStub;\n+ $result = $firstInstance->is($secondInstance);\n+ $this->assertFalse($result);\n+ }\n+\n public function testIsWithTheSameModelInstance()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 1]);\n+ $secondInstance->exists = true;\n $result = $firstInstance->is($secondInstance);\n $this->assertTrue($result);\n }\n \n public function testIsWithAnotherModelInstance()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 2]);\n+ $secondInstance->exists = true;\n $result = $firstInstance->is($secondInstance);\n $this->assertFalse($result);\n }\n \n public function testIsWithAnotherTable()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 1]);\n+ $secondInstance->exists = true;\n $secondInstance->setTable('foo');\n $result = $firstInstance->is($secondInstance);\n $this->assertFalse($result);\n@@ -1854,7 +1878,9 @@ public function testIsWithAnotherTable()\n public function testIsWithAnotherConnection()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 1]);\n+ $secondInstance->exists = true;\n $secondInstance->setConnection('foo');\n $result = $firstInstance->is($secondInstance);\n $this->assertFalse($result);", "filename": "tests/Database/DatabaseEloquentModelTest.php", "status": "modified" }, { "diff": "@@ -559,7 +559,7 @@ public function test_original_on_response_is_model_when_single_resource()\n $response = $this->withoutExceptionHandling()->get(\n '/', ['Accept' => 'application/json']\n );\n- $this->assertTrue($createdPost->is($response->getOriginalContent()));\n+ $this->assertEquals($createdPost->getKey(), $response->getOriginalContent()->getKey());\n }\n \n public function test_original_on_response_is_collection_of_model_when_collection_resource()", "filename": "tests/Integration/Http/ResourceTest.php", "status": "modified" } ] }
{ "body": "- Laravel Version: 5.8\r\n- PHP Version: 7.3\r\n- Database Driver & Version: MySQL 5.7\r\n\r\n### Description:\r\nThe Model::is($other) method is used to check if two model objects refer to the same database record. This works fine when both models exist and have been assigned primary keys. But if neither model has been persisted, it will always return true since null === null.\r\n\r\n### Steps To Reproduce:\r\n\r\n```\r\n$modelA = new Foo();\r\n$modelB = new Foo();\r\nvar_dump($modelA->is($modelB));\r\n// returns true but should return false\r\n```\r\n\r\n### Proposed Fix:\r\n\r\nWithout primary keys to reference, there is no foolproof way to determine if the two model objects are really the same. However, we could make the test more accurate in this scenario by testing for identity with a === check in cases when the models don't exist.\r\n\r\n\r\n```\r\n /**\r\n * Determine if two models have the same ID and belong to the same table.\r\n *\r\n * @param \\Illuminate\\Database\\Eloquent\\Model|null $model\r\n * @return bool\r\n */\r\n public function is($model)\r\n {\r\n return !$this->exists ? \r\n $this === $model : \r\n ! is_null($model) &&\r\n $this->getKey() === $model->getKey() &&\r\n $this->getTable() === $model->getTable() &&\r\n $this->getConnectionName() === $model->getConnectionName();\r\n }\r\n\r\n```\r\n", "comments": [ { "body": "\"belong to the same table\" does it include their existence or just they are both related to the same table?", "created_at": "2019-04-11T13:53:49Z" }, { "body": "@akiyamaSM I'm not sure I understand your question. In both the existing and proposed versions of the method, the test includes checking for table/class, if that's what you mean. ", "created_at": "2019-04-11T14:46:16Z" }, { "body": "It was a question about the description of the method, what they mean by \"they blong to the same table\".\r\ndo they mean there is a record already? or just that they are under the same of table. Hope I didn't make it worse.", "created_at": "2019-04-11T14:54:30Z" }, { "body": "```is()``` doesn't provide an answer to \"does either model exist in the database\", just that the model 'belongs' to the same table and has the same id(even if null). With Eloquent, all models belong to a table that is either specified on the model class or inferred from the name of the class. \r\n\r\n```php\r\n$user = new User;\r\n$user2 = new User;\r\n$user->is($user2); //true\r\n\r\n$user = new User;\r\n$post = new Post;\r\n$user->is($post); //false\r\n```\r\nYou can use the ```exists``` property to check if the model is actually in the database.\r\n```php\r\n$user = new User;\r\n$user->exists; //false\r\n\r\n$user = User::find(1);\r\n$user->exists; //true (if indeed the 'find' call was successful.\r\n```", "created_at": "2019-04-16T15:18:56Z" }, { "body": "Yeah, I understand that. But is() should be testing to see if the two objects refer to the same record, which may or may not be the case, regardless of whether they've been persisted yet. ", "created_at": "2019-04-16T16:43:22Z" }, { "body": "@adamthehutt I guess that's the key, if they are not yet persisted or at least one of them we can't compare, can we?", "created_at": "2019-04-16T16:49:25Z" }, { "body": "Right, but at the very minimum it shouldn't be returning true automatically in that situation. I think testing for identity with === makes sense as a fallback.", "created_at": "2019-04-16T16:54:45Z" }, { "body": "FWIW, the real solution to this problem is to implement an Identity Map for Eloquent, which would be amazingly useful. ", "created_at": "2019-04-16T16:57:45Z" }, { "body": "Since the PR was rejected I'm going to close this. As suggested, please do the check in userland.", "created_at": "2019-04-19T13:30:36Z" } ], "number": 28172, "title": "Model::is() gives false positive when models don't exist" }
{ "body": "This fixes an issue with `is()` as described in #28172 where it would return `true` when given model instances that weren't actually persisted in the database. I think the expected functionality would be that it only returns true when comparing persisted database records.\r\n\r\nI had to set `exists = true` for the test cases here to keep them valid - I did attempt to set it on the `EloquentModelStub` but it broke other tests, so felt it was more appropriate to be explicit on the relevant tests instead. Let me know if you'd prefer another approach.\r\n", "number": 28240, "review_comments": [], "title": "[5.8] Fix issue with is() and unpersisted models" }
{ "commits": [ { "message": "Fix issue with is() and unpersisted models" }, { "message": "Fix outstanding texts" } ], "files": [ { "diff": "@@ -1189,6 +1189,8 @@ public function replicate(array $except = null)\n public function is($model)\n {\n return ! is_null($model) &&\n+ $this->exists &&\n+ $model->exists &&\n $this->getKey() === $model->getKey() &&\n $this->getTable() === $model->getTable() &&\n $this->getConnectionName() === $model->getConnectionName();", "filename": "src/Illuminate/Database/Eloquent/Model.php", "status": "modified" }, { "diff": "@@ -252,12 +252,16 @@ public function testCollectionReturnsDuplicateBasedOnlyOnKeys()\n $three = new TestEloquentCollectionModel();\n $four = new TestEloquentCollectionModel();\n $one->id = 1;\n+ $one->exists = 1;\n $one->someAttribute = '1';\n $two->id = 1;\n+ $two->exists = 1;\n $two->someAttribute = '2';\n $three->id = 1;\n+ $three->exists = 1;\n $three->someAttribute = '3';\n $four->id = 2;\n+ $four->exists = 1;\n $four->someAttribute = '4';\n \n $duplicates = Collection::make([$one, $two, $three, $four])->duplicates()->all();", "filename": "tests/Database/DatabaseEloquentCollectionTest.php", "status": "modified" }, { "diff": "@@ -1513,7 +1513,9 @@ public function testReplicatingEventIsFiredWhenReplicatingModel()\n \n $model->setEventDispatcher($events = m::mock(Dispatcher::class));\n $events->shouldReceive('dispatch')->once()->with('eloquent.replicating: '.get_class($model), m::on(function ($m) use ($model) {\n- return $model->is($m);\n+ return $model->getKey() === $m->getKey()\n+ && $model->getTable() === $m->getTable()\n+ && $model->getConnectionName() === $m->getConnectionName();\n }));\n \n $model->replicate();\n@@ -1821,31 +1823,55 @@ public function testScopesMethod()\n public function testIsWithNull()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = null;\n \n $this->assertFalse($firstInstance->is($secondInstance));\n }\n \n+ public function testIsWithUnpersistedModelInstance()\n+ {\n+ $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n+ $secondInstance = new EloquentModelStub;\n+ $result = $firstInstance->is($secondInstance);\n+ $this->assertFalse($result);\n+ }\n+\n+ public function testIsWithUnpersistedModelInstances()\n+ {\n+ $firstInstance = new EloquentModelStub;\n+ $secondInstance = new EloquentModelStub;\n+ $result = $firstInstance->is($secondInstance);\n+ $this->assertFalse($result);\n+ }\n+\n public function testIsWithTheSameModelInstance()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 1]);\n+ $secondInstance->exists = true;\n $result = $firstInstance->is($secondInstance);\n $this->assertTrue($result);\n }\n \n public function testIsWithAnotherModelInstance()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 2]);\n+ $secondInstance->exists = true;\n $result = $firstInstance->is($secondInstance);\n $this->assertFalse($result);\n }\n \n public function testIsWithAnotherTable()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 1]);\n+ $secondInstance->exists = true;\n $secondInstance->setTable('foo');\n $result = $firstInstance->is($secondInstance);\n $this->assertFalse($result);\n@@ -1854,7 +1880,9 @@ public function testIsWithAnotherTable()\n public function testIsWithAnotherConnection()\n {\n $firstInstance = new EloquentModelStub(['id' => 1]);\n+ $firstInstance->exists = true;\n $secondInstance = new EloquentModelStub(['id' => 1]);\n+ $secondInstance->exists = true;\n $secondInstance->setConnection('foo');\n $result = $firstInstance->is($secondInstance);\n $this->assertFalse($result);", "filename": "tests/Database/DatabaseEloquentModelTest.php", "status": "modified" }, { "diff": "@@ -553,6 +553,7 @@ public function test_to_json_may_be_left_off_of_single_resource()\n public function test_original_on_response_is_model_when_single_resource()\n {\n $createdPost = new Post(['id' => 5, 'title' => 'Test Title']);\n+ $createdPost->exists = true;\n Route::get('/', function () use ($createdPost) {\n return new ReallyEmptyPostResource($createdPost);\n });", "filename": "tests/Integration/Http/ResourceTest.php", "status": "modified" } ] }