簡體   English   中英

$ errors在Laravel 5.4中返回null

[英]$errors returns null in laravel 5.4

所以我正在使用laravel 5.4,但是我陷入了這個錯誤並且無法解決它。我研究了這個錯誤,並且我發現這是以前發生的,但是解決方案不適用於我的項目。

我創建了一個在頁面中添加注釋的表單,如果我輸入某種形式將其保存在數據庫中,並且驗證工作正常,則它可以工作,因為它不允許我添加空注釋,但不會在頁面中顯示錯誤。 This is the comment form in views

<form method="post" action="{{ route('comments.store') }}">
    {{ csrf_field() }}

    <input type="hidden" name="commentable_type" value="App\Company">
    <input type="hidden" name="commentable_id" value="{{ $company->id }}">

    <h2>Add a comment</h2>
    <div class="form-group @if($errors->has('url')) has-error @endif">
        <label for="comment-content">Work done (url/title)</label>
        <textarea placeholder="Enter url/title"
                  style="resize: vertical;"
                  id="comment-content"
                  name="url"
                  rows="2" 
                  spellcheck="false"
                  class="form-control autosize-target text-left">
        </textarea>
    </div>

    <div class="form-group @if($errors->has('body')) has-error @endif">
        <label for="comment-content">Comment</label>
        <textarea placeholder="Enter comment"
                  style="resize: vertical;"
                  id="comment-content"
                  name="body"
                  rows="3"
                  spellcheck="false"
                  class="form-control autosize-target text-left">
        </textarea>
    </div>

    <div class="form-group">
        <input type="submit" class="btn btn-primary" value="Submit"/>
    </div>
</form>

這是CommentsControlles.php

public function store(CommentSubmitFormRequest $request)
{
    $comment = Comment::create([
        'body' => $request->input('body'),
        'url' => $request->input('url'),
        'commentable_type' => $request->input('commentable_type'),
        'commentable_id' => $request->input('commentable_id'),
        'user_id' => Auth::user()->id
    ]);

    if ($comment)
    {
        return back()->with('success', 'Comment added successfully');
    }
}

這是Request CommentSubmitFormRequest.php

class CommentSubmitFormRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'body' => 'required',
            'url' => 'required',
        ];
    }
}

當我提交空的評論表格時, $errors返回null而不是錯誤

您的驗證規則不完整。 它只是說是必填項,在您的情況下,因為字段確實存在,所以您的bodyurl被發送。 您應該設置最少的字符數或對url字段輸入active_url/url

public function rules()
{
    return [
        'body' => 'required|min:1', // minimum length of 1 character
        'url' => 'required|url', // must be a valid URL
    ];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM