AJAX向controller发送数据,如何更新正确的id?

时间:2022-12-01 16:03:31

I am using ajax to post data to the controller and I need to update the record based on the id I pass through. How would I go about this with Laravel Eloquent? Here is the controller...I know the data is being passed to the controller correctly just don't know how to update based on the id I send. Thank you for your help.

我正在使用ajax向控制器发布数据,我需要基于我传递的id更新记录。我该如何用拉拉维尔的口才来谈这件事呢?这是控制器……我知道数据被正确地传递给控制器,只是不知道如何根据我发送的id进行更新。谢谢你的帮助。

public function home(Request $request) {

$updateCus = New Customer($request->all());
$updateCus->update()->where('id', $request['id']);

}

3 个解决方案

#1


3  

Correct syntax is:

正确的语法是:

Customer::where('id', $request->id)->update([
    'name' => $request->name,
    'country' => $request->country,
]);

Or, if you want to update many columns:

或者,如果你想更新很多列:

Customer::where('id', $request->id)->update($request->all());

#2


0  

If you want to update a record, you must fetch it from the database first. Instead, you're creating a new Customer. You should do something like this:

如果要更新一条记录,必须首先从数据库中获取它。相反,您正在创建一个新客户。你应该这样做:

public function home(Request $request) {
    $customer = Customer::where('id', $request['id'])->first();
    if ($customer) {
        $customer->field1 = $request['field1'];
        //... update the fields you want to
        $customer->save();
    } else {
        //user not found...
    }
}

#3


0  

public function home(Request $request){
$id=$request->id;
$update=\DB:"table('tablename')->update(['columnname'=>$columname])->where('id',$id);
}

#1


3  

Correct syntax is:

正确的语法是:

Customer::where('id', $request->id)->update([
    'name' => $request->name,
    'country' => $request->country,
]);

Or, if you want to update many columns:

或者,如果你想更新很多列:

Customer::where('id', $request->id)->update($request->all());

#2


0  

If you want to update a record, you must fetch it from the database first. Instead, you're creating a new Customer. You should do something like this:

如果要更新一条记录,必须首先从数据库中获取它。相反,您正在创建一个新客户。你应该这样做:

public function home(Request $request) {
    $customer = Customer::where('id', $request['id'])->first();
    if ($customer) {
        $customer->field1 = $request['field1'];
        //... update the fields you want to
        $customer->save();
    } else {
        //user not found...
    }
}

#3


0  

public function home(Request $request){
$id=$request->id;
$update=\DB:"table('tablename')->update(['columnname'=>$columname])->where('id',$id);
}