简体   繁体   English

Laravel 从自定义验证返回错误消息

[英]Laravel return error messages from custom validation

I can't find any solution on how to display error messages from custom validation.我找不到任何关于如何显示自定义验证错误消息的解决方案。 I can not find it even on StackOverflow.我什至在 StackOverflow 上都找不到它。 My problem is that I have my controller and I need to validate some stuff in my custom class.我的问题是我有我的控制器,我需要在我的自定义类中验证一些东西。

Controller:控制器:

public function store()
{
    $customStuff = new MyTestClass();

    $variable =  $customStuff->myCustomValidation(5 );
    
    return view('test.index', compact('variable'));
}

And custom class:和自定义类:

namespace App\Classes;

class MyTestClass
{
    public function myCustomValidation($a = null, $b = null)
    {
        if (empty($a))
        {
            dd('error 1'); // how to throw message here
        }
        elseif (empty($b))
        {
            dd('error 2');  // how to throw message here
        }
        else
        {
            return ($a + $b);
        }
    }
}

This is just a sample code.这只是一个示例代码。 I know how to use Validator inside Controller but is it possible to return an error back to the user if something is wrong in the custom class ?我知道如何在Controller中使用Validator ,但是如果自定义class中出现问题,是否可以将错误返回给用户? Instead of dd() , it has to be an error message to the user.而不是dd() ,它必须是给用户的错误消息。

If you want to return that the validation failed to your view then do如果您想将验证失败返回到您的视图,请执行

return redirect()->back()->withErrors(['Message here!']);

And if you return as a API response then do如果您作为 API 响应返回,则执行

return response()->json(['error' => 'Message here!'], 404); // Or any other status code
<?php namespace App\Classes; class MyTestClass { public function myCustomValidation($a = null, $b = null) { abort_if(empty($a), 403, 'error 1'); abort_if(empty($b), 403, 'error 2'); return ($a + $b); } }

Why did you created a plain Class for validation?你为什么要创建一个普通的类来进行验证?

You can uselaravel rules if you are trying to create a custom validator如果您尝试创建自定义验证器,则可以使用laravel 规则

If you don't want to use a validator you can set a flash message如果你不想使用验证器,你可以设置一个flash 消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM