【 Laravel 】日 常 整 理 记 录 分 享
文章目錄
- 語法
- 捕獲 Mail::send() 錯誤信息
- Auth::user(); 無法從構造函數__construct中獲取用戶信息
- 如何使用 curl 函數 模擬登錄 Laravel 自帶的 auth?
- beyondcode / laravel-websockets安裝問題
- 安照中文字母排序
- 0. 更新 / 安裝 mix 時候出現錯誤
- 1. 在視圖模板中獲取頁面當前路由 `Request::path()`
- 2. 在save()操作時,一直報錯: Array to string conversion,最后竟然是因為其他字段傳過來的是array類型,數據庫字段類型string
- 3. ajax elementUI upload file 報錯 : Route ['login' ] xxxx ,
- 4. find_in_set(<傳入值>,<字段名稱>);
- 5.[如何讓 Laravel API 永遠返回 JSON 格式響應?](https://segmentfault.com/a/1190000016261077)
- 6. [獲取時間差(年、月、日、時、分、秒)](https://www.php.net/manual/zh/datetime.diff.php)
- 7. ajax Validator 校驗
- 8. [在 Docker 中使用 Laravel schedule](https://learnku.com/articles/7022/using-laravel-schedule-in-docker)
- 9. getChanges 與 getDirty 的區別
- 10. 隱藏 $appends 屬性值
- 11. 顯示隱藏屬性、隱藏顯示屬性
- 12. laravel appends 屬性排序 (sortBy('') / sortByDesc(''))
- 13. SASS error: Incompatible units: 'px' and 'rem'
- 14. php artisan 參數含義
 
 
- 數據庫方面
- 1. 數據加載慢可能存在的情況
 
 
- 環境
- 1. 服務器部署的時候
- 2. Laravel 需要的PHP 擴展
- 2. 解決: Please provide a valid cache path.
- 3. ERROR: file_put_content(..../storage/framework/sessions/xxxxxxxxx): failed to open stream: Permission denied {xxxxxx.......}
- 4. 多環境 ENV 配置
- 5. JWT 獲取用戶信息
- 6. 訪問報錯404 Not Found
- 7. 開啟 反向代理 模塊
- 8. 定制錯誤頁面
- 9. Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255
- 10. 踩坑 env,config
- 11. phpsessionclean.service: Failed to reset devices.list: Operation not permitted
- 12. vendor does not exist and could not be created
- 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)
- 14. Generating optimized autoload files In PackageManifest.php line 122:undefined index: name
 
- 15. Install of `kylekatarnls/update-helper` failed
 
語法
捕獲 Mail::send() 錯誤信息
try{Mail::send('emails.configuration_test', array(), function($email)use($request){$email->to($request->test_address)->subject('Configuration Test');}); } catch(Exception $e){// Never reached }更改為:try{Mail::send('emails.configuration_test', array(), function($email)use($request){$email->to($request->test_address)->subject('Configuration Test');}); } catch(\Exception $e){ // 加上 \ // reachedreturn $e->getMessage(); }Auth::user(); 無法從構造函數__construct中獲取用戶信息
如何使用 curl 函數 模擬登錄 Laravel 自帶的 auth?
從頁面請求中,拷貝 header 中的cookie 信息
 cookie 必須和 csrf token匹配才行,csrf token 其實是存在 session 里的,session 又是依賴于 cookie 的
$header = [
 .
 .
 “Cookie”: “XSRF-TOKEN=eyJpdiI6InBmQWhTeGF6cjRXK3k0ZEdWNFNOXC93PT0iLCJ2YWx1ZSI6Ikp4am1oNHVWWmRnbFg1OUJcLzNrd3hTTWJxbXQyaG9qdnZjRVwvZ0Y3aHJ2WFV4TjdPM0k3MVFhUVl6RW55Wk9ReiIsIm1hYyI6IjE4ZWQyDMyMjJlOGJhNjNmZjY0MmU4MGE2MmE3MjJkZDg5MmM0ZGVkMjg5YWQzZjk5YmQifQ%3D%3D; laravel_session=eyJpdiI6Ik5icTRhUzZQTDl4SVhWd05tMGUxaEE9PSIsInZhbHVlIjoiQ2RQa0U1NW5yWE9aYWFIQUQ3cjc2ZTNyXC80dTG9Qb0lRcFFxYlAzNlgwZlZPdGorM0IiLCJtYWMiOiIzYjk1N2ZiYmI0MzgwMDRhMzUzNTM5OTMwNjU3M2E0OWJjYzE1YWQ4NGVjYmE2Y2IwOTZjMzcyMTNlNjBiZGYzIn0%3D”
 ];
參考:https://learnku.com/laravel/t/30521
beyondcode / laravel-websockets安裝問題
參考:https://laracasts.com/discuss/channels/laravel/beyondcodelaravel-websockets-installation-issues
Laravel 5.7上安裝它,則應使用舊版本:composer require beyondcode/laravel-websockets:1.3最新的(1.4)版本僅支持Laravel 5.8、6.x和7.x。安照中文字母排序
use App\Models\Users; use DB; $user = Users::orderBy(DB::raw('convert(`company_name` using gbk)'), 'asc')->get()->toArray();0. 更新 / 安裝 mix 時候出現錯誤
在更新 / 安裝 mix 時候出現錯誤
 不幸的是,你的依賴項可能沒有正確安裝的原因有無數個。一個常見的根本原因是安裝了老版本的 Node (node -v) 和 npm (npm -v)。第一步,訪問 http://nodejs.org 并更新它們。
否則,它通常與需要刪除的錯誤鎖文件有關。讓這一系列命令嘗試從頭開始安裝一切
rm -rf node_modules rm package-lock.json yarn.lock npm cache clear --force npm install1. 在視圖模板中獲取頁面當前路由 Request::path()
2. 在save()操作時,一直報錯: Array to string conversion,最后竟然是因為其他字段傳過來的是array類型,數據庫字段類型string
3. ajax elementUI upload file 報錯 : Route [‘login’ ] xxxx ,
方案:
<el-upload :headers="uploadHeader" ></el-upload>uploadHeader: {Authorization: "Bearer " + window.localStorage.getItem("token")}4. find_in_set(<傳入值>,<字段名稱>);
find_in_set(str,strlist) :查詢字段(strlist)中包含(str)的結果,返回結果為null或記錄(str位于strlist中的位置),如果str不在strlist中或strlist為空字符串,那么返回0,如果任意一個參數為null,那么返回null。
例如:查詢user_id含有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.如何讓 Laravel API 永遠返回 JSON 格式響應?
6. 獲取時間差(年、月、日、時、分、秒)
7. ajax Validator 校驗
$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. 在 Docker 中使用 Laravel schedule
9. getChanges 與 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. 隱藏 $appends 屬性值
// userModel.php protected $appends = ['is_admin']; public function getIsAdminAttribute() {return $this->attributes['admin'] == 'yes'; }// userController.php $user->get()->makeHidden(['is_admin']);11. 顯示隱藏屬性、隱藏顯示屬性
隱藏屬性: protected $hidden = ['password']; 臨時暴露隱藏屬性: return $user->makeVisible('password')->toArray(); ------------------------------------------------- 顯示屬性: protected $visible = ['first_name', 'last_name']; 臨時隱藏顯示屬性 return $user->makeHidden('first_name')->toArray();12. laravel appends 屬性排序 (sortBy(’’) / sortByDesc(’’))
$list = User::get()->sortBy('age'); 升序 $list = User::get()->sortByDesc('age'); 降序13. SASS error: Incompatible units: ‘px’ and ‘rem’
在 resources/sass/_variables.scss 中
 查看 $font-size-base 的單位值,
 原因:
 自定義的參數與 引入的bootstrap 中單位不一致
14. php artisan 參數含義
參考鏈接:https://learnku.com/docs/laravel-cheatsheet/5.8/artisan/4430
數據庫方面
1. 數據加載慢可能存在的情況
1)域名改為ip地址: https://codeday.me/bug/20181030/324662.html
 2)數據庫配置編碼格式問題:https://lukem.top/2018/02/01/laravel-eloquent-is-slow/
編碼格式一致導致通過 Laravel 執行同樣的查詢時,索引不能正常使用。解決方案,將配置文件中的collation修改為 null
3) 通過 OneApm工具,檢測到 Pdo 連接數據庫很慢
 
 4) 服務器運營商之間的延遲問題
環境
1. 服務器部署的時候
php artisan cache:clear
 php artisan view:clear
 優化路由加載:php artisan route:clear
 優化配置加載:php artisan config:clear
 優化自動加載: composer install --optimize-autoloader
為了方便,可以在項目根目錄寫一個腳本 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/cache2. Laravel 需要的PHP 擴展
OpenSSL PHP PHP PDO 擴展 PHP Mbstring 擴展 PHP Tokenizer 擴展 PHP XML 擴展 PHP Ctype 擴展 PHP JSON 擴展2. 解決: Please provide a valid cache path.
在 storage 里創建 framework
 mkdir storage/framework/{cache, sessions, views}
 大概就是這樣:
 
3. ERROR: file_put_content(…/storage/framework/sessions/xxxxxxxxx): failed to open stream: Permission denied {xxxxxx…}
解決方案:
 特殊的 storage文件夾 需要把他以及其子文件的權限升到 775,
4. 多環境 ENV 配置
背景: 假如在項目中有多個.env文件,例如,
- .env
- .env.local
- env.production
解決方案: (以.env.local為示例)
- 配置Apache 服務器 SetEnv APP_ENV local ;
- 配置Nginx 服務器 fastcgi_param APP_ENV local;; // 注意 末尾的分號
- Laravel 項目下 對應有 .env.local , 其中 APP_ENV = local;
- laravel 會通過 env('APP_ENV')根據環境變量 APP_ENV來判斷當前具體的環境,假如環境變量 APP_ENV 為 local,那么 laravel 將會自動加載 .env.local 文件。
最后執行 php artisan config:cache && rm bootstrap/cache/* -rf 清除緩存
5. JWT 獲取用戶信息
- 需要在ajax請求頭中加入Authorization: Bearer <token>(注意Bearer 后的空格)
- 需要在所調用接口中加入Request $request, 然后在auth('api')->user()獲取用戶信息
6. 訪問報錯404 Not Found
Apache是否啟用了重寫模塊 sudo a2enmod rewrite
7. 開啟 反向代理 模塊
Apache是否啟用了代理模塊 sudo a2enmod proxy proxy_balancer proxy_http
8. 定制錯誤頁面
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:discoverFatal 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解決方案:composer install
10. 踩坑 env,config
當執行了, php artisan config:clear 結果在/bootstrap/目錄下生成config.php, , 然后發現數據庫讀取的為線上數據, 就是很尷尬了, ,
正常情況: 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
該錯誤所在環境
 系統:Debian 4.9.88
 環境:Apache2 PHP 7.1
 框架:Laravel 5.7
 參考:
 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)
博主將網站域名由A更改B之后,報錯The MAC is invalid. 故采用的第二種方式,即更改APP_URL
解決方式: 第一種:執行php artisan key:generate 生成新的 APP_KEY 第二種:查看APP_URL 是否與訪問地址一致 第三種:清除瀏覽器緩存14. Generating optimized autoload files In PackageManifest.php line 122:undefined index: name
參考:https://github.com/laravel/framework/commit/65a555105f7812e87888245c8123cad027bf88df
15. Install of kylekatarnls/update-helper failed
composer 1.8.* 升級至 composer 1.10.11
composer self-update 1.10.11
參考:https://github.com/kylekatarnls/update-helper/issues/9#issuecomment-689592351
總結
以上是生活随笔為你收集整理的【 Laravel 】日 常 整 理 记 录 分 享的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 【Git 】命令总结记录
- 下一篇: 【MySQL】 日 常 整 理 记 录
