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!

Categories
Blog Learning Tech

How to update PHP version on shared host website or under cpanel?

Hello welcome to the post!

Look for “MultiPHP Manager” in Cpanel search bar or on home page of your Cpanel after login.

Reference screenshot

It will show you your current System PHP version and below option to change the setting for PHP version as required.

From dropdown menu like on right select the version of PHP you needed and apply, before that not to forget to select the list of domains, if you have multiple websites or subdomains to apply the latest PHP version.

Hope this solves your issue to the fastest when composer dependencies gives error like below when you trying to test small issue of your website.

{ "message": "syntax error, unexpected token \")\"", "exception": "ParseError", "file": "/home4/ininszp2/abclar/vendor/symfony/css-selector/XPath/Extension/NodeExtension.php", "line": 68, "trace": [ { "file": "/home4/ininszp2/abclar/vendor/composer/ClassLoader.php", "line": 428, "function": "Composer\\Autoload\\includeFile" }, { "file": "/home4/ininszp2/abclar/vendor/symfony/css-selector/XPath/Translator.php", "line": 56, "function": "loadClass", "class": "Composer\\Autoload\\ClassLoader", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/symfony/css-selector/CssSelectorConverter.php", "line": 40, "function": "__construct", "class": "Symfony\\Component\\CssSelector\\XPath\\Translator", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php", "line": 19, "function": "__construct", "class": "Symfony\\Component\\CssSelector\\CssSelectorConverter", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/laravel/framework/src/Illuminate/Mail/Markdown.php", "line": 73, "function": "__construct", "class": "TijsVerkoyen\\CssToInlineStyles\\CssToInlineStyles", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php", "line": 309, "function": "render", "class":

Thanks for reading and Happy learning!

Categories
Learning Tech

If Laravel created_at or updated_at SQL error, what to do?

Hello, welcome to my random post.

Quick to elaborate, what I was doing what I found it right to fix.

I am building an application with Laravel and I was facing with this below error:

// Illuminate\Database\QueryException
// SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘created_at’ in ‘order clause’ (SQL: select * from food order by created_at desc limit 10 offset 0)

The cause of such error is when we don’t have column name in our database table, as to be created_at and updated_at.

In my case I was following camel case styles column names in database table: createdAt and upatedAt, so it was cause of this error and further to it, as I were looking for the solution and found that I am using latest() method to fetch the code (which is not allowed when don’t have laravel style column names of our database table), example like below

$food = Food::latest()->paginate(10);

so we have to have a columns names with created_at and updated_at in our database table, if want to use latest() method

Otherwise we need to change the method to orderBy() or first() method to fetch the result from database, also remember to add arguments to orderBy method/function like below, otherwise you would face again error of arguments need to be passed.

$food = Food::orderBy('createdAt', 'desc')->paginate(10);

Thanks for reading and happy coding. Have a nice day 🙂