因此,我有一个{strong>原始应用程序,用于cliets
。我已经使用Laravel做到了,现在我想在 ApiController 中创建组件,仅使其与 Postman 一起使用。
当我使用POST时,错误:Creating default object from empty value
(在$ client-> clt_name处)
当我使用GET时,它只会在message
中显示验证错误
这是API
public function clients(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'regex:/^[^{}<>]+$/u|max:255|required',
'adress' => 'regex:/[A-Za-z0-9\-\\,.]+/'
]);
if($validator->fails()){
$message = "Please fill in the right information";
return $this->sendError('Validation Error.' . $message);
}
$client_id = $request->clt_id;
$client->clt_name = $request->name;
$client->clt_adres = $request->adress;
$client->save();
$client = client::where('clt_id', $client_id)->first();
if($client){
if(!is_null($client)){
return $this->sendError("404", 'client not found');
}
}
else{
//new client
$client = new client;
}
}
和删除功能:
public function delete_client(Request $request){
$client = client::find($id);
$client->delete();
}
我对制作API还是很陌生,因此,我们将不胜感激。
答案 0 :(得分:2)
我希望这就是您要寻找的
public function clients(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'regex:/^[^{}<>]+$/u|max:255|required',
'adress' => 'regex:/[A-Za-z0-9\-\\,.]+/'
]);
if($validator->fails()){
$message = "Please fill in the right information";
return $this->sendError('Validation Error.' . $message);
}
$client_id = $request->clt_id;
$clt_name = $request->name;
$clt_adres = $request->adress;
return client::updateOrCreate(
['clt_id' => $client_id],
['clt_name' => $clt_name, 'clt_adres' => $clt_adres]
);
}
如果没有clt_id,这将创建新客户端,否则将更新客户端。
答案 1 :(得分:0)
尝试这种方式
创建对象并分配值
$client= new Client; //your table name
$client->clt_name = $request->name;
$client->clt_adres = $request->adress;
$client->save();
答案 2 :(得分:0)
检查:
public function clients(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'regex:/^[^{}<>]+$/u|max:255|required',
'adress' => 'regex:/[A-Za-z0-9\-\\,.]+/'
]);
if($validator->fails()){
$message = "Please fill in the right information";
return $this->sendError('Validation Error.' . $message);
}
$client = client::where('clt_id', $request->clt_id)->first();
if($client !== null){
// update client - all fields must be fillable in client model
$client = $client->update($request->except('clt_id'));
} else{
//new client - all fields must be fillable in client model
$client = Client::create($request->all());
}
return response()->json($client);
}