Categories
Learning Tech

Laravel; How to pull existing records on select change event using session type and date passed to dynamic web route in Laravel?

Welcome to Post,

Lets learn how to do the thing in the question, assuming you have basic or advance knowledge or learning something of your own to understand the things or you have got stuck due to simple issues of mistakes.

Using jQuery, HTML, Laravel Blade, Controller, Web Route and AJAX.

Lets begin.

Lets we talk first and defined about the HTML form field and its jQuery functionality. (I will be skipping middle parts of the code what it does and how its populated for the form fields ) and we will be using two fields here to show the example : session_date and session_type, which would look like below in the html code. session_type values would be morning, evening and so on for the day session.

<div class="row">
                            
                            <div class="form-group col-md-3">
                                <label for="session_date">Session Date:<sup>*</sup> </label>
                                <input type="date" name="session_date" id="session_date" class="form-control jsSessionDate" 
                                    value="{{ old('session_date', now()->format('Y-m-d'))}}"    
                                />
                                <!--<div class="text-end"><small class="text-muted"></small></div>-->
                            </div>
                            
                            <div class="form-group col-md-3">
                                <!--<input type="hidden" name="session_type" class="form-control hide mt-1" value="morning" />-->
                                                
                                <label for="session_type">Select Session Type:<sup>*</sup></label>
                                <select name="session_type" id="session_type" class="form-select text-capitalize jsSessionTypeChange" 
                                    >
                                    @foreach ($sessions_types as $ddSession)
                                        <option value="{{ $ddSession }}" {{old('session_type') ==  $ddSession ? 'selected' : ''}}>{{ $ddSession }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

Once we have the basic fields ready in HTML side we can write the jQuery side of it to fetch the records and make the AJAX call our server side of Laravel Controller.

$(document).on('change', '.jsSessionTypeChange', function(e) {
                const { value } = e.target;
                const sessionDateVal = $('.jsSessionDate').val();
                console.log(value)
                
                if(!value) return;
                
                const $this = $(this);
                const payload = { 
                    _token:  $('meta[name="csrf-token"]').attr('content'),
                };
                
                const sessionType = value || 'morning';
                const sessionDate = sessionDateVal ?? {{now()->format('Y-m-d')}};
                
                const baseUrl = window.location.origin+'/ams';
                const url = `${baseUrl}/existing-session/${sessionType}/${sessionDate}`;
                    
                console.log({url, sessionType, sessionDate});
                
                $.ajax({
                    url,
        			type: "get",
        			cache: false,
                }).done(function(resp) {
                    if(resp) {
                          console.log({
                              resp
                          })
                    }
                   })
                   .fail(function(err) {
                     console.error("Existing session fetch  error: ", err, err.responseText);
                });
            });

//IGNORE THE CONSOLE LOGS

Here, I am getting values from date filed and select dropdown for session type, on session type change event forming server side api end point url, not using PHP Laravel Blade example with javascript is its very difficult for blade to understand passing dynamic javascript variable to it.

Because PHP code executed on the page load even we defining the blade {{ }} in onChange event function scope. so its looks for that variable and its goes undefined , tried otherways around the then get the error from rotue generation syntax as route is forming dynamically.

So I thought to set back with simple Javascript code for forming the base URL and its endpoint for ajax call to happen.

Giving you context what I said above and for what thing i was trying to do in Javascript of code using Laravel Blade syntax, which didn’t worked out simply.

Try 1:

const type = value || 'morning';
const url = "{{ route('existing-session', ['sessionType' => '${type}']) }}";

$.ajax({
    url: url,
    // ... rest of your AJAX configuration
});

Try 2:
const type = value || 'morning';
const url = "{{ route('existing-session', ['sessionType' => '${type}']) }}";

$.ajax({
    url: url,
    // ... rest of your AJAX configuration
});

Try 3: Finally
const type = value || 'morning';
const baseUrl = window.location.origin;
const url = `${baseUrl}/existing-session/${type}`;

$.ajax({
    url: url,
    // ... rest of your AJAX configuration
});

Okay, now our HTML and JQUERY code is ready, lets quickly add in to our routes/web.php, dynamic route for ajax to work!

// To get existing Session on Create View
Route::get('existing-session/{sessionType}/{sessionDate}', [App\Http\Controllers\EventSessionController::class, 'existingSession'])->name('existing-session');

Now Finally in Controller side, write as method to get the sessionType and sessionDate and pull it the data from database and return as json response to the ajax call. Then we are good to finish!

public function existingSession($sessionType, $sessionDate) {
    // Fetch session with today's date and specific session type

    if($sessionType  !== '' && $sessionDate !== '') {
        $existingSession = EventSession::with(['members', 'samagams'])->where('session_type', $sessionType)
        ->whereDate('session_date', $sessionDate ?? now()->format('Y-m-d'))
        ->first();

        $response = ["data" => $existingSession, "success" => true, "error" => false, "message" => $sessionType." session found for date ".$sessionDate];
    } else {
        $response = [ "data" => null, "success" => false, "error" => true, "message" => "No existing session found for given session type ". $sessionType ." and date " .$sessionDate];
    }

    return response()->json($response);
}

Voila, your quick AJAX example ready in Laravel with pulling in data with dynamic passing of data to the GET route.

Hope this gives you hints, idea how to do the things in PHP Laravel.

Thanks for reading the post and happy learning!