欢迎各位兄弟 发布技术文章
这里的技术是共享的
下面是自己亲自做的
$customer = Customer::firstOrCreate(['customer_tel'=>$customer_tel]);customer_tel必须是属于$fillable数组的
$customer->update($request->all());
先是 firstOrCreate 不要使用 firstOrNew ,表示己经创建了一个存在数据库里面的对象了,
然后 再 update (假如 firstOrNew ,很可能是新建一个并未存在于数据库的对象,就不能使用update了)
不能先使用 firstOrNew 再使用 updateOrCreate($request->all());因为updateOrCreate的第一个参数数组是不检查$fillable数组的
会把里面的全面填进去,所以 POST过来的 _token method 这些 参数值也会存进数据库,显然会出问题,
关于 updateOrCreate 可以看看 /node-admin/12931
下面是updateOrCreate的用法
// 如果没有匹配的模型则创建之 肯定可以 用法1)
$flight = App\Flight::updateOrCreate( ['departure' => 'Oakland', 'destination' => 'San Diego'], ['price' => 99] );
应该可以 用法2) 传两个数组,第二个数组是检查$fillable的
$profile = Profile::updateOrCreate( ['id' => $id], $request->all() );
来自 https://laracasts.com/discuss/channels/eloquent/how-to-use-firstornew?page=1
How to use firstOrNew?
Hi,
Would you tell me whether I could use findOrNew or firstOrNew to replace the following cumbersome code?
public function store(Request $request) { $test = Test::where('test_name', $request->test_name) ->first(); if ($test == null) { $test = new Test($request->all()); $test->save(); } else { Test::where('id', $test->id)->update($request->all()); } }