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

时间:2018-01-03 21:23:48

标签: 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时验证请求的方法吗?

1 个答案:

答案 0 :(得分:3)

您可以在affirm()方法中执行以下操作:

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

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