问:我正在尝试通过确认当前用户的密码来删除记录。用户点击后有一个删除图标,显示用户名并要求输入密码以删除记录。如果用户输入正确的密码并单击删除按钮,它应该删除选定的记录。我的控制器在这里..有人可以帮我吗?
公共函数销毁(请求 $request)
{
$email=$request->email;
$password=$request->password;
if( Auth::attempt (['email'=>$email,'password'=>$password]))
{
return "success";
}
else{
return "error";
}
; }
//刀片文件
<div class="card-body">
<div class="table-overflow">
<table id="dt-opt" class="table table-hover table-xl">
<thead>
<tr>
<th>No</th>
<th>Product Title</th>
<th>Added Quantity</th>
<th>Avialable Quantity</th>
<th>Type</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($data as $item)
<tr >
<td>{{$item->id}}</td>
<td>{{$item->title}}</td>
<td>{{$item->added_quantity}}</td>
<td>{{$item->available_quantity}}</td>
<td>{{$item->type}}</td>
<td>{{$item->price}}</td>
<td class="font-size-18">
<a href="" class="text-gray m-r-15"><i class="ti-pencil fa-lg"></i></a>
<a data-toggle="modal" data-target="#deleteModal" class="text-gray"><i class="ti-trash fa-lg"></i></a>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="d-flex justify-content-center">
{!! $data->links() !!}
</div>
</div>
</div>
//删除模态
{{-- 删除模态--}}
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="{{url('confirm-&-delete/')}}" method="POST">
{{ csrf_field() }}
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel"> <span>{{ Auth::user()->name }}</span> Please type your password to delete the record</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="text" class="form-control" name="email" placeholder="User Name" required>
</div>
<div class="modal-body">
<input type="password" class="form-control" name="password" placeholder="Password" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-gradient-danger">Delete</button>
</div>
</form>
</div>
</div>
</div>
答:我会在服务中使用一个函数来确认用户密码。
我会在 app/Services/UserService.php 中创建一个服务
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class UserService
{
public function confirmCurrentUserPassword($password)
{
if(! $user = Auth::user()) {
return 0;
}
return User::where('id', $user->id)
->where('password', $password)
->first();
}
}
在您的控制器中,将收到的用户密码从用户服务传递给函数。
public function destroy()
{
$password = Hash::make($request->password);
$userService = new UserService();
$currentUser = $userService->confirmCurrentUserPassword($password);
if(! $currentUser instanceof User) {
return redirect()->back()->with('status', 'some message');
}
// You can then delete the user
}