Categories
Javascript Learning Learning Tech

How I have resolve, Module not found, Can’t resolve ‘optimism’

Hello welcome to this post.

Straight to the answer, here it goes:

Tried running first nextjs app

λ npm run dev

> developfe-dev@1.0.0 dev
> next

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from F:\windows\developapp\code\.env
info  - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
error - ./node_modules/@apollo/client/cache/core/cache.js:1:0
Module not found: Can't resolve 'optimism'

Import trace for requested module:
./node_modules\@apollo\client\cache\index.js
./node_modules\@apollo\client\core\index.js
./node_modules\@apollo\client\index.js
./pages\_app.js

https://nextjs.org/docs/messages/module-not-found
Terminate batch job (Y/N)?
^C

Next reinstalled package



F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm i @apollo/client@latest --save

added 9 packages, changed 1 package, and audited 1119 packages in 13s

90 packages are looking for funding
  run `npm fund` for details

6 vulnerabilities (4 low, 2 high)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.

Then run again! boom!

F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm run dev

> developfe-dev@1.0.0 dev
> next

ready – started server on 0.0.0.0:3000, url: http://localhost:3000
info – Loaded env from F:\windows\developapp\code\.env
info – Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
event – compiled successfully

So, here is the simple answer to the question.

Thanks for reading and Happy Learning!

Categories
Learning

How to add multiple email address to sendgrid nodejs code?

Hello there, welcome to my random question post.

I was facing small issue to add multiple address to bcc to the sendgrid nodejs example :

What I was tried to do ( which was wrong in accepting as sendgrid bcc parameters value)

let testAccount = {
        emailSubject: subjectMsg,
        emailFrom: `Application <${process.env.CESEmailFrom}>`,
        emailTo: email || process.env.OWNER_TO_EMAIL_ADDRESS,
        emailBcc: process.env.OWNER_EMAIL_ADDRESS //note here
 };

(this is just a payload I am preparing to pass to seng-grid function), process.env.OWNER_EMAIL_ADDRESS was holding values like : email1@testdomain.com, email2@testdomain.com so which is incorrect to pass a comma separated string value.

Instead, we just need to tweak a little at the same bcc, line to pass it as Javascript Array value. Here is the example of working code (note the bcc line in the code below):

let testAccount = {
        //user: process.env.CESUsername,
        //pass: process.env.CESPassword,
        emailSubject: subjectMsg,
        emailFrom: `Kitchen Anak <${process.env.CESEmailFrom}>`,
        emailTo: email || process.env.OWNER_TO_EMAIL_ADDRESS,
        emailBcc: process.env.OWNER_EMAIL_ADDRESS && process.env.OWNER_EMAIL_ADDRESS.split(',') || '',
    };

Using javascript split function, I was able pass it as a array, isn’t that simple? 🙂

Facing other error related to sendgrid bcc option

Along this, I have also then faced error after fixing above, still on my Vercel deployment code, then which was related to sendGrid bcc parameter for multiple email address.

According to sendGrid documentation we should have unique email address for ‘to’, ‘cc’ and ‘bcc’ options while sending email, in my case I was having ‘bcc’ email address set in at ‘to’ option.

Hence, so creating a duplicate error log at API level of code. (attaching screenshot of error occurred) and then fixed it by removing or keeping all the ‘to’ and ‘bcc’ parameters unique! Volia, that simple 🙂

Log error due to sendgrid bcc email address should be unique.

Result after correcting email address successful.

Successful email send log!

Thanks for visiting & Happy Learning!

Categories
Learning

How to pass multiple data to Laravel compact method from Controller to view blade?

Hello there, welcome to the random post.

Ok, I was looking to add multiple data with compact method in Laravel from controller, here is quick example solution how I did it.

My initial code was like below in one of the controller method I was working on, skipping writing whole function code, posting down what was inside the function and how I turned it out to after on my question search on Google.

Example 1:

(returning single category data to the category.edit.blade.php)

$category = Category::findOrFail($id);
return view('category.edit', compact('category','gvd', 'parentCategories'));
Example 2:

(passing multiple data)

$category = Category::findOrFail($id);
$gvd = $this->generalViewData; //this controller property returning array data to $gvd variable, then passing to compact below

$allParentCategoryIds = Category::select('parentId')->pluck('parentId');
            
// Looping on data
foreach ($allParentCategoryIds as $pid) {
      $parentCategories = Category::select('name', 'categoryId')->where('categoryId', '=', $pid)->get();
 }

return view('category.edit', compact('category','gvd', 'parentCategories')); 

Here you could also note in case if come down here by searching about how to loop controller side in laravel? so from code example you could get the answer.

I am using Laravel 8 for current development.

Hope you find it easy and handful.

Thanks for reading & Happy Learning!

Categories
Blog Learning Tech

How to use if else conditions in laravel blade view or for html code?

Hello, thanks for checking out here!

Here is the quick and short answer with the examples:

Example 1
<img src="@if($category->image) {{ ($category->image) }} @else {{'https://via.placeholder.com/50'}} @endif" alt="{{ $category->name}}" width="50" height="50" />

This is what I was looking for my part of development laravel! same you can achieve for the html blocks: here is the example:

Example 2
@if ($message = Session::get('success'))
    <script>
      if(window.toastr)
          toastr["success"]("{{ session()->get('success') }}"); 
    </script> 
@endif
Example 3
@if ($message = Session::get('success'))
  <div class="alert alert-success">
     session()->get('success')
  </div>
@endif

To use elseif just use following syntax @elseif(condition) along your code or between.

Thanks & Happy learning Laravel!

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 🙂

Categories
Blog Javascript Learning Tech

Taking Random Angular Quiz, Got Results – Jat

Hello, welcome and thanks to visit here to read my this short random post.

I was looking to take a random angular quiz to test my ability on Angular after a year around how much I remember about it, as because currently I mostly working with React and GraphQl, ApolloServer and Client and loving NextJS.

So after searching on Google, I landed up over this blog (here) (not an intention to use the link wrongly here), I took the Quiz and here is my result below with the image.

I too read some articles in the morning and look for tips and tricks on Angular so I can heads up well for the next interview on Angular 🙂

So I tried Quiz from the above blog link and here it is:

Question ah? How it could prove its my result, you can check on the full screenshot from my computer currently and tiny image up on the top corner and below on the Task bar with Chrome Active.

JAT-angular-quiz-result-with-rest-of-the-WORLD!

That’s all I would like to share with you all.

Thanks for reading and visiting. Have a great time and year’s ahead!

P.S. yes I forgot to mention, I am next going to take up more quiz and sharp my Angular blade more finer as possible as to be! Happy Learnings!

Categories
Uncategorized

laravel 8 tips and tricks and how i did it

In day of my learning today on PHP Laravel 8 building application from scratch with google search help!

I am not a good write I am just posting random solutions of my finding in building Laravel application from scratch!. (I don’t claim anybody solutions to mine, this is suggest as a side support. Thanks!)

How to create mailable class in Laravel using version 8?

php artisan make:mail OrderStatusUpdate --markdown=emails.orders.statusupdated 

I have used –markdown option to automatically general email template file for me under resources/views/emails/orders/statusupdated.blade.php file to have template ready on fly to start working!

It will create OrderStatusUpdate class file under Mail folder under app/Mail folder automatically!

How to create custom route to view the email template in browser before sending any emails for test?

Route::get('/mailable', function () {
     $msg = 'Order ID TEST! updated successfully!';
    return new App\Mail\OrderStatusUpdated($msg);
});

This lines of code you can add to web.php under /routes folder which you can easily test out the template by directly visiting to your website or Laravel deployed path for example: youwebsite.com/mailable or yourwebsite.com/somefoldername/mailable like so!

How to pass data as array to mailable class file from Laravel Controller file?

public function handlUpdateOrderStatus(Request $request) {
        
        try {
            $query = Order::where('orderId',$request->orderId)->update(['status' => $request->value, 'updatedAt' => now()]);
            
            // create response result
            if($query) {
                
                $msg = 'Order # '.$request->orderNumber.' (OrderID:'.$request->orderId. ') updated to '. $this->orderStatusList[$request->value] .' successfully!';
                
                // Shoot email
                Mail::to( env('MAIL_REPLY_TO_ADDRESS'), env('MAIL_FROM_NAME_ADMIN') )->send(new OrderStatusUpdated(['msg'=> $msg, 'orderNumber' => $request->orderNumber]));
                
                return ["success" => true, 'message'=> $msg];
                
            } else {
                
                return [
                    "error" => true,
                    'message'=> "Error in updating status, please try again/later."];
            }
        }
        catch(\Exception $e){
            // Get error here
            echo "Email test exception or query exception OrderController!";
        }
        
    }

This function in my OrderController.php file is actually to update the DB record and then shoot email, so here also wanted to pass data to mailable class instance as an array, this is how above, I have passed as array data and will retrieve in the mailable class file (in following next question or block below this one Queue1)

While I was testing this code I came up to another error of issue (Swift_TransportException Connection to mail.xxxxx.com:465 Timed Out), I thought error was to parameter to Mail:: facade function or line, but, syntactically what I followed was correct so no change there.

Then I searched over this and came to find, in .env file MAIL_ENCRYPTION set to null, before setting anything there, I was looking under config/mail.php for default settings where I have tried to add ssl value to encryption and then testes found to be working. Then I have changed the same under .env file MAIL_ENCRYPTION=ssl which was set to null by default of installation of Laravel application and commented or reverted back config/mail.php code and then voila, it worked like charm! (continue to complete Queue1)

How to retrieve data as array passed to mailable instance from Laravel controller and pass down to Laravel email template?


namespace App\Mail;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderStatusUpdated extends Mailable implements ShouldQueue {
public $details;
    /**
     * Create a new message instance.
     *
     * @param  \App\Models\Order  $order
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Order # '. $this->details['orderNumber'] .' Status Updated')
                ->markdown('emails.orders.statusupdated');
    }
}

Here is the block of code fetching/retrieving data in public variable which is pass down to this mailable class file instance in controller as we discussed above in last question and accessing the same under build function of this mailable class file.

I have also implemented this class file with ShouldQueue following Laravel guide on mail.

I have also added following public property: $afterCommit : true, but got below error:

App\Mail\OrderStatusUpdated and Illuminate\Bus\Queueable define the same property ($afterCommit) in the composition of App\Mail\OrderStatusUpdated. However, the definition differs and is considered incompatible. Class was composed

I have remove it as it was not troubling me even if I don’t have it, I guess this be might the case for lower version of Laravel’s than 8.

How to finally consume the data passed in Laravel email template passed down via its mailable class?

@component('mail::message')

# Order Status

Order # {{ $details['orderNumber'] }} 
{{ $details['msg'] }}

@component('mail::button', ['url' => ''])
View Order
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

Finally this is how the template rendered and worked for me! Hope it will work for you too!

Beside this I have also added Laravel Customize components which I will be implementing/using further in the application development. Keep you posted in case I can up with issues in its implementations.

Thanks for visiting & reading the post. Hope it help you in your way of building applications.

Categories
Learning Tech Uncategorized

Tips & Tricks how they do it in laravel, now we can too do it

In day of my learning on PHP Laravel building application from scratch with googling help and docs.

How to foreach or for loop on html select input or dropdown field in laravel blade file

<select class="custom-select jsUpdateOrderStatus"   id="ddlTodayOrdersStatus{{$loop->index}}"          name="ddlTodayOrdersStatus{{$loop->index}}"
data-orderid="{{$order->orderId}}" >
     @foreach ($orderStatus as $status)
         <option value="{{$loop->index}}" 
         {{$order->status === $loop->index ? "selected" : "" }}"  
         data-loopIndex=" {{$loop->index}}">{{$status}}</option>
     @endforeach
</select>

To Note : $order is passed as dynamic object to the blade file in which this code will be implemented, its for just example to explain. (hint: make sure your laravel directive/code are intended properly in blade files, otherwise it might throw error to the view)

How to add format date to html in laravel blade file

<p>Example code 1: </p>
<p>{{ Carbon\Carbon::parse($order->createdAt)->format('d-M-Y H:i:s') }}</p>

<p>Example code 2:</p>
<p>{{ Carbon\Carbon::parse($order->createdAt)->diffForhumans() }}</p>

Using ajax script code in laravel blade file (just for ajax javascript syntax example):

<script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    </script>
    <script>
        // alert('javascripts section loaded test!');
        $(function() {
            // alert("jQuery works test!") ;
            
           $('.jsUpdateOrderStatus').change(function(e) {
              
            //   console.log('change fired! ');
              
              const curTargetEle = $(e.target);
              const value = curTargetEle.val();
              const orderId = curTargetEle.data('orderid');
              const curDDLUpdatedText = curTargetEle.find('option:selected').text();
              const curDDLUpdatedTextInital = curDDLUpdatedText.substring(0,1);
              const curSiblingLabelEle = curTargetEle.siblings('.input-group-prepend').find('label');
              
              if(!value || value === "") {
                  console.error('value not passed'); 
                  return;
              }
              
              
            //perform AJAX call
            // console.log('jsUpdateOrderStatus fired ', value, orderId);
            
            const payload = { 
                _token:  $('meta[name="csrf-token"]').attr('content'),
                orderId,
                value
            };
            
            if(confirm("Are you sure, you want to change order status?")) {
                $.ajax({
                    url: "{{route('update-order-status')}}",
        			type: "post",
        			cache: false,
                    data: payload,
                    // dataType: 'json',
                    // data:"{id:$(this).data('fid')}"
                }).done(function(resp) {
                  
                  //success
                  console.log("Order status success response: ", {resp});
                  
                  if(resp && resp.success) {
                      
                      curSiblingLabelEle.text(curDDLUpdatedTextInital);
                      
                      const msg = `Order ${orderId} set to ${curDDLUpdatedText} succesfully`;
                      toastr["success"](msg || resp.message);
                      
                      location.reload();
                  }
                  
                   }).fail(function(err){
                  //failure
                   toastr["error"](err.responseText || err.status);
                  console.error("Order status error response: ", {err});
                });
            }
           });
               
        });
    </script>


To note: here some ccode you won't find relevant to your need, you may remove them, this is to show a general idea of ajax JavaScript side of implementation on some html input/select field change event to dynamically handle request. 

Conditionality showing html code in Laravel blade file using Laravel @if directive

<ul class="nav nav-tabs" id="myTab" role="tablist
    @if (count($todayOrders))
      <li class="nav-item" role="presentation">
        <a class="nav-link active" id="todayorder-tab" data-toggle="tab" href="#todayorder" role="tab" aria-controls="todayorder" aria-selected="true">Today's Order <sup class="badge badge-pill badge-dark">{{count($todayOrders)}}</sup></a>
      </li>
    @endif
  <li class="nav-item" role="presentation">
    <a class="nav-link  @if (!count($todayOrders)) active @endif " id="allorder-tab" 
        data-toggle="tab" href="#allorder" role="tab" aria-controls="allorder" aria-selected="false">All Orders <sup class="badge badge-pill badge-dark">{{count($orders)}}</sup></a>
  </li>
</ul>

To note: this is just example you can do the same with any other kind of html codes.

Conditionality setting class to html tag using Laravel @if directive

class="nav-link  @if (!count($todayOrders)) active @endif " 

HTML code example:
<a class="nav-link active" id="todayorder-tab" data-toggle="tab" href="#todayorder" role="tab" aria-controls="todayorder" aria-selected="true">Today's Order <sup class="badge badge-pill badge-dark">{{count($todayOrders)}}</sup></a>

Thanks for visiting & reading this post. Hope it help you in your way of building applications.

Categories
Javascript Learning Tech

How to add Buy me coffee script dynamically into React application or Javascript

Stumble upon in the search of adding Buy me coffee script into react application land to the following wonderful hook solution to add script to react on stack overflow here

I will also add up here the update code of stack overflow which helped in the solution (for incase above shared link will be changed in future, and all the code credit is to the author of stack overflow user)

Update:
Now that we have hooks, a better approach might be to use useEffect like so:

useEffect(() => {
  const script = document.createElement('script');

  script.src = "https://use.typekit.net/foobar.js";
  script.async = true;

  document.body.appendChild(script);

  return () => {
    document.body.removeChild(script);
  }
}, []);
Which makes it a great candidate for a custom hook (eg: hooks/useScript.js):

import { useEffect } from 'react';

const useScript = url => {
  useEffect(() => {
    const script = document.createElement('script');

    script.src = url;
    script.async = true;

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};

export default useScript;
Which can be used like so:

import useScript from 'hooks/useScript';

const MyComponent = props => {
  useScript('https://use.typekit.net/foobar.js');

  // rest of your component
}

Solution, I have added on top a ‘config’ param to the useScript function for easy BMC Buy me coffee widget attributes to get added to script object dynamically:

const useScript = (url, config = null) => {

  useEffect(() => {
    const script = document.createElement("script");

    script.src = url;
    script.async = true;

    if (config && Object.keys(config).length) {
      for (let key in config) {
        script.setAttribute(key, config[key]);
      }
    }

    // console.log(script);
    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, [url]);
};

export default useScript;

Boom!

Categories
Javascript Learning Tech

How to play with Graphql playground for Mutation’s?

Okay, well I was also looking for solution to this and here it is:

Mutation example of adding employee using Graphql Playground, most important step after you have added the code below to playground tab window:

# Write your query or mutation here
mutation AddEmployee(
  $name: String!,
  $phoneNumber: String!,
  $email: String! ,
  $designation: String,
  $image: String) {
    addEmployee(employee: 
      { name: $name, phoneNumber:$phoneNumber, email: $email, designation: $designation, image:$image },
    ) 
      {
        emp_id
        name
      }
    
}

You need to add your JSON payload to QUERY VARIABLES tab window (which is closed by default on below main playground window, without this input payload you will not see results, but error. (keep an eye on here while you make mutation test in graphql playground)

grapql-mutation-example-with-query-variable-input-parameters

Thanks for visiting!