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
Learning Learning Tech

How to build Android APK/apk from command line interface on windows/mac?

Hello,

If you are looking for, to build or generate the android apk file (in your capacitor project) directly from the command line rather then opening Android Studio and building up.

I will share few steps and challenges face to build android apk from CLI on windows and also would share below the mac version of command line code too incase you are mac user.

First step first,

Before running the CLI command which I will be sharing below, we make sure we add the two things under Environment variables of windows system.

  • Java JDK or JAVA_HOME path
  • zipalign if not set or when you run command your cli throw error not zipalign command (so we need it too in the PATH variable of the windows system)
See last two entries in the image above, second entry were zipalign.exe is available under your real Android Studio folder.

Next, just try out these command you will be good to go

Windows CLI command for Android APK release build
cd android && 
gradlew.bat assembleRelease && 
cd app/build/outputs/apk/release &&
jarsigner -keystore YOUR_KEYSTORE_PATH -storepass YOUR_KEYSTORE_PASS app-release-unsigned.apk YOUR_KEYSTORE_ALIAS &&
zipalign 4 app-release-unsigned.apk app-release.apk

In Code above, note we are using gradlew.bat which is important to note for window users reset is same for MAC command too (didn’t tested on mac, channel of command source from the post), result would working for me on windows!

Note the date and time of output (compare to post date and time, I renamed the file to mdw-app-release.apk for use)
Mac CLI command for Android APK release build
cd android && 
./gradlew assembleRelease && 
cd app/build/outputs/apk/release &&
jarsigner -keystore YOUR_KEYSTORE_PATH -storepass YOUR_KEYSTORE_PASS app-release-unsigned.apk YOUR_KEYSTORE_ALIAS &&
zipalign 4 app-release-unsigned.apk app-release.apk

If you like to generate for debug just changed assembleRelease to assembleDebug and change the file names accordingly, from release to debug or whatever names you would like to prefix or suffix.

Hope this gives ideas and info for the challenge you might facing.

Happy Learning & Thanks for visit.

Categories
Javascript Learning Tech

What is forwardRef and how its helps in react?

Hello, lets quickly take a review on React forwardRef, what it in actual,

In React, the forwardRef function is a utility that allows you to pass a ref through a component to one of its children. It’s commonly used when you need to access the underlying DOM node or React component instance of a child component from the parent component.

When you create a component using functional components in React, you can use the useRef hook to create a ref object. This ref object can then be passed as a prop to child components. However, when you pass the ref as a prop to a child component, React does not automatically pass it down to the underlying DOM element or custom component. This is where forwardRef comes into play.

By using forwardRef, you can create a component that accepts a ref and forwards it to one of its children. Here’s an example:

const ChildComp = React.forwardRef((props, ref) => {
  // Use the ref object to access the underlying DOM node or component instance
  return <input ref={ref} />;
});

const ParentComp = () => {
  const inputRef = React.useRef(null);

  const handleClick = () => {
    // Access the input element using the ref
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <ChildComponent ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

In the example above, the ChildComponent uses forwardRef to forward the ref prop to the <input> element. In the ParentComponent, a ref is created using the useRef hook and passed to ChildComponent using the ref prop. This allows the ParentComponent to access the input element and call the focus method when the button is clicked.

By using forwardRef, helps to bridge the gap between functional components and the imperative DOM or component operations that sometimes require direct access to child component element.

Note here we are accessing child’s component dom node not child component here as ref object, i.e can be consider as subtle difference to understand for our mind.

Hope this helps to clear out the basic concept behind using forwardRef in React.

Happy Learning!

Categories
Learning

How to use “where” with “pluck” in laravel?

Hello,

Here is the quick solution:

$categoryId = ProductCategory::where('id',$id)->pluck('categoryId')[0];
$parentId = ProductCategory::where('id',$id)->pluck('parentId')[0];
        
print_r($categoryId);
print_r($parentId);
        

Plucking it array index 0 as the return from pluck is array based so indexing gives us the value for the particular column you need to pluck from table.

Hope this will give you an idea or solution to your problem.

Happy Learning, Happy Learning Laravel!

Categories
Learning

How to calculate the costing of grams from per kg weight?

For the simple question here is the simple answer:

as we know 1kg = 1000 grams

Formular for easy getting grams rate from per kg is looks like:

So g grams is g/1000 kg and the price will be g/1000 * r (rupees/kg)
or
rupees/kg= g*r/1000

For example to calculate the rate of 100 grams from per kg.

Let say we have some wheat item whose rate is 1 kg = 20 rupees and we have to calculate the rate for 100 grams wheat?
100/1000 * 20 = 2 rupees
or
100 * 20/1000 = 2 rupees

Hope this solves our understanings.

Happy learning!