Reputation: 57
I have multiple fields in my users table in laravel but i want to delete only image from users table, Please let me know the process. Here are my usercontroller.php file..
public function userprofile(Request $request)
{
$user = DB::table('users')->where('id',Auth::user()->id)->get();
//dd($user);
$userWish = DB::table('package_wishlist')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$userComp = DB::table('package_comparison')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$bookings = DB::table('agent_bookings')
->where('cust_email',Auth::user()->email)->get();
return view('user/profile',['bookings'=>$bookings,'user'=>$user[0],'userWish'=>$userWish,'userComp'=>$userComp]);
}
public function imagedestroy($id)
{
$image = DB::table('users')->where('id', $id)->get();
$file= $image->user_image;
$filename = public_path().'/uploads/user_uploads/'.$image;
File::delete($filename);
}
And here is my profile.blade.php file..
@foreach($user as $delimage)
<a onclick="event.preventDefault();
document.getElementById('delete-image-form').submit();"
class="btn btn-default btn-sm btn-block">Delete</a>
<form id="delete-image-form" method="POST" action="{{
route('delimage.imagedestroy', $delimage->id) }}"
style="display: none;">
@method('DELETE')
@csrf
</form>
@endforeach
And my web.php file is this...
Route::get('/userprofile', 'CustomHomeController@userprofile')->name('userprofile');
Route::get('/userprofile/{id}', 'CustomHomeController@imagedestroy')->name('imagedestroy');
Upvotes: 1
Views: 508
Reputation: 6233
use first() instead of get(). get() gives you a collection which you need to iterate to get an attribute. so you just can't get image of a user like
$image = DB::table('users')->where('id', $id)->get();
$file= $image->user_image; //this won't work.
Try like
public function imagedestroy($id)
{
$image = DB::table('users')->where('id', $id)->first();
$file= $image->user_image;
$filename = public_path().'/uploads/user_uploads/'.$image;
File::delete($filename);
}
And your userprofile method should be like
public function userprofile(Request $request)
{
$user = DB::table('users')->where('id',Auth::user()->id)->first();
//dd($user);
$userWish = DB::table('package_wishlist')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$userComp = DB::table('package_comparison')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$bookings = DB::table('agent_bookings')
->where('cust_email',Auth::user()->email)->get();
return view('user/profile',['bookings'=>$bookings,'user'=>$user,'userWish'=>$userWish,'userComp'=>$userComp]);
}
So you don't need to iterate in view. just use
<a onclick="event.preventDefault();
document.getElementById('delete-image-form').submit();"
class="btn btn-default btn-sm btn-block">Delete</a>
<form id="delete-image-form" method="POST" action="{{
route('imagedestroy', $user->id) }}"
style="display: none;">
@method('DELETE')
@csrf
</form>
Upvotes: 1