【问题标题】:Laravel post radio buttonLaravel 发布单选按钮
【发布时间】:2019-05-07 08:19:39
【问题描述】:

我想将单选按钮的值发送给类,问题是每次名字都不一样,因为我有一个id最终在视图中分组,我如何引用这个名字?

@foreach($users as $user)
<tr>
    <td>{{ $user->id }}</td>
    <td>{{ $user->name }}</td>
    <td>{{ $user->email }}</td>

    <td>
        <form method="post" action="updateprivileges/{{$user->id}}">
            @csrf 
            <div class="row">
                <div class="col-4">
                    <input type="radio" value="1" class="flat" name="privileges_{{ $user->id }}" {{ $user->privileges[0]['roles_id'] == '1' ? 'checked' : '' }} > <div class="uprawnienia-margin">Administrator</div>
                </div>
                <div class="col-4">
                    <input type="radio" value="2" class="flat" name="privileges_{{ $user->id }}" {{ $user->privileges[0]['roles_id'] == '2' ? 'checked' : '' }} > <div class="uprawnienia-margin">Serwisant</div>
                </div>
                <div class="col-4">
                    <input type="radio" value="3" class="flat" name="privileges_{{ $user->id }}" {{ $user->privileges[0]['roles_id'] == '3' ? 'checked' : '' }} > <div class="uprawnienia-margin">Monter</div>
                </div>
            </div>
            <input type="submit" name="add" class="btn btn-primary input-lg" value="Przeslij" />
        </form>
    </td>
</tr>
@endforeach

【问题讨论】:

  • $(document).on("click", "*[name*='privileges_']", function () { }); 使用 jquery。
  • 你可以用“name”切换“value”,这样每个单选按钮的“name”都是一样的,“value”就是你当前传入的“name” ",并为单选按钮使用标签:developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
  • 您忘记了代码块上的&lt;td&gt; 和语法高亮。我还编辑了你的缩进。

标签: laravel forms button


【解决方案1】:

您有动态名称属性。您应该将其更改为静态值,以便您始终可以在接收有效负载的控制器中接收正确的值。并且不要忘记使用正确的HTTP Method

<form method="post" action="{{ URL::to('/updateprivileges/' . $user->id)}}">
    @csrf

    <input type="radio" name="privilege" value="1"> Administrator</br>
    <input type="radio" name="privilege" value="2"> Serwisant</br>
    <input type="radio" name="privilege" value="3"> Monter</br>
    <input type="submit" value="Przeslij">
</form>

routes/web.php中声明路由:

// put method
Route::post('updateprivileges/{id}', 'UserController@updatePrivileges');

现在,您的UserControllerRequest $request 中接收到privilege 变量:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function updatePrivileges(Request $request, $id)
    {
        $privilege = $request->input('privilege');
        dd($privilege); // dumps $privilege and dies
        // more code, perhaps save the users privilege
    }
}

我希望这会有所帮助。

您可能想查看Laravel Method SpoofingPut, Post, Patch。由于您知道用户(通过 id),您可能希望切换到 PUTPATCH 方法。

【讨论】:

  • 好的,这很好,我对你的解决方案有疑问,在看来,你已经获得了合法权利,现在这不会发生......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2011-02-16
  • 2011-03-26
  • 2016-12-23
  • 1970-01-01
  • 2018-04-23
  • 2017-05-27
相关资源
最近更新 更多