php - 验证失败时如何防止 Laravel 重定向?

标签 php laravel laravel-5 laravel-5.4 laravel-validation

我有一个写在 Laravel 5.4 之上的项目。

我需要为 API 创建 CRUD。但是,当请求验证失败时,Laravel 会自动将用户定向到主页。

我想显示错误而不是重定向,以便被调用的 API 知道错误的原因。

这是我的代码的精简版

class AssetsController extends Controller
{
    /**
     * Store a new asset in the storage.
     *
     * @param Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            $this->affirm($request);

            $data = $this->getData($request);

            $asset = Asset::create($data);

            return response()->json([
                'data' => $this->transform($asset),
                'message' => 'Asset was successfully added.',
                'success' => true,
            ]);

        } catch (Exception $exception) {
            return response()->json([
                'data' => null,
                'message' => $exception->getMessage(),
                'success' => false,
            ]);
        }
    }

    /**
     * Validate the given request with the defined rules.
     *
     * @param  Illuminate\Http\Request  $request
     *
     * @return boolean
     */
    protected function affirm(Request $request)
    {
        $rules = [
            'name' => 'required|string|min:1|max:255',
            'category_id' => 'required',
            'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
            'purchased_at' => 'nullable|string|min:0|max:255',
            'notes' => 'nullable|string|min:0|max:1000',
            'picture' => 'nullable|string|min:0|max:255',
        ];

        // This seems to redirect the user to the home page which I want to avoid
        return $this->validate($request, $rules);
    }
}

调用 $this->validate 方法时如何防止 Laravel 重定向?

另外,在为 API 创建 CRUD 时是否有另一种方法来验证请求?

最佳答案

你可以在 affirm() 方法中做这样的事情:

$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
    throw new Exception;
}

https://laravel.com/docs/5.5/validation#manually-creating-validators

关于php - 验证失败时如何防止 Laravel 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085316/

相关文章:

php - 将 MSSQL 和 MySQL 与 CodeIgniter 结合使用

javascript - 设置在线测验计时器

mysql - 如何将laravel模型保存到2个数据库

php - 使用ajax加载laravel View

javascript - FullCalendar 在 laravel 中不起作用?

php - 使用数据库驱动数据在 MS Excel 中创建动态下拉菜单

javascript - <select> 的 jQuery .clone() : change the selected option

php - 如何将数组值从一个方法传递给 Laravel 中的另一个方法?

php - 如何从laravel中的中间表中获取数据?

Laravel 5、检查类是否在容器中注册