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

Mim's avatar
Level 1

Can't insert data into my table

My pages refreshes after submitting but doesn't insert any data

In my showBedAssig.Blade file

  <a class="btn btn-info" id="assign-bed" href="#" style="margin-bottom:2%">Assign Bed </a>
              <table class="table table-striped table-hover">
                <thead class="thead-dark">
                  <tr>
                    
                    <th scope="col">#</th>
                    <th scope="col">Patient Name</th>
                    <th scope="col">Bed</th>
                    <th scope="col">Assign Date</th>
                    <th scope="col">Discharge Date</th>
                    <th scope="col">Status</th>
                    <th scope="col">Available</th>
                    <th scope="col">Occupied</th>
                  </tr>
                </thead>
                <tbody>
                  @foreach ($bed_assigns as $bed_assign)
                  <tr>
                    <td>{{ $bed_assign->patient->name }}</td>
                    <td>{{ $bed_assign->bed->name }}</td>
                    <td>{{ $bed_assign->assign_date }}</td>
                    <td>{{ $bed_assign->discharge_date }}</td>
                    <td>
                      @if ($bed_assign->status === 'Available')
                          <span class="badge badge-outline-success">Available</span>
                      @elseif ($bed_assign->status === 'Occupied')
                          <span class="badge badge-outline-danger">Occupied</span>
                      {{-- {{-- @else --}}
                          {{-- <span class="badge badge-outline-warning">.....</span> --}} 
                      @endif
                      </td>
                     <td>
                      @unless($bed_assign->status === 'Available')
                      <a class="badge badge-outline-success" onclick="hide" href="{{url('available',$bed_assign->id)}}">Available</a>      
                    @endunless
                    </td>

                    <td>
                      @unless($appointment->status === 'Occupied')
                      <a class="badge badge-outline-danger" onclick="hide" href="{{url('occupied',$bed_assign->id)}}">Occupied</a>      
                    @endunless
                    </td>
                  </tr>
                  @endforeach
              </tbody>
            </table>

In my form

 <div class="modal fade " id="assign-modal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog"> {{--modal-dialog modal-lg--}}
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel"> Assign New Bed</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
      
                        <form action="{{url('upload_assignedbed')}}" method="POST" id="assign-form" enctype="multipart/form-data">
                          @csrf
                          <div class="row mb-3">
                              <label for="user_id" class="col-sm-2 col-form-label">Patient Name</label>
                              <div class="col-sm-10">
                                <select class="form-select form-select-sm" id="patient_id" name="patient_id" aria-label=".form-select-sm example" >
                                  <option>--Select Patient--</option>
                                  @foreach($patients as $patient)
                                  <option value="{{$patient->id}}" class="form-control">{{$patient->name}}</option>
                                  @endforeach
                                </select>
                              </div>
                          </div>
                          <div class="row mb-3">
                              <label for="bed_id" class="col-sm-2 col-form-label">Bed</label>
                              <div class="col-sm-10">
                                <select class="form-select form-select-sm" id="bed_id" name="bed_id" aria-label=".form-select-sm example" >
                                  <option>--Select Bed Type--</option>
                                  @foreach($beds as $bed)
                                  <option value="{{$bed->id}}" class="form-control">{{$bed->name}}</option>
                                  @endforeach
                                </select>
                              </div>
                          </div>
                          <div class="row mb-3">
                            <label for="assigned_date" class="col-sm-2 col-form-label">Assigned Date</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="assigned_date" name="assigned_date" placeholder="Assigned Date" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                          <label for="discharged_date" class="col-sm-2 col-form-label">Discharged Date</label>
                          <div class="col-sm-10">
                              <input type="date" class="form-control" id="discharged_date" name="discharged_date" placeholder="Discharged Date" >
                          </div>
                      </div>
                      </form> 
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
              <button type="submit" id="sub-assign-btn" class="btn btn-outline-primary">Submit</button>
            </div>
          </div>
        </div>
      </div>



  
<!-- container-scroller -->

<!-- plugins:js -->
@include('nurse.script')
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
				<script>
								  $(document).ready(function(){
  									$('#assign-bed').click(function(){
    $('#assign-modal').modal('show');
  });

  $('#sub-assign-btn').click(function(){
    $('#assign-form').submit();
  });
});

In my showBedAssign controller

public function showBedAssigned(){

    $patients = User::where('usertype', '=', '0')->get();
    $beds = Bed::where('name', '!=', null)->get();

    $bed_assigns = BedAssign::all();

    return view('nurse.showBedAssigned', compact('bed_assigns'))
    ->with('beds', $beds)
    ->with('patients', $patients);
}

public function upload(Request $request){

       $request->validate([
        'assign_date'=> 'required|date',
        'discharge_date'=> 'date',
        'patient_id' => 'required|exists:patients,id',
        'bed_id' => 'sometimes|exists:beds,id',             
       ]);

    $bed_assigns = new BedAssign;

    $bed_assigns->assign_date = $request->input('assign_date');
    $bed_assigns->discharge_date = $request->input('discharge_date');
    $bed_assigns->status =  'Available';
    $bed_assigns->patient_id =$request->input('patient_id');
    $bed_assigns->bed_id = $request->input('bed_id');


    $bed_assigns->save();

    return redirect()->back()->with('message','Bed Assigned  Successfully');

}
0 likes
39 replies
tykus's avatar

Probably a validation failure. Can you display the $errors on the page?

<pre>@json($errors->all())</pre>

Then, if this supposition is correct, work out how/why you are getting the validation error?

tykus's avatar

@Mim check the Network tab in the browser’s devtools; is there a Request being made?

Mim's avatar
Level 1

@tykus The error says , Failed to load response data: No content available because this request was redirected.

peterl38's avatar

I think your ajax submit is probably not working, either because it is unavailable when the DOM is loaded, or the SUBMIT is firing on the HTML first.

In your form, you have

<button type="submit" id="sub-assign-btn" class="btn btn-outline-primary">Submit</button>

But I cannot see anywhere the ajax to prevent the HTML submit firing such as.

$("#assign-form").submit(function(e){
    e.preventDefault();
});

What do you see if you add a DD to the showBedAssign controller?

public function upload(Request $request){

	dd($request);// <- add this

    $request->validate([
        'assigned_date'=> 'required|date',
        'discharged_date'=> 'date',
        'patient_id' => 'required|exists:patients,id',
        'bed_id' => 'sometimes|exists:beds,id',             
       ]);

    $bed_assigns = new BedAssign;

If you see nothing, it's not getting that far, so look to your route file and be sure you're calling a POST method.

tykus's avatar

@peterl38 it's not an asynchronous request; the code simply submits the form although it is not clear why this particular jQuery is necessary:

$('#sub-assign-btn').click(function(){
    $('#assign-form').submit();
});
Mim's avatar
Level 1

@peterl38 +request: Symfony\Component\HttpFoundation\InputBag {#44 ▼ #parameters: array:5 [▼ "_token" => "nZLj6dVgNbad4Qhfeuupww2ZqXB006Wx0zyzxMJ3" "patient_id" => "8" "bed_id" => "1" "assign_date" => "2022-08-29" "discharge_date" => "2022-08-31" ]

i get it in the request

tykus's avatar

@Mim your validation rule expects assigned_date and discharged_date, but the request gives assign_date and discharge_date. So, as mentioned at the top... validation failure. Although this is not consistent with the mark-up you posted earlier 🤷‍♂️

Mim's avatar
Level 1

@tykus yes i realized and changed all

  $request->validate([
        'assign_date'=> 'required|date',
        'discharge_date'=> 'date',
        'patient_id' => 'required|exists:patients,id',
        'bed_id' => 'sometimes|exists:beds,id',             
       ]);

    $bed_assigns = new BedAssign;

    $bed_assigns->assign_date = $request->input('assign_date');
    $bed_assigns->discharge_date = $request->input('discharge_date');
    $bed_assigns->status =  'Available';
    $bed_assigns->patient_id =$request->input('patient_id');
    $bed_assigns->bed_id = $request->input('bed_id');

but is the same issue

tykus's avatar

@Mim so, now we have the correct validation rules, but still you are redirected back without validation errors? Where did you place <pre>@json($errors->all())</pre> in the page?

tykus's avatar

@Mim but that form is in the Modal, which doesn't display after you're redirected back, right? I meant for you to add that into the showBedAssig view template so you can see any validation errors after submitting the form

Mim's avatar
Level 1

@tykus it says ["The selected patient id is invalid."]

tykus's avatar

@Mim FFS... typed a reply to your earlier it's just printing an empty array response.

So The selected patient id is invalid. tells you the problem, right? This is the validation error mentioned at the outset of this thread. What value does it have, and why is it not existing on the patients table?

Mim's avatar
Level 1

@tykus the patients table is a foreign key connected to users with usertype 0 .

tykus's avatar

@Mim not exactly the question I asked... You have a collection/array of Patients which is used to populate the patient_id select input:

<select class="form-select form-select-sm" id="patient_id" name="patient_id">
    <option>--Select Patient--</option>
    @foreach($patients as $patient)
        <option value="{{$patient->id}}" class="form-control">{{$patient->name}}</option>
    @endforeach
</select>

So what is $patient->id representing exactly, is this an ID on the patients table, or an ID on the users table? Your exists validation rule is checking the patients table

tykus's avatar

@Mim I don't understand your database schema.

the patients table is a foreign key connected to users with usertype 0

What does this mean? Can you share the table schema for users and patients please?

Mim's avatar
Level 1

@tykus

  public function up()
  {
    Schema::create('patients', function (Blueprint $table) {
        $table->unsignedBigInteger('user_id');
        $table->id();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('date')->nullable();
        $table->string('payment_method')->default(1)->comment('1 = Cash');
        $table->timestamps();
    });
}

and users

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('phone')->nullable();
        $table->string('address')->nullable();
        $table->string('usertype')->default(0);
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->foreignId('current_team_id')->nullable();
        $table->string('profile_photo_path', 2048)->nullable();
        $table->timestamps();
    });
}

and this is my patient model

  class Patient extends Model

{ protected $fillable = [ 'user_id','payment_method' ];

public function doctor()   {
    return  $this->belongsTo(Doctor::class);
 }

 public function user() {
     return $this->belongsTo(User::class);
 }


 
use HasFactory;

}

tykus's avatar

@Mim okay, I don't know why this needed a separate table - it adds no value that I can see???

Anyway, you have a Collection of patients (for the select options); it has a name property which I suppose comes from the users table. It also has an id property which comes from where exactly - i.e. is it the id from the users table or from the patients table? How do you assign to the $patients property?

Mim's avatar
Level 1

@tykus okay so im building an online hospital management system that's why the users and patients have different tables . I don't really get the question about how I assign the $patients property , sorry. But if I do dd($request); the patient_id comes from the users table .

tykus's avatar

@Mim well that is why your validation rule is failing - make sure it is checking the correct table/column, for example, checking the user_id on the patients table

'patient_id' => 'required|exists:patients,user_id',

or, the id on the users table with the additional constraint on usertype column:

'patient_id' => ['required', Rule::exists('users', 'id')->where('usertype', 0)]
Mim's avatar
Level 1

@tykus yes i tried all that before and now but I got an SQLSTATE[23000]: Integrity constraint violation:

tykus's avatar

@Mim what does the reset of the error message say?

I assume the problem is a foreign key constraint that requires you to use a valid patients.id and not a users.id? Which goes back to (i) the unnecessary decision to separate the users and patients table and (ii) using the wrong data to populate the select input in the form.

// controller action that returns the view with the form 
$patients = Patient::query()
    ->join('users', 'users.id', 'patients.user_id') // join to get `name` from users table
    ->pluck('users.name', 'patients.id');
// the view with the form
<select class="form-select form-select-sm" id="patient_id" name="patient_id">
    <option>--Select Patient--</option>
    @foreach($patients as $id => $name)
        <option value="{{$id}}" class="form-control">{{$name}}</option>
    @endforeach
</select>
// `upload` Controller action
'patient_id' => ['required', Rule::exists('patients', 'id')]
Mim's avatar
Level 1

@tykus SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in 'where clause' (SQL: select count(*) as aggregate from patients where patient_id = 1)

thats the error i got after using that

tykus's avatar
tykus
Best Answer
Level 104

@Mim typo:

'patient_id' => ['required', Rule::exists('patients', 'id')]
tykus's avatar

@Mim do you understand the changes that were made here?

Tray2's avatar

@Mim The patient table should not contain a patient_id, it should contain an id and a user_id since you decided to store the same information in two places.

tykus's avatar

@Tray2 it doesn't the query was incorrect because of the exists Rule being written incorrectly.

Mim's avatar
Level 1

@Tray2 the patients table doesn't have a patient_id , the bed_assigns table rather have a patient_id because patient is a foreign key there

Mim's avatar
Level 1

@tykus but the problem is now the patient name doesn't display, although the other entity shows

tykus's avatar

@Mim what does the patient relationship look like on the BedAssign model?

Mim's avatar
Level 1

@tykus

   public function patient() {
      return $this->belongsTo(Patient::class);
  }

Please or to participate in this conversation.