Tabish
1 month ago
223
4
Laravel

how to insert data with laravel and ajax?

Posted 1 month ago by Tabish

I have this error:

http://localhost:8000/monthlyadd 500 (Internal Server Error)

error code:

message: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'monthly_id' cannot be null (SQL: insert into `month_monthly` (`month_id`, `monthly_id`) values (1, ?))"

how to solve this error?

my controller code:

 public function store(Request $request)
    {
        $monthly = new Monthly();
        $monthly->user_id = Auth::id();
        $monthly->result = $request->input('result');
        $monthly->problem = $request->input('problem');
        $monthly->suggestion = $request->input('suggestion');
        $monthly->months()->attach(request('month'));
        $monthly->years()->attach(request('year'));
        $monthly->save();
    }

js code:

<script>
      $(document).ready(function(){
          $('#addform').on('submit', function(e){
              e.preventDefault();
              $.ajax({
                  type: "post",
                  url: "/monthlyadd",
                  data: $('#addform').serialize(),
                  success: function(response){
                      console.log(response)
                      $('#exampleModal').modal('hide')
                      alert ("data seved")
                  },
                  error: function(error){
                      console.log(error)
                      alert ("data not seve")
                  }
              });
          });
      });
    </script>

modal monthly:

public function months()
    {
        return $this->belongsToMany(Month::class);
    }

modal month:

 public function monthlies()
    {
        return $this->belongsTo(Monthly::class);
    }

Please sign in or create an account to participate in this conversation.