4

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?

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, lovely simple solution, although I threw an HttpResponseException with the $validator->errors() as suggested here: paulund.co.uk/disable-validation-redirect-in-laravel

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.