I am trying to update some users info. Here is my code :
public function update(Request $request, $id)
{
$user = Auth::user();
$user_id = Auth::user()->id;
$arrRequest = $request->all();
$contact = Contact::findOrFail($id)->where('user_id', $user_id);
$validator = Validator::make($arrRequest, Contact::$rules);
$content = null;
if ($validator->fails()) {
$status = 400;
$content = $validator->errors();
} else {
$contact->update($arrRequest)->save();
$status = 200;
}
return response($content, $status);
}
The main problem is that the request is applied to all rows in the table though I'm specifying the $id of the row for the request to be applied to. I'm struggling to see where is my mistake.
The second problem (that just popped up) is that when I perform the request I'm now getting a message that says : Call to a member function save() on integer
. But it was working just fine earlier (except it was updating all rows..) ! And Im retrieving an object ($contact) and not just an integer...
Thanks !
答案 0 :(得分:1)
您正在使用findOrFail()
方法,该方法会返回模型或集合。
之后,您实际上通过在$contact
结果上附加where()
方法将findOrFail()
转换为Builder对象。 findOrFail()
要求$ id或$ id数组,并且将返回Model或Collection,而不是Builder。
如果您只想确保用户拥有所请求的ID,您可以在获取对象后检查,或使用findOrFail()
以外的其他内容。
$contact = Contact::findOrFail($id);
if ($contact->user_id != $user->id) {
abort(403);
}
或
$contact = Contact::where('id', $id)
->where('user_id', $user->id)
->first();
if (! $contact) {
abort(404);
}
虽然我不推荐最后一个,但$id
应该足以获取你想要的项目。
第二个错误是在save()
之后调用update()
引起的,update()
将返回一个布尔值。
答案 1 :(得分:0)
我终于设法让它发挥作用了......虽然发生了一些奇怪的事情。 这是我的解决方案:
public function update(Request $request, $id)
{
$user = Auth::user();
$user_id = Auth::user()->id;
$arrRequest = $request->all();
$contact = Contact::where('user_id', $user_id)->find($id);
$validator = Validator::make($arrRequest, Contact::$rules);
$content = null;
if ($validator->fails()) {
$status = 400;
$content = $validator->errors();
} else {
$contact->update($arrRequest);
$contact->save();
$status = 201;
}
return response($content, $status);
}
感谢Robert,我可以理解它的一些部分。我想如果我首先使用update()然后save()(不是连续),我的save方法是应用于对象而不是返回的布尔值?这就是为什么它有效?还在学习啊!