【问题标题】:unique validation is in not working in laravel 5.4独特的验证在 laravel 5.4 中不起作用
【发布时间】:2017-05-19 05:17:42
【问题描述】:

我正在制作一个使用 laravel 5.4 进行验证的待办事项列表。

当我点击提交按钮时,只有所需的验证有效,但唯一的无效。

我做错了什么以及如何解决它以使其按预期工作?

下面是我的表格(位于home.blade.php):

<div class="panel-body">
    <form class="form form-control" action="/todo" method="post">
        {{csrf_field()}}
        <fieldset class="form-group">
            <textarea class="form-control" name="textbox" id="textArea"></textarea>
            <button type="submit" class="btn btn-primary">Submit</button>
        </fieldset>
    </form>
    {{-- for dispaying the error --}}
    @if (count($errors) >0)
        {{-- expr --}}
        @foreach ($errors->all() as $error)
            <h3 class="text-danger">{{$error}}</h3>
        @endforeach
    @endif
</div>

这里是我的 Todo 控制器的内容(在我的todocontroller.php 文件中):

use Illuminate\Http\Request;
use App\todo;
public function store(Request $request)
{
    $todo = new todo;
    $todo->body = $request->textbox;
    $this->validate($request,[
        "body" => "required|unique:todos"
    ]);
    $todo->save();
    return redirect('/todo');
}

【问题讨论】:

  • 独特的有什么不好的?它总是抛出错误还是从不抛出?
  • 明智地直接传递“文本框”而不是正文。 $this->validate($request,["textbox" => "required|unique:todos"]);
  • 你的问题解决了吗?您是否还面临任何挑战?

标签: php laravel-5


【解决方案1】:

您应该简单地使用该字段的名称;你不需要给自己压力。

看看下面的sn-p:

<?php

namespace App\Http\Controllers;
use App\Todo;// following Laravel's standards, your model name should be Todo; not todo
use Illuminate\Http\Request;

class NameOfYourTodoController extends Controller
{

    public function store(Request $request)
    {
        $todo = new Todo();

        // use the name of the field directly (here, textbox)
        $this->validate($request, [
            'textbox' => 'required|unique:todos'
        ]);

        // other code logics here.
    }
}

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 2017-07-12
    • 2019-06-21
    • 2014-11-29
    • 2017-06-21
    • 2021-11-28
    • 2018-12-01
    • 2017-10-19
    相关资源
    最近更新 更多