Failed To Save Relationship Data In jQuery AJAX 500 (Internal Server Error)

I am trying to save data without relationship and success, but when I try to save data with one to many relationship, it’s failed with 500 (Internal Server Error).

Table
Failed To Save Relationship Data In jQuery AJAX 500 (Internal Server Error)

Product Model

public function category()
{
    return $this->belongsToMany('AppCategory');
}

/** 
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'id', 'name', 'product_code', 'product_photo'
];

Category Model

public function product() // parent 
{
    // one job only belongs to one type of job
    return $this->belongsToMany('AppProduct');
}

/** 
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'id', 'name'
];

Controller

// Save data to table product
    $product = new AppProduct;
    $product->name = $request->get('name');
    $product->product_code = $request->get('code');

    $productCode = AppProduct::where('product_code', '=', $request->get('code'))->first();

    if ($productCode === null) {
        $product->save();

        // Save relationship data between product and categories
        $getCategories = $request->get('categories');
        $productId = DB::table('products')->select('id')->where('product_code', $request->get('code'))->get();
        $theProduct = AppProduct::withTrashed()->findOrFail($productId);
        $theProduct->category()->attach($getCategories);

    }
    

    return response()->json(['success' => 'Product added successfully']);

View

<select style="width:100%;" placeholder="Select Categories" name="categories[]" multiple
                            id="categories"
                            class="categories form-control {{ $errors->first('categories') ? 'is-invalid' : '' }}"></select>

$('#saveBtnForCreate').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: "{{ route('products.store') }}",
            method: 'post',
            data: {
                name: $('#name').val(),
                code: $('#code').val(),
                categories: $('#categories').val(),
            },
            success: function(result) {
                if (result.errors) {
                    $('.alert-danger').html(
                        'An error in your input! Make sure the product code is unique'
                    );
                    $.each(result.errors, function(key, value) {
                        $('.alert-danger').show();
                        $('.alert-danger').append('<strong><li>' + value +
                            '</li></strong>');
                    });
                } else {
                    $('.alert-danger').hide();
                    $('.alert-success').show();
                    $('.datatable').DataTable().ajax.reload();
                    setInterval(function() {
                        $('.alert-success').hide();
                        location.reload();
                    }, 2000);
                }
            }
        });
    });

You know, when I am trying to save data without relationship (product name & product code) its success. But when I am trying to save relationship data between product and categories, it’s failed with 500 (Internal Server Error). Also, I couldn’t use dd() for debug the query. Any solution about it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’ve found the solution. Since you need to insert new data with relationship in one time, you need to use insertGetId method. This method will retrieve the id of last inserted data, so you can use the Id to perform relationship.

$productName = $request->get('name');
    $productCode = $request->get('code');
        $productId = DB::table('products')->insertGetId(
            [
                'name' => $productName,
                'product_code' => $productCode
            ]
        );

        // Save relationship data between product and categories
        $categoryId = $request->get('categories');
        $theProductId = AppProduct::withTrashed()->findOrFail($productId);
        $theProductId->category()->attach($categoryId);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x