TH1981 TH1981 - 1 month ago 8
PHP Question

Laravel 5.2 return with errors - how to tell which form is submitted

I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.

I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.

I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.

I know I can use

$errors
to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?

Update:

Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:

AJAX call:

(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';

$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});

e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();


Request:

public function response(array $errors)
{
$response = parent::response($errors);

if ($this->ajax() || $this->wantsJson()) {
return $response;
}

return $response->with('requestMethod', $this->method());
}


I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.

Answer

You could override the response method so that you can flash the type of request.

In you Request class you could add

    public function response(array $errors)
{
    $response = parent::response($errors);

    if ($this->ajax() || $this->wantsJson()) {
        return $response;
    }

    return $response->with('requestMethod', $this->method());
}

(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)

In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.

Then in your view you could do something like:

@if(session('requestMethod') == 'POST')

https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data

Hope this helps!

Comments