Search code examples
ajaxlaravellaravel-validation

Returning error if the validation fails in laravel


I am using ajax to populate the data to a database. The thing which I want is, I want to receive errors if the entered data fails validation. I have following code in my controller:

public function store(Request $request)
{
    $rules = $this->category->getRules();

    if ($request->validate($rules)->fails())
    {
        return Response::json(array(
            'success' => false,
            'errors' => $request->validate($rules)->getMessageBag()->toArray()

        ), 400);
    }

    $data = $request->all();
    $data['title'] = $request->title;
    $data['is_parent'] = $request->is_parent;
    $data['parent_id'] = $request->parent_id;
    $data['priority'] = $request->priority;
    $data['icon'] = $request->icon;
    $data['slug'] = $request->slug;
    $data['show_in_nav'] = $request->show_in_nav;
    $this->category->fill($data);
    $status = $this->category->save();
    if($status){
        return response()->json(['status'=>true,'data'=>'Category created successfully.']);
    } else {
        return response()->json(['status'=>false,'data'=>null]);
    }
}

It is still giving the error in console with 422 (Unprocessable Entity)but not in a json. How can I manage to get the errors in json so that I can show it to the user?


Solution

  • Thank you all for your efforts but I simply got my desired output by doing this in ajax:

    error: function(response){   
        let data = response.responseJSON.errors;
        $.each( data, function( key, value ) {
        $( "<span class='text-danger'>"+value+"</span>" ).insertAfter( "#"+key );
    });
    }
    

    Also I did not have to write condition in validation simply doing the following worked for me.

    public function store(Request $request)
    {
        $rules = $this->category->getRules();
        $request->validate($rules);
        $data = $request->all();
        $data['name'] = $request->name;
        $data['is_parent'] = $request->is_parent;
        $data['parent_id'] = $request->parent_id;
        $data['priority'] = $request->priority;
        $data['icon'] = $request->icon;
        $data['slug'] = $request->slug;
        $data['show_in_nav'] = $request->show_in_nav;
        $this->category->fill($data);
        $status = $this->category->save();
        if($status){
            return response()->json(['status'=>true,'data'=>'Category created successfully.']);
        } else {
            return response()->json(['status'=>false,'data'=>null]);
        }
    }