【问题标题】:Update status problems更新状态问题
【发布时间】:2022-01-07 11:51:14
【问题描述】:

我正在尝试更新状态。如果状态为 0,则单击时必须将其更新为 1。但如果单击时状态为 1,则必须将其更新为 0。

我的控制器

public function status(Course $course)
{
    if ($course->status == 0) {
        $course->update(['status' => '1']);
        return redirect('/profile')->with('statusOn', 'status on!');
    } else {
       $course->update(['status' => '0']);
       return redirect('/profile')->with('statusOff', 'status off!');
    }
}

路线

Route::post('/course/status/{course}', [CourseManagementController::class, 'status']);

刀片

  <form method="POST" action="/course/status/{{$c->id}}">
                            @csrf
                            @if($c->status == 0)
                            <button type="submit" class="btn btn-success">active</button>
                            @else
                            <button type="submit" class="btn btn-danger">deactive</button>
                            @endif
                        </form>

【问题讨论】:

  • 好的...有什么问题?当你测试这段代码时会发生什么,你需要什么帮助?
  • 它正在重定向到个人资料页面,但状态没有改变,所以我需要了解我做错了什么?
  • 您确定该方法正在执行吗?如果你 dd($course) 进入它,你会看到 dd?
  • 我在您的表单中看不到任何会改变状态的内容。您显示的按钮虽然可能具有不同的颜色和文本,但在功能上是相同的。您需要在它们上设置一个值,然后您可以在控制器函数中读取该值,以查看是否按下了激活或停用按钮。
  • @Alex 我明白了,谢谢。不是我在我使用过的其他 MVC 框架中遇到的,根据我的经验,你必须在动作函数中编写一些特定的东西才能做到这一点。否则,它只会从表单发布的数据中填充模型。这是有用的信息,谢谢。因此,我现在认为我理解了下面接受的答案。

标签: php html laravel forms laravel-blade


【解决方案1】:

您好,请调试!

public function status(Course $course)
{
    dump($course); // the data is okay or not

    if ($course->status == 0) {
        $status = $course->update(['status' => '1']);

        dd($status); // check the update status

        // return redirect('/profile')->with('statusOn', 'status on!');
    } else {
        $status = $course->update(['status' => '0']);

        dd($status); // check the update status

        // return redirect('/profile')->with('statusOff', 'status off!');
    }
}

如果一切正常,请检查Course 类的fillable 变量,status 可能在fillable 数组中丢失

【讨论】:

  • 感谢您的回答。大声笑是的,这是愚蠢的错误。我忘记了可填充数组中的状态)
  • 很高兴知道,有帮助,别忘了投票:)
猜你喜欢
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2021-10-21
  • 1970-01-01
相关资源
最近更新 更多