Ошибка php artisan migrate

Я пробую изучать Laravel. Начал новый проект по туториалу https://laracasts.com/series/laravel-from-scratch-… .

При вводе комманды :

php artisan migrate

я получаю ошибку:

IlluminateDatabaseQueryException  : could not find driver (SQL: select * from information_schema.tables where table_schema = blog and table_name = migrations)

  at /home/morilon/php_proj/blog/vendor/laravel/framework/src/Illuminate/Database/Connection.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::("could not find driver")
      /home/morilon/php_proj/blog/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68

  2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=blog", "root", "", [])
      /home/morilon/php_proj/blog/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68

  Please use the argument -v to see more details.

Что значит : could not find driver (SQL: select * from information_schema.tables where table_schema = blog and table_name = migrations) ?

После установки я удалил и установил заново MySQL, просто пароль забыл.
При переустановке использовал такие комманды:

pkg —get-selections | grep mysql
sudo apt-get remove —purge [everything that came up]
sudo apt-get autoremove && sudo apt-get autoclean
sudo apt-get install mysql-server
sudo apt install php-mysql

Что то устанавливал, не знаю точно что помогло. Наверно

sudo apt-get install php-pear php7.2-curl php7.2-dev php7.2-gd php7.2-mbstring php7.2-zip php7.2-mysql php7.2-xml

Теперь показывает

IlluminateDatabaseQueryException  : SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from information_schema.tables where table_schema = blog and table_name = migrations)

I am trying to install Laravel. I have installed Xampp, but when I try to setup my database using php artisan migrateI get the error:

[IlluminateDatabaseQueryException] could not find driver (SQL: select * from information_schema.tables where table_schema = homestead
and table_name = migrations) [PDOException] could not find
driver

config/database.php file has the relevant connections:

'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => env('DB_DATABASE', database_path('database.sqlite')),
        'prefix' => '',
    ],

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'pgsql' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'public',
        'sslmode' => 'prefer',
    ],

    'sqlsrv' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '1433'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'prefix' => '',
    ],

],

Any ideas?

this is my config/database.php
‘mysql’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘127.0.0.1’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE’, ‘forge’),
‘username’ => env(‘DB_USERNAME’, ‘forge’),
‘password’ => env(‘DB_PASSWORD’, »),
‘unix_socket’ => env(‘DB_SOCKET’, »),
‘charset’ => ‘utf8mb4’,
‘collation’ => ‘utf8mb4_unicode_ci’,
‘prefix’ => »,
‘strict’ => true,
‘engine’ => null,
],

and this is my .env file

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_5
DB_USERNAME=root
DB_PASSWORD=root

Странная ошибка, возникающая при выполнении первой миграции в Laravel 8, тянется ещё со времён Laravel 5.4. И её почему-то до сих пор не устранили. Связано ли это с тем, что программисты, работающие с Laravel, предпочитают исключительно MySQL и люто ненавидят MariaDB, или ещё по какой причине, но ошибка случается и поправить её на самом деле, не составляет труда.

Ошибка выглядит следующим образом. При выполнении команды:

php artisan migrate

Миграции начинают обрабатываться:

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table

Но тут же вылетает сообщение об ошибке:

   IlluminateDatabaseQueryException

  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667▕         // If an exception occurs when attempting to run a query, we'll format the error
    668▕         // message to include the bindings with SQL, which will make this exception a
    669▕         // lot more helpful to the developer instead of just the database's errors.
    670▕         catch (Exception $e) {
  ➜ 671▕             throw new QueryException(
    672▕                 $query, $this->prepareBindings($bindings), $e
    673▕             );
    674▕         }
    675▕

      +9 vendor frames
  10  database/migrations/2014_10_12_000000_create_users_table.php:26
      IlluminateSupportFacadesFacade::__callStatic("create")

      +21 vendor frames
  32  artisan:37
      IlluminateFoundationConsoleKernel::handle(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput))

Решение проблемы с ошибкой php artisan migrate — SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes при применении миграции в Laravel

Для устранения этой ошибки нужно внести изменения в метод boot класса AppServiceProvider. Для этого открываем файл, находящийся по адресу:

/папка_проекта/app/Providers/AppServiceProvider.php

Изначально он имеет вид:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

В него нужно вписать 2 строчки (использование библиотеки фасадов use IlluminateSupportFacadesSchema; и модификацию метода bootSchema::defaultStringLength(191);) таким вот образом:

use IlluminateSupportFacadesSchema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Таким образом модифицированный файл с классом AppServiceProvider будет иметь вид (добавляется 6-я и 26-я строки):

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesSchema;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

После сохранения этих изменений, команда php artisan migrate работает без ошибок, все миграции применяются и проект на фреймворке Laravel оживает. =)

Важно(!)
Перед тем, как накатывать повторно миграции, удалите созданные ранее таблицы из базы данных.
Иначе будет новая ошибка! ;)

По материалам:
laravel-news.com

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Выберите, то, чем пользуетесь чаще всего:

Laravel error illuminate database queryexception can be taken care of with this handy solution by Bobcares.

At Bobcares, we offer solutions for every query, big and small, as a part of our Server Management Service.

Let’s take a look at how our Support Team recently helped a customer with the illuminate database queryexception error.

What is Laravel error illuminate database queryexception

Some of our customers have been facing trouble with this error. It develops while executing PHP artisan migration command on CMD during Laravel development on Windows 10. Interestingly, this is a typical Windows problem.

For instance:

$ php artisan migrate:install
could not find driver (SQL: create table `migrations` (`id` int unsigned not null auto_increment primary key, `migration` varchar(255) not null, `batch` int not null) default character set utf8mb4 collate ‘utf8mb4_unicode_ci’)

1 …LaravelblogvendorlaravelframeworksrcIlluminateDatabaseConnectorsConnector.php:70
PDOException::(“could not find driver”)

2 …LaravelblogvendorlaravelframeworksrcIlluminateDatabaseConnectorsConnector.php:70
PDO::__construct()

The following image illustrates how the error presents itself:

Laravel error illuminate database queryexception

Laravel is a popular web application framework. It offers expressive and elegant syntax that makes tasks like routing, authentication, caching and sessions a lot easier. Moreover, it  offers various features and tool that makes web projects a lot easier.

Migration is a feature in Laravel that allows us to easily share the database schema. This comes in handy when we are working with multiple tables and columns. In other words, it helps us avoid having to create the tables manually repeatedly. For instance, when we use PHP artisan migrate, we can get a new table in the database in an instant.

How to resolve Laravel error illuminate database queryexception

According to our Support Techs, we can resolve the error by enabling the php_pdo_mysql.dll Extention into the php.ini file. We can do this with the help of the following steps:

  1. First, we will update php.ini present in the PHP folder. We do this by opening the php.ini file in the PHP folder and adding the following line:
    extension=php_pdo_mysql.dll
  2. After that, we will update php.ini in the xampp folder by opening the file and adding the following extension:
    extension=php_pdo_mysql.dll
  3. Next, we have to restart XAMPP by opening the control panel and restarting Apache and MySQL as seen below:

    Laravel error illuminate database queryexception

Once we are done with the above procedure, we will be able to re-run PHP artisan migrate without running into any further trouble.

[Seeking a solution to another query? We are just a click away.]

Conclusion

In conclusion, the skilled Support Engineers at Bobcares demonstrated how to deal with illuminate database queryexception error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

Понравилась статья? Поделить с друзьями:
  • Ошибка photoviewer dll
  • Ошибка photoshop первичный диск переполнен
  • Ошибка photoshop недостаточно памяти
  • Ошибка photoshop not a png file
  • Ошибка phl delta vfd b