[Laravel] Daily record sharing

Article Directory

grammar

Anzhao Chinese alphabetical order

use App\Models\Users;
use DB;
$user = Users::orderBy(DB::raw('convert(`company_name` using gbk)'), 'asc')
			->get()->toArray();

0. An error occurred when updating/installing mix

There are errors when updating/installing mix.
Unfortunately, there are countless reasons why your dependencies may not be installed correctly. A common root cause is the installation of old versions of Node (node ​​-v) and npm (npm -v). The first step is to visit http://nodejs.org and update them.

Otherwise, it is usually related to the wrong lock file that needs to be deleted. Let this series of commands try to install everything from scratch

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
npm install

1. Get the current route of the page in the view template Request::path()

2. During the save() operation, I kept reporting an error: Array to string conversion. In the end, it turned out that the other fields passed were of array type and the database field type was string.

3. ajax elementUI upload file 报错 : Route [‘login’ ] xxxx ,

Program:

	<el-upload  :headers="uploadHeader" ></el-upload>
    uploadHeader: {
       Authorization: "Bearer " + window.localStorage.getItem("token")
     }

4. find_in_set(<incoming value>, <field name>);

find_in_set(str,strlist): The query field (strlist) contains the result of (str), the return result is null or record (str is located in the position of strlist), if str is not in strlist or strlist is an empty string, then 0 is returned , If any parameter is null, then return null.

For example: query user_id contains a value of 3

表数据
id   user_id
3     1,2,3,4 
4     1,2,13,4 
sql :
$query->where(function ($query) use ($uid) {
    $query->whereRaw("FIND_IN_SET($uid, user_id)>0");
});

5. How to make Laravel API always return JSON format response?

6. Get the time difference (year, month, day, hour, minute, second)

7. Ajax Validator verification

$validator = Validator::make(Request()->all() [
  'question' => 'required',
    'answer' => 'required',
    'product_type' => 'required|in:' . $productList,
    'tags' => 'array',
], [
    'question.required' => '问题 为必填项',
    'answer.required' => '解答内容 为必填项',
    'product_type.required' => '产品类型 为必选项',
]);
if ($validator->fails()) {
    return $this->ajaxFail(false, $validator->errors()->all());
}

8. Use Laravel schedule in Docker

9. The difference between getChanges and getDirty

getDirty 需要在 save 前调用
而 getChanges 在 save 后调用。
在 Laravel Tinker 中测试一下:

>>> use App\Models\Order;
>>> $order = Order::find(3);
>>> $order->notes = "带两根大葱";
=> "带两根大葱"

>>> $order->getDirty();
=> [
     "notes" => "带两根大葱",
   ]
   
>>> $order->getChanges();
=> []
>>> $order->save();
=> true

>>> $order->getDirty();
=> []
>>> $order->getChanges();
=> [
     "notes" => "带两根大葱",
     "updated_at" => "2019-01-24 12:05:40",
   ]

10. Hide the value of the $appends property

// userModel.php
protected $appends = ['is_admin'];
public function getIsAdminAttribute()
{
    
    
    return $this->attributes['admin'] == 'yes';
}

// userController.php
$user->get()->makeHidden(['is_admin']);

11. Show hidden attributes, hide display attributes

隐藏属性:
protected $hidden = ['password'];
临时暴露隐藏属性:
return $user->makeVisible('password')->toArray();
-------------------------------------------------
显示属性:
protected $visible = ['first_name', 'last_name'];
临时隐藏显示属性
return $user->makeHidden('first_name')->toArray();

12. laravel appends attribute sorting (sortBy('') / sortByDesc(''))

$list = User::get()->sortBy('age');  升序
$list = User::get()->sortByDesc('age');  降序

13. SASS error: Incompatible units: ‘px’ and ‘rem’

In the resources / sass / _variables.scss in
view $font-size-baseof unit value,
reasons:
Since the unit bootstrap parameters defined inconsistencies introduced

14. php artisan parameter meaning

Reference link: https://learnku.com/docs/laravel-cheatsheet/5.8/artisan/4430

Database aspect

1. Slow data loading may exist

1) The domain name is changed to the ip address: https://codeday.me/bug/20181030/324662.html
2) The database configuration encoding format problem: https://lukem.top/2018/02/01/laravel-eloquent-is -slow/

The same encoding format causes the index to not work normally when executing the same query through Laravel. Solution, modify the collation in the configuration file to null

3) Through the OneApm tool , it is detected that Pdo connects to the database very slowly.
Through the OneApm tool, it is detected that Pdo is very slow to connect to the database
4) The delay problem between server operators

surroundings

1. When the server is deployed

php artisan cache:clear
php artisan view:clear
Optimize routing loading: php artisan route:clear
Optimize configuration loading: php artisan config:clear
Optimize automatic loading:composer install --optimize-autoloader

For convenience, you can write a script in the project root directory optimize.sh

#!/usr/bin/env bash
php artisan clear-compiled
php artisan cache:clear
php artisan route:cache
php artisan config:cache
php artisan optimize --force
composer dump-autoload --optimize
chmod -R 777 storage
chmod -R 777 bootstrap/cache

2. PHP extensions required by Laravel

OpenSSL PHP
PHP PDO 扩展
PHP Mbstring 扩展
PHP Tokenizer 扩展
PHP XML 扩展
PHP Ctype 扩展
PHP JSON 扩展

2. 解决: Please provide a valid cache path.

Creating a framework in storage is
mkdir storage/framework/{cache, sessions, views}
roughly like this:
Write picture description here

3. ERROR: file_put_content(…/storage/framework/sessions/xxxxxxxxx): failed to open stream: Permission denied {xxxxxx…}

Solution:
a special storagefolder permissions required to file with him and his son to rise to 775,
sudo chmod -R 775 storage/

4. Multi-environment ENV configuration

Background: If there are multiple .envfiles in the project , for example,

  • .env
  • .env.local
  • env.production

Solution: (with .env.localan example)

  • Configure Apache server SetEnv APP_ENV local;
  • Configure Nginx server fastcgi_param APP_ENV local;; // Note the semicolon at the end
  • Corresponding to the Laravel project .env.local, where APP_ENV = local;
  • laravel will pass env('APP_ENV')the environmental variables APP_ENVto determine the current specific environment, if the environment variable APP_ENVis local, it will be automatically loaded laravel .env.localfile.

The last execution php artisan config:cache && rm bootstrap/cache/* -rfClear Cache

5. JWT get user information

  • Need to be added to the ajax request header Authorization: Bearer <token>(note the space after Bearer)
  • Need to add to the called interface Request $request, and then auth('api')->user()get user information

6. Access error 404 Not Found

Whether Apache is enabled with the rewrite module sudo a2enmod rewrite

7. Turn on the reverse proxy module

Whether Apache has the proxy module enabled sudo a2enmod proxy proxy_balancer proxy_http

8. Custom error page

https://www.golaravel.com/post/laravel-5-0-custom-error-pages/

9. Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

[xx@localhost api]$ composer dump-autoload
Generating optimized autoload files
Class Illuminate\Foundation\ComposerScripts is not autoloadable, can not call post-autoload-dump script
> @php artisan package:discover

Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Application' not found in /data/www/default/dms/api/bootstrap/app.php:14
Stack trace:
#0 /data/www/default/dms/api/artisan(20): require_once()
#1 {main}
  thrown in /data/www/default/dms/api/bootstrap/app.php on line 14
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

solution:composer install

10. Step on env, config

When executed, the php artisan config:clearresult /bootstrap/is generated in the directory config.php, and then it is found that the database reads online data, which is very embarrassing.

正常情况: 
env 方法 可以获取 .env 文件的值 
config 可以获取 config 文件夹下 指定配置的值

非正常情况: 
当我们执行了 php artisan config:cache 之后 
在bootstrap/cache 文件夹下 会生成一个 config.php 文件 
这个文件包含了 config 文件夹下的所有文件内容,并以文件名作为键值 
同时把 .env 文件 根据特殊的解析方式,解析到 config.php

最终结果: 
env 无法获取到 .env 文件的值 
config 方法 只能获取到 bootstrap/cache/config.php 文件里面的值
--------------------- 
作者:断水流灬 
来源:CSDN 
原文:https://blog.csdn.net/duanshuiliu2017/article/details/79879463 
版权声明:本文为博主原创文章,转载请附上博文链接!

11. phpsessionclean.service: Failed to reset devices.list: Operation not permitted

The environment where the error is located
System: Debian 4.9.88
Environment: Apache2 PHP 7.1
Framework: Laravel 5.7
Reference:
https://github.com/turnkeylinux/tracker/issues/1114

12. vendor does not exist and could not be created

chmod 777 -R www

13. The MAC is invalid. {“userId”:2,“exception”:"[object] (Illuminate\Contracts\Encryption\DecryptException(code: 0): The MAC is invalid. at /v ar/www/html/web/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:199)

After the blogger changed the website domain name from A to B, he reported the error The MAC is invalid. Therefore, the second method adopted is to change APP_URL

解决方式:
第一种:执行php artisan key:generate 生成新的 APP_KEY
第二种:查看APP_URL 是否与访问地址一致
第三种:清除浏览器缓存

14. Generating optimized autoload files In PackageManifest.php line 122:undefined index: name

Insert picture description here

Reference: https://github.com/laravel/framework/commit/65a555105f7812e87888245c8123cad027bf88df

Guess you like

Origin blog.csdn.net/qq_22227087/article/details/82527526