部署Laravel项目到服务器时出现Class 'PDO' not found错误,如何解决?
Hey there! I’ve run into this exact issue multiple times when deploying Laravel apps, so let’s walk through how to fix it step by step—changing PHP versions alone won’t cut it if the required PDO extension isn’t set up for that version.
Step 1: Confirm Which PHP Version Your Web Server Is Using
First, double-check that the PHP version your web server (Apache/Nginx) relies on is the one you think you switched to. A super common gotcha is having different versions for the CLI and web environment:
- Create a temporary file named
phpinfo.phpin yourpublic_htmldirectory with this content:<?php phpinfo(); ?> - Access it via your browser (e.g.,
yourdomain.com/phpinfo.php) and note the PHP Version listed at the top—this is the version you need to configure. - You can check the CLI version with
php -vin your terminal, but don’t assume it matches the web server’s version!
Step 2: Install the PDO Extension for Your Target PHP Version
PDO is a PHP extension that needs to be installed separately for each PHP version. The exact command depends on your OS and database (we’ll use MySQL as the default—adjust if you’re using PostgreSQL/SQLite):
For Ubuntu/Debian Systems
If your PHP version is 8.1, run:
sudo apt update && sudo apt install php8.1-pdo-mysql
Replace 8.1 with your actual PHP version (e.g., 7.4, 8.2). For PostgreSQL, use php8.1-pdo-pgsql instead.
For CentOS/RHEL Systems
Using dnf (for newer versions):
sudo dnf install php81-pdo-mysql
Adjust the version number to match your PHP setup.
For Control Panels (cPanel, Plesk, BT Panel)
Navigate to the PHP extensions section for your targeted PHP version, find the pdo_mysql (or relevant database PDO extension) option, and enable it. Save changes and restart your web server.
Step 3: Enable PDO in php.ini (If Required)
Sometimes the extension is installed but not enabled. Locate your php.ini file (its path is listed in the phpinfo output under Loaded Configuration File):
- Open the file and look for a line like
;extension=pdo_mysql - Remove the leading semicolon (
;) to uncomment it, so it becomesextension=pdo_mysql - Save and close the file.
Step 4: Restart Your Web Server and PHP-FPM
After installing/enabling the extension, you must restart your services to apply changes:
- For Apache:
sudo systemctl restart apache2 - For Nginx:
sudo systemctl restart nginx - For PHP-FPM (match your version):
sudo systemctl restart php8.1-fpm
Step 5: Verify the Fix
- Delete the
phpinfo.phpfile for security. - Reload your Laravel project in the browser—this should resolve the PDO error.
- If you want to double-check, run
php -m | grep pdoin the terminal to confirm the extension is loaded (for CLI; the working site confirms the web server’s setup).
内容的提问来源于stack exchange,提问作者Hanie

