我在laravel的用户表中有多个字段,但是我只想从用户表中删除图像,请让我知道该过程。 这是我的usercontroller.php文件。
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);
}
这是我的profile.blade.php文件。
@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
我的web.php文件是这个...
Route::get('/userprofile', 'CustomHomeController@userprofile')->name('userprofile');
Route::get('/userprofile/{id}', 'CustomHomeController@imagedestroy')->name('imagedestroy');
答案 0 :(得分:1)
使用first()代替get()。 get()为您提供一个集合,您需要对其进行迭代以获取属性。这样就无法获得
这样的用户的图片$image = DB::table('users')->where('id', $id)->get();
$file= $image->user_image; //this won't work.
尝试
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);
}
您的userprofile方法应该像
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]);
}
因此,您无需在视图中进行迭代。只需使用
<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>