Updating database records using AJAX in Laravel

In my project using Laravel, I need to update the status of a patient when they schedule an appointment with a doctor. The patient can have three statuses: Accept, Waiting (automatically set when the patient selects a date and time), Not Accept. However, when I click on the active button, nothing changes in the database.

Here is the controller for changing the status:

public function changeStatus(Request $request)
{
    $user = rdv::where('IDP', $request->input('IDP'))->get();
    
    if (count($user) > 0) {
        if ($user->Etat_de_rdv == 'en_attente') {
            $user->Etat_de_rdv = 'Accepté';
        } else {
            $user->Etat_de_rdv = 'Reservé';
        }

        $user->Etat_de_rdv = $request->input('status');
        $user->save();

        return response()->json(['success' => 'Status changed successfully']);
    }
}

Below is the script:

  <script>

    $('.toggle-class').change(function () {
        var status = $(this).prop('checked') ? 'Accepted' : 'Busy';
        var id = $(this).data('IDP');
        console.log(id);
        console.log(status);
        $.ajax({
            type: "get",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: 'changeStatus',
            data: {
                Etat_de_rdv: status,
                IDP: id
            },
            success: function (data) {
                console.log(data.success);
            }
        });
    });
</script>

This view displays all appointments seen by the doctor:

<h3> Your patients :</h3>
@foreach($pat as $lo)
    @if ($lo->IDD== $med->ID)
        <div class="admin">
            <div class="info">
                <h3> {{ $lo->Nom_et_prénom  }} </h3>
                <p>{{ $lo->Numéro_de_téléphone }}</p>
                <p>{{ $lo->date}}</p>
                <p>{{ $lo->time }}</p>
                <input data-id="{{$lo->IPD}}" class="toggle-class" type="checkbox" data-onstyle="success"
                       data-offstyle="danger" data-toggle="toggle" data-on="Accepted"
                       data-off="Busy" {{ $lo->Etat_de_rdv ? 'checked' : '' }}>
            </div>
        </div>
    @endif
@endforeach 

*rdv means: appointment table *IDP: Patient's ID

Answer №1

->get(); retrieves a collection, not an array. Therefore, it is recommended to use $user->count() > 0 instead.

Update: ->get() fetches a collection of objects. Hence, you cannot simply use

$user->Etat_de_rdv == en_attente
. There are two approaches to solving this dilemma.

  1. If you are confident that the IDP condition will always return a single item, then consider using ->first() in place of ->get(), eliminating the need to modify the inner if statement.

  2. In case there will be multiple users, start by renaming the variable to $users and iterate over it like this:

    $foreach($users as $user) { // your current code... }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a distinct foreign key constraint in DB2

I have a question about the structure of two simplified tables: create table CASE_INSTANCE (id int not null, stage_id int not null, primary key (id, stage_id)); create table SAMPLE (id int not null, case_id int not null); My goal is to create a ...

What are the steps to retrieve raw messages from Gmail using Node.js?

I'm attempting to retrieve the complete email message data, including body content, using the raw format option specified in the gmail api reference. Unfortunately, it doesn't appear to be functioning correctly. Here is the code I'm using: ...

Sending data from JQuery to a PHP file

My JQGrid is set up to display bookings with a double click event: ondblClickRow: function(rowid) { rowData = $("#bookings").getRowData(rowid); var brData = rowData['bookref']; getGridRow(brData); }, The data then gets passed to the ...

Uninstalling an Element Using jQuery

There is a requirement to dynamically insert city names into the input field with the ID citiesList. If the value of the input field is empty and the user clicks on the cancel button, then the input should be deleted. However, upon clicking the edit but ...

Extracting properties from an object in NodeJS: a step-by-step guide

I'm struggling to access a specific property within an object using a GET request in NodeJs (with express). Here is the object I am working with: const friends = [{ id: 1, name: "laura", country: "England", language ...

retrieve a string from a given array

I need to retrieve a string from an array in vue and display it on the screen. Here is the method I created for this purpose: displayFixturesName() { const result = this.selectedFixture.toString(); document.getElementById(& ...

Utilizing Laravel to structure nested JSON responses

I am trying to generate a JSON structure similar to this example in my API controller within Laravel. Below is the snippet of the controller: $data = []; foreach ($products as $p => $product) { // Code logic here } if (count($data) == 1) { $da ...

use ajax to selectively update specific element

Seeking assistance with updating the cart page using ajax when adjusting the quantity of products. The view logic seems to be functioning correctly. The issue arises when targeting the class "ajax_updater". Upon clicking the quantity buttons, ajax succes ...

Button in HTML not functioning as expected

I have 3 different files that are crucial for my webpage to function properly: index.html: <html> <head> </head> <body> <h1>Webpage</h1> <p id = "text">Hello world!</p> <button oncl ...

Selecting many objects using jQuery Selector

I currently have a navigation bar that is created using PHP-generated HTML like this: <ul> <div class="container"><button type="button" name="1" class="delButton" alt="Delete"></button></div> <a href="/" alt="Home">Home ...

No changes in SQLite filesize were observed even after dropping a table

My SQLite Database is 4MB in size. I executed the "drop table name;" command and confirmed in SQLite Manager that the table name was dropped successfully. Despite dropping the table, the filesize of the database remains the same at 4MB. When I open the Dat ...

Ways to retrieve the most recent entry per group and verify if it is the sole entry?

As per the insights shared in this response, the optimal approach to retrieve the most recent record within each group can be achieved by utilizing the following query: SELECT m1.* FROM messages m1 LEFT JOIN messages m2 ON (m1.name = m2.name AND m1.id &l ...

Using Laravel and vue.js to convert values into an array

I am currently utilizing vue.js within my Laravel project. Within the project, I have three tables: Article Location article_location (pivot table) I am looking to convert location articles into JSON format so that I can pass it to vue. How should I ...

Filtering in JavaScript can be efficiently done by checking for multiple values and only including them if they are not

In my current coding challenge, I am attempting to create a filter that considers multiple values and only acts on them if they are not empty. Take the following example: jobsTracked = [ { "company": "Company1", ...

Node-red occasionally crashes and the JSON output may unexpectedly return HTML content

Having some trouble with my node-red crashing several times a day. I suspect that one of the issues may be related to an http request I am making. I'm trying to retrieve JSON data from a webpage, but sometimes I encounter errors in the log indicating ...

Attempting to send a request to a PHP script using Ajax, however, there is no

I have implemented an Ajax call to a php script named save_tags.php, the contents of which are as follows: $id = $_POST['id']; $name = $_POST['name']; $type = $_POST['type']; $tags = json_decode(stripslash ...

Implementing the History API to dynamically load content into a div using Ajax

On my WordPress site, I have post content that loads into a div using AJAX when a user clicks on it. Now, I'd like to update the URL for the current post without using hashes. How can I achieve this with my JavaScript? JavaScript: jQuery(docum ...

Finding the count of childNodes within a div using Selenium

I've been grappling with this issue for the majority of today; I'm trying to tally up the number of childNodes within a parent div. It's essentially mimicking a list where each childNode represents a row that I want to count. The HTML struct ...

Transferring the jQuery modal variable value to a PHP script

I feel like I might be making this more complex than it needs to be, but I'm working on a jQuery modal that communicates with a PHP file. The PHP file contains the form and validation logic, and the modal includes this file. The modal is triggered by ...

Changing the className of buttons based on user interaction

I'm looking to create a function in React JS that changes the button's color when clicked. Specifically, I want the color of the button to change upon clicking. I have attempted to achieve this using the following code: {"classname" i ...