我已经搜索并尝试了许多类似案件的解决方案,但对我的案件无济于事。我对Laravel还是很陌生,对口才不太了解。我正在尝试删除论坛的话题,请帮忙。
这是删除线程的途径:
Route::get('/forum/{forum_id}/thread/{thread_id}/delete', [
'uses' => 'ForumsController@deleteThread',
'as' => 'thread.delete']);
这是函数(我不知道如何获取线程ID):
public function deleteThread($id)
{
$forum = Forum::find($id);
$thread = $forum->threads;
dd($thread);
$thread->delete();
return redirect()->back();
}
这是删除按钮:
<a href="{{ route('thread.delete', ['forum_id' => $forum->id, 'thread_id' => $thread->id]) }}" class="btn btn-danger">Delete</a>
这是论坛模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forum extends Model
{
public function threads () {
return $this->hasMany(Thread::class);
}
}
这是线程模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
public function forum () {
return $this->belongsTo(Forum::class);
}
}
答案 0 :(得分:2)
您的路线如下:
Route::get('/forum/{forum_id}/thread/{thread_id}/delete', [ ... ])
您必须使用forum_id
和thread_id
作为控制器功能的参数:
public function deleteThread($forum_id, $thread_id)
{
$forum = Forum::find($forum_id);
$thread = Thread::find($thread_id);
$thread->delete();
return redirect()->back();
}
您甚至可以让Laravel为您注入Forum
和Thread
到控制器中-通过在函数中键入它们:
public function deleteThread(Forum $forum, Thread $thread)
{
$thread->delete();
return redirect()->back();
}
当然,您必须将路由的forum_id
参数分别调整为forum
,将thread_id
调整为thread
。例如,这还需要更改在其他视图中传递给URL的参数(又名删除按钮)。
更新
顺便说一句,您不应该使用get请求删除。您应该使用DELETE
HTTP请求。
答案 1 :(得分:1)
您应该尝试以下操作:
public function deleteThread($forum_id,$thread_id)
{
Thread::destroy($thread_id);
return redirect()->back();
}