Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jdauphinais's avatar

Use laravel validation on create/update using ajax

I am using ajax from a page to create a record in the database. The Jquery is getting all the data needed and I am not using the normal form request but instead, I am sending an ajax to laravel with all the data.

From there, in my controller, at the moment, I am using:

public function addRevenue(Request $request)
    {
        // When using stdClass(), we need to prepend with \ so that Laravel won't get confused...
        $result = new \stdClass();
        $inputs = $request->all();
        $projectRevenue = ProjectRevenue::where('project_id', '=', $inputs['project_id'])->where('year', '=', $inputs['year'])->where('product_code', '=', $inputs['product_code'])->first();
        if ($projectRevenue === null) {
            ProjectRevenue::insert($inputs);
            $result->result = 'success';
            $result->msg = 'Record added successfully';
        } else {
            $result->result = 'error';
            $result->msg = 'Record already in DB';
        }

        return json_encode($result);
    }

It is working but I would prefere to use Laravel validate method instead. Since I am not moving from the page, how can I catch the information that is coming back so that I can give different messages as in my original example?

0 likes
1 reply
jlrdw's avatar

Just include some validation prior to request

        $request->validate([
            'species' => 'required'
        ]);
       $petid = $request->input('petid');
       $species = $request->input('species');

And in js display any errors in a div

                error: function (data, ajaxOptions, thrownError) {
                    var status = data.status;
                    if (data.status === 422) {
                        $.each(data.responseJSON.errors, function (key, value) {
                            $('#msg').append('<div>' + value + '</div>');
                        });
                    }

                    if (status === 403 || status === 500) {
                        $('#msg').text("Not Auth");
                       
                    }
                   
                }
            });

Please or to participate in this conversation.