Search code examples
phplaravellaravel-5laravel-5.4laravel-validation

How to prevent Laravel from redirecting when validation fail?


I have a project that is written on the top of Laravel 5.4.

I need to create CRUD for an API. However, when the request validation fails, Laravel auto direct the user to the home page.

Instead of redirecting, I want to to display the errors so that the API called knows the reason for the error.

Here is stripped down version of my code

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);
    }
}

How can I prevent Laravel from redirecting when $this->validate method is called?

Also, is there another way to validate the request when create CRUD for API?


Solution

  • You could do something like this in affirm() method:

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

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