Меню

Laravel ошибка при миграции

$ php artisan migrate:status
+——+————————————————+——-+
| Ran? | Migration                                      | Batch |
+——+————————————————+——-+
| N    | 2014_10_12_000000_create_users_table           |       |
| N    | 2014_10_12_100000_create_password_resets_table |       |
| N    | 2018_04_23_062130_create_categories_table      |       |
+——+————————————————+——-+

======================================
$ php artisan migrate

   IlluminateDatabaseQueryException  : SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exists (SQL: create table `users` (`id` int unsigned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `password` varchar(255) not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

  at D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:664
    660|         // If an exception occurs when attempting to run a query, we’ll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database’s errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::(«SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exists»)
      D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:458

  2   PDOStatement::execute()
      D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:458

  Please use the argument -v to see more details.

GaneMax@GANEMAX D:OSPaneldomainscatalog.loc

Имя файла миграции для категорий?
2018_04_23_062130_create_categories_table
Создавал файл миграции так
$ php artisan make:migration create_categories_table —create=categories

Пытаюсь выполнить миграцию 1 таблицы, но не дает.

Код миграции:

    <?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('login');
            $table->string('first_name');
            $table->string('second_name');
            $table->string('patronymic');
            $table->string('full_name');
            $table->string('phone');
            $table->string('email');
            $table->integer('group');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Выдает следующую ошибку:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘roles’ already exists

Ради интереса удалила все файлы миграций из папок, история повторяется. Впервые вижу такое.

задан 17 фев 2020 в 16:10

Adelineoff's user avatar

Уважаемая Аделина всё довольно просто, я уверен что Вы уже разобрались, но пожалуйста:
В ошибке указанно, что одна из таблиц которую Вы пытаетесь создать уже есть, вероятно Вы изменили код метода Schema::create() таблицы ‘role’, с таблицей user всё нормально. В этом случае либо пересоздайте все таблицы (при разработке это обычная практика) с помощью:

php artisan migrate:refresh // эта команда сбросит и перезапишет все миграции

Либо просто удалите таблицу из базы данных и запустите миграцию снова. Надеюсь, что смог помочь!)) И от меня Вам первый лайк!

ответ дан 17 фев 2020 в 17:10

Vadim Voskresensky's user avatar

Vadim VoskresenskyVadim Voskresensky

5211 золотой знак4 серебряных знака17 бронзовых знаков

1

Just went through all the steps listed on the Laravel site to install and get up and running for MacOS HighSierra. I currently have Composer, Homebrew, valet, PHP 7.2.8, MySQL version 8.0.11 and Laravel 5.6.28 installed. I can create a new project by doing the Laravel new blog command and not have any problems. Also when I go to my browser I can see current project I just created or am working on. I can run the valet list command and so I know its running/working. I also can create a migration and have it show up in my project as well by running the php artisan make:migration test_test_test.

My PATH also has ~/.composer/vendor/bin in it as well.

my .env file look like such

APP_NAME=Laravel
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog        
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1 
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp 
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

I run the php artisan migrate -vvv command and it runs and stalls/hangs up with no output. I have to ctl-c to get out of it. tried the -v /-vv as well, did the same thing.

I created a database named blog and even add a table test manually to make sure that the database was working/running.

Update

Went ahead and uninstall MySQL and reinstall it. I was able to get the php artisan migrate -v command to run and am getting this error.

now I’m getting this error.

MacBook-Pro:anything computername$ php artisan migrate -v

PDOException  : SQLSTATE[HY000] [2006] MySQL server has gone away

at /Users/computername/Sites/anything/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68
64|         if (class_exists(PDOConnection::class) && ! $this->isPersistentConnection($options)) {
65|             return new PDOConnection($dsn, $username, $password, $options);
66|         }
67| 
> 68|         return new PDO($dsn, $username, $password, $options);
69|     }
70| 
71|     /**
72|      * Determine if the connection is persistent.

Exception trace:

Created a router and view that connects to a table that I creates to see if I would be able to access the database variables and print them out. On return I got this error.

Exception message: PDO::__construct(): Unexpected server respose while doing caching_sha2 auth: 109

Just went through all the steps listed on the Laravel site to install and get up and running for MacOS HighSierra. I currently have Composer, Homebrew, valet, PHP 7.2.8, MySQL version 8.0.11 and Laravel 5.6.28 installed. I can create a new project by doing the Laravel new blog command and not have any problems. Also when I go to my browser I can see current project I just created or am working on. I can run the valet list command and so I know its running/working. I also can create a migration and have it show up in my project as well by running the php artisan make:migration test_test_test.

My PATH also has ~/.composer/vendor/bin in it as well.

my .env file look like such

APP_NAME=Laravel
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog        
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1 
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp 
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

I run the php artisan migrate -vvv command and it runs and stalls/hangs up with no output. I have to ctl-c to get out of it. tried the -v /-vv as well, did the same thing.

I created a database named blog and even add a table test manually to make sure that the database was working/running.

Update

Went ahead and uninstall MySQL and reinstall it. I was able to get the php artisan migrate -v command to run and am getting this error.

now I’m getting this error.

MacBook-Pro:anything computername$ php artisan migrate -v

PDOException  : SQLSTATE[HY000] [2006] MySQL server has gone away

at /Users/computername/Sites/anything/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68
64|         if (class_exists(PDOConnection::class) && ! $this->isPersistentConnection($options)) {
65|             return new PDOConnection($dsn, $username, $password, $options);
66|         }
67| 
> 68|         return new PDO($dsn, $username, $password, $options);
69|     }
70| 
71|     /**
72|      * Determine if the connection is persistent.

Exception trace:

Created a router and view that connects to a table that I creates to see if I would be able to access the database variables and print them out. On return I got this error.

Exception message: PDO::__construct(): Unexpected server respose while doing caching_sha2 auth: 109

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Laravel ошибка 500 после переноса
  • Laravel обработка ошибок валидации