【问题标题】:Laravel deleting a thread of a forumLaravel 删除论坛的一个线程
【发布时间】:2018-11-23 12:24:25
【问题描述】:

我已经搜索并尝试了很多类似案例的解决方案,但对我的案例没有任何效果。我对 Laravel 还是很陌生,对 eloquent 不太了解。我正在尝试删除论坛的线程,请帮助。

这是删除线程的路径:

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);
    }
}

【问题讨论】:

    标签: php laravel eloquent laravel-5.5


    【解决方案1】:

    您的路线如下所示:

    Route::get('/forum/{forum_id}/thread/{thread_id}/delete', [ ... ])
    

    您必须使用 forum_idthread_id 作为控制器功能的参数:

    public function deleteThread($forum_id, $thread_id)
    {
        $forum = Forum::find($forum_id);
        $thread = Thread::find($thread_id);
    
        $thread->delete();
    
        return redirect()->back();
    }
    

    您甚至可以让 Laravel 为您将 ForumThread 注入控制器 - 通过在函数上提示它们:

    public function deleteThread(Forum $forum, Thread $thread)
    {
        $thread->delete();
    
        return redirect()->back();
    }
    

    当然,您必须将路由的forum_id 参数分别调整为forumthread_idthread。这还需要更改您在其他视图中传递给 URL 的参数,例如(又名 删除按钮)。

    更新 顺便说一句,您不应该使用获取请求来删除。您应该使用DELETE HTTP 请求。

    【讨论】:

      【解决方案2】:

      你应该试试这个:

      public function deleteThread($forum_id,$thread_id)
          {
              Thread::destroy($thread_id);
      
              return redirect()->back();
          }
      

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-27
        • 1970-01-01
        • 2011-02-28
        相关资源
        最近更新 更多