Laravel 模型使用观察者(Observer) 作者: Chuwen 时间: 2021-10-20 分类: Laravel,PHP 评论 参考:https://segmentfault.com/a/1190000012292973
PHP 对象动态传参数(反射) / Laravel Cast 的相关使用用例 作者: Chuwen 时间: 2021-10-20 分类: Laravel,PHP 评论 ## 序言 主要在用到 Laravel Cast,所以有了这个想法,暂时记录下用法,后面再慢慢解释(如果有空 哈哈哈哈) ## 代码 `MailSendLogComment.php` ```php $this->test ]; } } ``` `MailSendLogCommentCast.php`: ```php newInstanceArgs(json_decode($value, true)); } return $value; } /** * Prepare the given value for storage. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @param mixed $value * @param array $attributes * * @return array */ public function set($model, $key, $value, array $attributes): array { if ($key === 'comments') { // 如果给的值不是 MailSendLogComment 对象就报错 if ($value instanceof MailSendLogComment) { throw new InvalidArgumentException('The given value is not an ' . MailSendLogComment::class . ' instance.'); } $attributes['comments'] = json_encode($value->toArray(), JSON_UNESCAPED_UNICODE); } return $attributes; } } ``` `MailSendLog.php` ```php MailSendLogCommentCast::class, 'type' => MailSendLogTypeEnum::class// 限定必须使用此枚举类型 ]; } ``` ## 用法 ```php // 查询数据 use App\Models\MailSendLog; dump(MailSendLog::first()->comments);// 返回的是 \App\Casts\Manage\MailSendLogComment 对象 dump(MailSendLog::first()->comments->test);// 返回的是 \App\Casts\Manage\MailSendLogComment 对象 test 属性的值 // 新增数据 $M = new MailSendLog(); $M->title = '邮件标题'; $M->content = '邮件内容'; $M->comments = new MailSendLogComment('邮件备注'); //必须传入这个类型,否则将会报错 $M->exception = '错误日志'; $M->save();// 保存 ```
做个 Larvel Model 插入或更新小笔记,因为犯错比较多的 作者: Chuwen 时间: 2021-09-03 分类: Laravel,PHP 1 条评论 ### Laravel 模型 新建数据 或者 更新数据 > 可能我这个方法不够优雅,欢迎批评指正 ```php first(); // 如果为空 if (is_null($content)) { // 创建模型实例 $content = new Content; $content->uid = $uid; } $content->text = '测试测试'; // 新建数据 或者 更新数据 $content->save(); } } ``` 再留个中文文档的相关链接:https://learnku.com/docs/laravel/8.x/eloquent/9406#c7d398
Laravel 验证器(Validation)验证数组及元素 作者: Chuwen 时间: 2021-08-30 分类: Laravel,PHP 评论 ### 示例 ```php $rules = [ 'country_code_list[]' => ['required_without:courier_code', 'array'],//这个字段必须为数组 'country_code_list[].*' => ['string', 'distinct', 'size:2'],//数组里的元素必须是字符串,并且要是唯一的,并且长度要为 2 ]; $validated = Validator::make($request->all(), $rules); // 打印验证错误信息 dd($validated->errors()); ``` ### 模拟请求数据 > POST 请求 BODY ```json { "country_code_list[]": [ "CN", "JP" ] } ```
Laravel 迁移文件 新增、修改、删除 字段命名规则 作者: Chuwen 时间: 2021-08-27 分类: PHP 2 条评论 ## 个人规范仅供参考 ### 新增迁移文件 > 推荐使用创建模型命令生成迁移文件 `php artisan make:model 模型名 -m` ```shell php artisan make:model User -m # 这样就会生成 create_users_table # 会自动生成有复数的表名字 ``` ### 添加字段 > 规则:`add_字段名_to_表名` ```shell php artisan make:migration add_votes_to_users_table --table=users ``` ### 修改字段 > 规则:`change_字段名_to_表名` ```shell php artisan make:migration change_votes_to_users_table --table=users ``` ### 删除字段 > 规则:`remove_字段名_to_表名` ```shell php artisan make:migration remove_votes_to_users_table --table=users ```