laravel 保存操作如何过滤一些不必要的字段?

  1. laravel eloquent创建数据时可以使用$fillable属性和$guarded属性限制,但是修改的时候不起作用,网上搜索有人用array_only函数解决,请问还有什么别的方法么?
慕斯709654
浏览 1394回答 1
1回答

慕后森

你指的不起作用,我猜你应该不是用的 Eloquent::save() 去创建的。我建议你在 Request 层就做用户提交数据的验证,和处理,这样Controller 里会更加清晰! <?php namespace App\Http\Requests\Organization\Department; use Illuminate\Http\JsonResponse; use Illuminate\Foundation\Http\FormRequest; class CreateDepartmentRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { if (Auth::user()->hasPermission('create_department')) { return true; } } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'parent_id' => 'required|numeric', 'leader' => 'numeric', 'buttman' => 'numeric', 'grade' => 'required' ]; } /** * Error message * @return array */ public function messages() { return [ 'name.required' => '部门名称为必填项', 'parent_id.required' => '上级部门为必填项', 'parent_id.numeric' => '上级部门 ID 必须为数字', 'leader.numeric' => '部门领导 ID 必须为数字', 'buttman.numeric' => '部门对接人 ID 必须为数字', 'grade.required' => '部门职系为必填' ]; } /** * Error Response * @param array $errors * @return JsonResponse */ public function response(array $errors) { return new JsonResponse([ 'status' => 'error', 'data' => $errors ], 422); } } //控制器里再获取指定的字段,到这里数据基本上就没问题了! $input = $request->intersect(['arg1', 'arg2']);
打开App,查看更多内容
随时随地看视频慕课网APP