Support the ongoing development of Laravel.io →
Requests Validation Architecture

I have a repository EloquentPageRepository that creates and saves pages.

I have an Observer than is fired when a page is being saved, and it does the validation there:

public function saving(\Eloquent $model)
    {
        $this->validator->setData($model->getAttributes());

        if ($this->validator->fails()) {
            $model->setAttribute('errors', $this->validator->errors());
            throw new ValidationException();
        }
    }

The ValidationException() is an empty Exception that I use because I don't always need to redirect or block the request when the validation fails (for example: I do batch import of pages that go through the validator)

So in my Page controller I do:

try {
$this->repo->update($page, $data);
} catch (ValidationException $v) {
 Log::info('validation failed');
}

But in other part of my website, I need to display the validation errors (because there is not only batch import, you can also edit a page on a form).

In the past, when my project was simple, I could do Redirect::back->withErrors($page->errors()) or something like that.

But how can I do this with my Exception? And how do I display the errors in the view then?

Last updated 2 years ago.
0

Add getters and setters for the validation errors and input in your exception. This is what I usually do (the exception class is the third file down): https://gist.github.com/thepsion5/9bccc8d05a36ef2c4453

Last updated 2 years ago.
0

Awesome!

I did a few changes and it worked immediately!

And completed a project before 6pm. I can go home and relax now thanks to you!

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

vanpet vanpet Joined 10 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.