Category Archives: PHP

[Solved] Model Error: must return a relationship instance

Model Error: must return a relationship instance

There is a method in the model as follows:

public function adjustbills()
    {
        if($this->user_combined == '1'){
            $invoiceNumberArr = ['xxx'];
            return Adjustbill::whereIn('invoice_number',$invoiceNumberArr)->where('user_id', $this->user_id);
        }else{
            return $this->hasMany(Adjustbill::class, 'invoice_number', 'invoice_number')->where('user_id', $this->user_id);
        }
    }

When the calling method is model -> When adjustbills,

  1. If it goes to the following judgment, no error will be reported
  2. If it goes to the above judgment, it will report an error must return a relationship instance, because laravel uses the following hasMany relationship by default, if not, it will report an error.

Solution:

  1. Find a way to modify the above logic to the following way of relationship
  2. Called as :model->adjustbills->get()

[Solved] error processing package libapache2-mod-php7.2

Error in installing libpciaccess:


Setting up php7.2-cli (7.2.24-0ubuntu0.18.04.11) ...
dpkg: error processing package php7.2-cli (--configure):
 installed php7.2-cli package post-installation script subprocess returned error exit status 10
No apport report written because MaxReports is reached already
                                                              Setting up python-libxml2 (2.9.4+dfsg1-6.1ubuntu1.5) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
dpkg: dependency problems prevent configuration of libapache2-mod-php7.2:
 libapache2-mod-php7.2 depends on php7.2-cli; however:
  Package php7.2-cli is not configured yet.

dpkg: error processing package libapache2-mod-php7.2 (--configure):
 dependency problems - leaving unconfigured
Setting up libsqlite0 (2.8.17-14fakesync1) ...
No apport report written because MaxReports is reached already
                                                              Setting up librpm8 (4.14.1+dfsg1-2) ...

... ...

Errors were encountered while processing:
 ufw
 nfs-common
 openssh-server
 php7.2-cli
 libapache2-mod-php7.2
E: Sub-process /usr/bin/dpkg returned an error code (1)

To view installation information:

 apt list | grep libapache2-mod-php

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

libapache2-mod-php/bionic,bionic,now 1:7.2+60ubuntu1 all [installed]
libapache2-mod-php5filter/trusty 5.5.9+dfsg-1ubuntu4 amd64
libapache2-mod-php7.2/bionic-security,bionic-updates,now 7.2.24-0ubuntu0.18.04.11 amd64 [installed]

Just remove the contents reported as errors:

apt-get remove --purge libapache2-mod-php7.2
apt-get remove --purge nfs-common
apt-get remove --purge php7.2-cli
apt-get remove --purge ufw
apt-get remove --purge openssh-server
... ...

Upgrade list:

apt-get update

Review the installed information again and confirm remove:

apt list | grep libapache2-mod-php*

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

libapache2-mod-php/bionic,bionic 1:7.2+60ubuntu1 all
libapache2-mod-php5filter/trusty 5.5.9+dfsg-1ubuntu4 amd64
libapache2-mod-php7.2/bionic-security,bionic-updates,now 7.2.24-0ubuntu0.18.04.11 amd64 [residual-config]

Reinstall, done!:

apt install libpciaccess
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package libpciaccess
[email protected]:~/wk/bak_load/win2030/buildroot/dl$ sd apt-get install libpciaccess-dev
Reading package lists... Done
Building dependency tree       
Reading state information... Done
libpciaccess-dev is already the newest version (0.14-1).
The following packages were automatically installed and are no longer required:
  keyutils libnfsidmap2 libtirpc1 ncurses-term openssh-sftp-server php7.2-common php7.2-json php7.2-opcache php7.2-readline rpcbind ssh-import-id
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 32 not upgraded.

[Solved] yii error: Setting unknown property: yii\console\Request: :cookieValidationKey

1. Command:
php yii
2. Error:
Exception ‘yii\base\UnknownPropertyException’ with message ‘Setting unknown property: yii\console\Request::cookieValidationKey’
3. Reason:
console/yii file

$config = yii\helpers\ArrayHelper::merge(
    require __DIR__ . '/config/main.php',
    require __DIR__ . '/../conf/main-local.php'
);

$application = new yii\console\Application($config);

The above program execution entry combines all configurations before actual operation, and some configuration parameters are invalid for console operation

4. Solution:
Delete these parameters before performing console operations

unset($config['components']['request']);
$application = new yii\console\Application($config);

[Solved] Artisan error: SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes

Problem Description:

php artisan migrate Error:

Illuminate\Database\QueryException 

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

Cause Analysis:
The maximum character length of utf8 encoding supported by MySql is 3 bytes, if a wide character of 4 bytes is encountered, an insertion exception will occur. The maximum Unicode character that can be encoded by three bytes UTF-8 is 0xffff, which is the basic multiliterate plane (BMP) in Unicode. Therefore, Unicode characters that are not in the Basic Multicultural Plane, including Emoji emojis (Emoji is a special Unicode encoding), cannot be stored using MySql’s utf8 character set.

This should also be one of the reasons why Laravel 5.4 switched to the 4-byte length utf8mb4 character encoding. However, it should be noted that the utf8mb4 character encoding is only supported from MySql version 5.5.3 onwards (check the version: selection version();). If the MySql version is too low, a version update is required.

Solution:
1. Upgrade MySql version to 5.5.3 or higher. Add in /app/providers/AppServiceProvider.php:

use Illuminate\Support\Facades\Schema;

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

2. Delete the table in the database and re execute php artisan migrate

Tp6 Cannot enable error [How to Solve]

tp6 open error, you need to copy the root directory of .example.env, save it as .env, then modify the header to APP_DEBUG=true, and then directory config/app.php modify ‘show_error_msg’ => fales.

If the pdo still reports an error after starting php.ini again, log out the .env file

[DATABASE]
TYPE=mysql
HOSTNAME=host.docker.internal
DATABASE=easyadmin
USERNAME=root
PASSWORD=root
HOSTPORT=3306
CHARSET=utf8
DEBUG=true
PREFIX=ea_

 

[Solved] Laravel Upload Files Verificate Error: The file failed to upload.

Cause of error

This is the verification code I wrote based on the verification component of laravel:

In most cases, it is normal, but when the front end uploads pictures, it occasionally reports the inexplicable error of the file failed to upload. You know, there is no prompt about this error in my code. After many investigations, it can be basically determined that the error is caused by the size of the picture.

First of all, the size of the uploaded file configured by PHP by default is 2m, which can be found in PHP.ini configuration file;

upload_max_filesize=2M
post_max_size=8M

Secondly, the size limit in my laravle validation is also 2M, and laravel by default internally calls the validation based on the configuration of php, so this validation I made did not take effect at all, and the error reported was also called internally by the laravel framework.

The 422 exception thrown by the system function form validation class: The file failed to upload. and by looking at the resources/lang/en/validation file we can see that the actual framework layer is calling the uploaded validation.

Solution:

After modifying the php default configuration and changing the upload image limit size, the image upload problem was successfully solved, I changed it to 20M here, you can modify it according to the actual situation of the project.

upload_max_filesize=20M
post_max_size=20M

[Solved] PHPMailer Error: SMTP ERROR: Failed to connect to server: (0)

1. Explain

After configured $mail->Username$mail->password, the error is reported as follows:

2021-09-01 12:22:37 SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Error

2. Solution

1. Ignore SSL authentication (this is my reason)

Add the following code after code: $mail = new PHPMailer();

// Instantiating the PHPMailer core class
$mail = new PHPMailer(); 

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

...

2. Set the port to bit 25, do not use SSL, 465 (other possible reasons)

Change

// Set up ssl encryption for login authentication
$mail->SMTPSecure = 'ssl';
// set the remote server port number for ssl connection to smtp server
$mail->Port = 465;

to

$mail->Port = 25;

[Solved] PHP Fatal error: Uncaught Elasticsearch\Common\Exceptions\NoNodesAvailableException: No alive nodes

The environment background is docker DNMP installation of ES + PHP

Corresponding docker compose configuration and corresponding port

Port 9200 can also be accessed normally

Code

Then 500 errors are reported, including:

 PHP Fatal error:  Uncaught Elasticsearch\Common\Exceptions\NoNodesAvailableException: No alive nodes found in your cluster in /www/localhost/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/StaticNoPingConnectionPool.php:67
Stack trace:
#0 /www/localhost/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php(87): Elasticsearch\ConnectionPool\StaticNoPingConnectionPool->nextConnection()
#1 /www/localhost/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Transport.php(105): Elasticsearch\Transport->getConnection()
#2 /www/localhost/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php(275): Elasticsearch\Transport->performRequest('POST', '/my_index/my_ty...', Array, '{"testField":"a...', Array)
#3 /www/localhost/vendor/react/promise/src/FulfilledPromise.php(28): Elasticsearch\Connections\Connection->Elasticsearch\Connections\{closure}(Array)
#4 /www/localhost/vendor/ezimuel/ringphp/src/Future/CompletedFutureValue.php(55): React\Promise\FulfilledPromise->then(Object(Clos in /www/localhost/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/StaticNoPingConnectionPool.php on line 67

The reason is that the node cannot be found. The solution is as follows: find your own IP and specify the IP

Then the execution is OK

[Solved] Error while sending STMT_PREPARE packet. PID=29294

In the error reporting scenario, the command command of tp6 + nohup of Linux is used to execute the continuous script
error reason: the connection to the database will be disconnected for a long time

Detailed error information is as follows

[think\exception\ErrorException]                    
Error while sending STMT_PREPARE packet. PID=29294  
                                                      


PHP Fatal error:  Uncaught think\exception\ErrorException: Error while sending STMT_CLOSE packet. PID=29294 in /....../vendor/topthink/think-orm/src/db/PDOConnection.php:603
Stack trace:
#0 /....../vendor/topthink/think-orm/src/db/PDOConnection.php(603): think\initializer\Error->appError(2, 'Error while sen...', '/...', 603, Array)
#1 /....../topthink/think-orm/src/db/PDOConnection.php(1576): think\db\PDOConnection->free()
#2 /....../vendor/topthink/think-orm/src/db/Connection.php(345): think\db\PDOConnection->close()
#3 [internal function]: think\db\Connection->__destruct()
#4 {main}
thrown in /....../vendor/topthink/think-orm/src/db/PDOConnection.php on line 603

Solution:

Modify the database configuration file database.php and set it to true to enable disconnect and reconnect
 // whether to disconnect and reconnect
'break_reconnect' => true,

[Solved] PHP post Datas json_decode Error: 4 JSON_ERROR_SYNTAX

Error description

In the PHP development process, when processing json strings, json_decode returns NULL, calling last_error returns 4 (JSON_ERROR_SYNTAX), but json strings can be correctly processed by other languages ​​such as python, javascript or some online json parsers.

Diagnosis

There are several situations that generally cause php json_decode errors here:

1. The json string is read from a file and the character order mark (BOM) is not removed

2. json contains invisible characters, json_decode parsing errors

3. json object value is a single-quoted string

In particular, the third error is relatively hidden, the naked eye is often easy to ignore

Solution:

The following solutions are given for the above three cases

1.BOM Issue:

Open the file in binary mode and confirm whether there is a BOM. If so, remove the BOM before parsing. The following code takes UTF-8 as an example to detect and delete BOM.

function removeBOM($data) {

if (0 === strpos(bin2hex($data), ‘efbbbf’)) {

return substr($data, 3);

}

return $data;

}

2.Invisible character

Remove invisible characters before parsing.

for ($i = 0; $i <= 31; ++$i) {

$s = str_ replace(chr($i), “”, $s);

}

3.Single quote string value

Let’s look at the following example:

<?php

$s = “{\”x\”:’abcde’}”;

$j = json_ decode($s, true);

var_ dump($j);

echo json_ last_ error() . “\n”;

PHP 5.5. 9 output

NULL

four

Generally, you only need to replace single quotation marks with double quotation marks. During specific processing, you should pay attention to that single quotation marks may also appear in other places. Whether to replace them globally needs to be analyzed according to the specific situation.