我创建了一个Lumen代码来存储包含5张图像的数据(采用手动图像方法),并且该API工作正常。我不确定是否要更新查询,我可以更新所有数据部分,但不了解图像。
我尝试更新图像名称,但是相同的问题是如何替换图像
public function store(Request $request)
{
$post = new Post;
$post->setConnection('mysql1');
$user= User::where('token', $request->token)->first();
if ($user) {
$a = Auth::user()->id;
$post = Auth::user()->posts()->create([
'post_id' => rand(),
'title' => $request->title,
'cooked_time' => $request->cooked_time,
'user_id' => Auth::id(),
]);
if (!function_exists('public_path')) {
function public_path($path = null) {
return rtrim(app()->basePath('public/' . $path) , '/');
}
}
$images = new PostImage;
$destination_path = public_path('/images');
if ($request->hasFile('image1')) {
$image1 = $request->file('image1');
$image_size1 = $image1->getClientSize();
$image_ext1 = $image1->getClientOriginalExtension();
$new_image_name1 = rand(123456, 99999999) . "." . $image_ext1;
$image1->move($destination_path, $new_image_name1);
$images->image_name1 = $new_image_name1;
}
if ($request->hasFile('image2')) {
$image2 = $request->file('image2');
$image_size2 = $image2->getClientSize();
$image_ext2 = $image2->getClientOriginalExtension();
$new_image_name2 = rand(123456, 99999999) . "." . $image_ext2;
$image2->move($destination_path, $new_image_name2);
$images->image_name2 = $new_image_name2;
}
if ($request->hasFile('image3')) {
$image3 = $request->file('image3');
$image_size3 = $image3->getClientSize();
$image_ext3 = $image3->getClientOriginalExtension();
$new_image_name3 = rand(123456, 99999999) . "." . $image_ext3;
$image3->move($destination_path, $new_image_name3);
$images->image_name3 = $new_image_name3;
}
if ($request->hasFile('image4')) {
$image4 = $request->file('image4');
$image_size4 = $image4->getClientSize();
$image_ext4 = $image4->getClientOriginalExtension();
$new_image_name4 = rand(123456, 99999999) . "." . $image_ext4;
$image4->move($destination_path, $new_image_name4);
$images->image_name4 = $new_image_name4;
}
if ($request->hasFile('image5')) {
$image5 = $request->file('image5');
$image_size5 = $image5->getClientSize();
$image_ext5 = $image5->getClientOriginalExtension();
$new_image_name5 = rand(123456, 99999999) . "." . $image_ext5;
$image5->move($destination_path, $new_image_name5);
$images->image_name5 = $new_image_name5;
}
$images->post_id = $post->post_id;
$images->save();
return response()->json(['message' => 'success', 'user' => $user['name'], 'post' => $post, 'images' => $images,], 200);
}
}
如果我要更新请求,我希望替换存储的图像,这就是我更新代码的方式
public function update(Request $request, $post_id)
{
$posts = Post::findorFail($post_id);
// dd($posts);
if (Auth::user()->id !== $posts->user_id) {
return response()->json(['status'=> 'error', 'message' => 'unauthorized'], 401);
}
$post1=$request->all();
$posts->fill($post1)->save();
return response()->json(['status' => 'success', 'updated_post' => $posts,], 200);
}
如何更新和替换文件夹中的图片