我想删除一条记录:在按钮单击(hasMany)时删除属于用户的例程。我已经建立了视图,模型和内部关系,删除路由,以及要删除的控制器方法。
当我尝试单击按钮从数据库中删除该例程时,它什么也不起作用。为什么不删除记录?
下面是我的代码: route:Route::post('routine/delete', 'RoutineController@delete'); // Delete a routine for a user.控制器:
public function delete(Request $request)
{
$id = $request->input("id"); // Getting the id via. the ajax request.
$routine = \App\Routine::find($id); //Fetching the routine object from the db ifentified by the id passed via ajax
if ($routine)
{
$routine->delete();
}
return ["status" => "success"];
}查看:
<div class="col-lg-2">
<!-- When this button is clicked, we determine which routine to remove. -->
<button class="btn btn-danger remove_routine" data-id="{{$routine->id}}" data-token="{{csrf_token()}}" style="display:inline">Delete</button>
</div>用户模型:
public function routine()
{
return $this->hasMany('App\Routine');
}例程模型:
public function user()
{
return $this->belongsTo('App\User');
}提前感谢!
发布于 2016-08-14 01:24:38
不知道它是否准确地回答了您的问题,我也不使用AJAX,但我总是这样删除:
视图
@foreach($database-thing as $item)
<form method="POST" action="$yourActionHere" style="display:inline" >
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger btn-xs"><i class="fa fa-trash"></i> Delete</button>
</form>
@endforeach
// Even easier with laravelcollective/forms
@foreach($database-thing as $item)
{!! Form::open([
'method'=>'DELETE',
'url' => [$yourUrl, $item->id // <-- Very important],
'style' => 'display:inline'
]) !!}
{!! Form::button('<i class="fa fa-trash"></i> Verwijder', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs']) !!}
{!! Form::close() !!}
@endforeach控制器
public function destroy($id)
{
YourModel::destroy($id);
// All your other logic like redirects and stuff
}发布于 2016-08-17 06:31:33
基于上面的代码和这个更新的控制器函数,工作删除:
public function delete(Request $request,$id)
{
$user=Auth::user();
$routine = \App\Routine::findOrFail($id); // find or throw an error if you don't find the routine id in db.
// Makes if() statement redundant, since it checkes for that id already.
// Need to check that the owner of the routine is the current authenticated user.
if ($user->id != $routine->user->id)
{
Session::flash('flash_message', 'No routine found.');
}
else
{
$routine->delete();
Session::flash('routine_deleted','Routine deleted!');
}
// No need to return $routine since I am deleting it, otherwise it will throw and error of trying to get property of non-object.
return redirect()->back()->with('user') ;
//return view('view_routine')->with('user', 'routine');
} 发布于 2020-07-03 15:50:53
这就对了
$remove = 2;
$filtered = $c->filter(function ($value, $key) use($remove){
return $value['id']!=$remove;
});https://stackoverflow.com/questions/38934146
复制相似问题