Rainn
4 months ago

Custom Form Validation Is Not Working For Some Reason

Posted 4 months ago by Rainn

I am using custom form validation for my replies using toastr. For some reason the validation does indeed kick in by displaying the toastr notification example. But it won't stop the user from creating a reply.

I've tried overriding stock validation functions such as: formatValidationErrors() and failedValidation() The second function was the only one to work (displays the toastr notification), but it gave me the issue above.

App\Http\Controllers\ReplyController.php

Here is the store method. The ThreadReceivedReply event is included at the top of the file.

public function store(Thread $thread, ReplyForm $form)
{
    if (Gate::denies('create', new Reply)) {
        toastr()->error('You are creating too many replies. Please wait 30 seconds', 'Slow Down');
        return back();
    }
    
    $reply = Reply::create([
        'body' => Purifier::clean(request('body')),
        'user_steamid' => auth()->user()->steamid
    ]);

    event(new ThreadReceivedReply($reply));

    if($reply->user_steamid != $thread->user_steamid) {
        $thread->user->notify(new RepliedToThread($thread));
    };

    $thread->replies()->save($reply);

    Cache::forget('replies');

    toastr()->success('Reply created. Nice job');
    return back();
}

App\Http\Forms\ReplyForm.php

<?php

namespace App\Http\Forms;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;

class ReplyForm extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; // testing
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'body' => 'required|max:1000|spamfree'
        ];
    }

    public function messages()
    {
        return [
            'body.required' => 'Your reply needs body text!'
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        
        $messages = $validator->messages();

        foreach ($messages->all() as $message)
        {
            toastr()->error($message, 'Woops');
        }

        return $validator->errors()->all();
    }
}

I was sort of going off of this post to try to fix the issue but it didn't get me very far. The expected outcome is when you don't input body information it will display that validation error as a toast. I would show you errors but none were displayed. If you need any more information please don't hesitate to ask me. Thank's for your help in advance!

Please sign in or create an account to participate in this conversation.