【 laravel 】踩坑

文章目录

语法

1. 在视图模板中获取页面当前路由 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 连接数据库很慢
通过 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/cache

2. 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,
sudo chmod -R 775 storage/

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_ENVlocal,那么 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: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

解决方案: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 是否与访问地址一致
第三种:清除浏览器缓存
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章