Reputation: 151
I want to update an image in my database using Laravel but unfortunately, the image is not updating. How can I resolve this issue?
Controller
public function updateaction(Request $request, $id)
{
$category = $request->input('select_category');
$project_name = $request->input('product_name');
$image = $request->file('select_file');
$new_name = mt_rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('projects'), $new_name);
$updaterecord = DB::table('projects')->where(['products_id' => $id])->update([
'project_name' => $project_name, 'category_id' => $category, 'image' => $image
]);
if ($updaterecord) {
return redirect('view_project');
}
return back();
}
View
<form action="{{route('project.update', $project->products_id)}}" method="POST"
enctype="multipart/form-data">
@csrf
<div class="group-form">
<select class="form-control" name="select_category" required>
<option value="">Select Category</option>
@foreach($categories as $category)
<option value="{{$category->id}}" @if($project->category_id) == $category->id) @endif>
{{$category->category_name}}</option>
@endforeach
</select>
</div>
<br>
<div class="group-form">
<input type="text" class="form-control" value="{{$project->project_name}}"
placeholder="Update Product Name" name="product_name" required>
</div>
<br>
<div class="group-form">
<input type="file" class="form-control" value="{{asset('/public/projects/'.$projects->image)}}"
name="select_file">
</div>
<br>
<div class="group-form">
<input type="submit" class=" btn btn-primary form-control" value="UPDATE" name="Update">
</div>
</form>
Route
Route::post('project_update/{id}/update', 'AdminController@updateaction')
->name('project.update');
Upvotes: 0
Views: 104
Reputation: 4813
YOUR MODEL IS NOT UPDATING THE 'image' ATTRIBUTE BECAUSE YOU ASSIGN TO IT AN OBJECT ($image
) INSTEAD OF A STRING ($new_name
).
TRY TO REPLACE $image
VARIABLE INSIDE THE UPDATE()
METHOD WITH $new_name
.
SEE :
public function updateaction(Request $request,$id)
{
$category=$request->input('select_category');
$project_name=$request->input('product_name');
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('projects'), $new_name);
$updaterecord=DB::table('projects')->where(['products_id'=> $id])
->update(['project_name'=>$project_name,'category_id'=>$category,'image'=>$new_name]);
if($updaterecord){
return redirect('view_project');
}
}
Upvotes: 1
Reputation: 81
You try to save UploadedFile object to database. I think, you need to save a string with file name, for example, $new_name instead of $image.
Upvotes: 2