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!

Categories
Uncategorized

PHP sql returns space in email address while query with json post data using post method

I have faced a scenario where I was getting space error in the email address before @ symbol in email address, as I were making simple post request to verify the login.
Json post object sample:

{
	"email": "test@example.com",
  	"password" : "test123"
}

Was returning error in response of like test @example.com so the email address was not getting verified in the database.

Upon google came to following stack overflow result for solution but not satisfy with the approach of replacing single quote again and forcing self to post the email address with single quote in post request, which is obviously not a good solution. (later I have commented on the result page with my solution 😉 )
Simply I did this at query level and it resolve the space issue in the email address while query in database.

$query = "SELECT * FROM 
            " . $this->table_name . " 
            WHERE email =  '".$this->email."'  LIMIT 0,1";

Finally, wrapped the email address variable with the single quotes, and resolved the issue of space before @ symbol.

Hope this solution and result page will save your day!

Categories
Uncategorized

npm install error due to typescrip dev dependency or following error

If you face any similar kind of log error during npm install for react:

7090 verbose stack FetchError: invalid json response body at https://registry.npmjs.org/@typescript-eslint%2ftypescript-estree reason: Unexpected end of JSON input7090 verbose stack     at C:\Users\HP\AppData\Roaming\npm\node_modules\npm\node_modules\minipass-fetch\lib\body.js:77:317090 verbose stack     at async Promise.all (index 60)7090 verbose stack     at async Arborist.[buildDepStep] (C:\Users\HP\AppData\Roaming\npm\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:854:5)7090 verbose stack     at async Arborist.buildIdealTree (C:\Users\HP\AppData\Roaming\npm\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:209:7)7090 verbose stack     at async Promise.all (index 1)7090 verbose stack     at async Arborist.reify (C:\Users\HP\AppData\Roaming\npm\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\reify.js:127:5)7090 verbose stack     at async install (C:\Users\HP\AppData\Roaming\npm\node_modules\npm\lib\install.js:38:3)7091 verbose cwd C:\Users\HP\Documents\team-captain\frontend7092 verbose Windows_NT 10.0.190427093 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\HP\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" "typescript" "--save-dev"7094 verbose node v12.17.07095 verbose npm  v7.5.27096 error code FETCH_ERROR7097 error errno FETCH_ERROR7098 error invalid json response body at https://registry.npmjs.org/@typescript-eslint%2ftypescript-estree reason: Unexpected end of JSON input7099 verbose exit 1

run following command to clean up npm cache or manually delete the npm-cache folder using path from the above log generation in command line interface.
or update your npm version to the latest version with using following command:
npm install -g npm@latest(or specific to latest version)
like here

Categories
Uncategorized

What is for?

I was wondering about below code, as searched result over google as usually everyone does to know.

<meta name="HandheldFriendly" content="True">

So here is the answer: https://stackoverflow.com/questions/1988499/meta-tags-for-mobile-should-they-be-used

Basically, explained its to identify as mobile content for one of the browser, and it also become general standard to for identifying mobile websites.

Categories
Blog Tech

angular ng serve command throws error: An unhandled exception occurred: Project does not exist

If you facing with such problem, you may refer to following link for the solution. I have posted this question here on StackOverlow Hope it helps someone. Thanks.

Categories
Blog Tech

Fix PUTTY keyboard-interactive authentication password message prompt or access denied error or alternative to connect to SSH with PUTTY

If you are struggling to connect to your server from windows using PUTTY software try this from installation folder path of PUTTY in the command line:

In terminal cd to your putty installation path, for example:

C:\Program Files\PuTTY

in command line type in below with corresponding user information of yours.

putty.exe -l yourserverusername -pw yourserverpwd yourdomain.com

this will let you pass with keyboard-interactive authentication password message and you are good to go!

Categories
Blog Tech

Binding JSON data dynamically from ajax/promise/observable request to pug template

I was struggling to loop over ajax response to pug, with a lot of scratching head on google and Github, got a clue to use ES6 template to create cart list items from response data and append its HTML back to section container of HTML, here is sample code below.

I have also tried out achieved the same via pug mixin (commented code below, not successful) but not sure how to pass JS object variable to mixin as it’s not accepting response data as an object parameter.

Found similar doing here https://codepen.io/anon/pen/GeQKxp
it has pass individual object literal to the mixin, but if we pass the object variable created in JS and pass to the mixin, it doesn’t work, not sure how to turn around with it!

Hope this example code give you a hint.

I am not a professional writer of content, therefore treat this as general information for help on the similar issue anyone face with pug and json data.

//- cart.pug template

block append headScript
    script(src='./../js/scripts.js')
    script.
        myApp.fetchCartItems().subscribe(
            data => {
                if ('productsInCart' in data){
                    const cartItemsData = data.productsInCart;
                    const cartItemsTemplate = cartItemsData.map(item => {
                        function getColors(colors) {
                            return colors.length ? colors.map( color => `<span>${color.name}</span>`) : 'standard color'
                        }
                        function getSizes(sizes) {
                            return sizes.length ? sizes.map( size => `<span>${size.code}</span>`).join(' ').toUpperCase() : 'standard size'
                        }
                        return `<div class="row cart-item-row">
                                <div class="col-md-6">
                                    <img src="../images/T${item.p_id}.jpg" class="cart-thumb" />
                                    <div class="cart-item-detail">
                                        <h3>${item.p_name}</h3>
                                        <label>Style #: ${item.p_style}</label>
                                        <label>Colour: ${getColors(item.p_available_options.colors)}</label>
                                    </div>
                                    <div class="cart-actions">
                                        <a href="javascript:void(0)" class="jsEdit">Edit</a>
                                        <a href="javascript:void(0)">X Remove</a>
                                        <a href="javascript:void(0)">Save for Later</a>
                                    </div>
                                </div>
                                <div class="col-md-2 text-center">${getSizes(item.p_available_options.sizes)}</div>
                                <div class="col-md-2 text-center">
                                    <input type="text" name="txtQty${item.p_quantity}" id="txtQty${item.p_quantity}" value="${item.p_quantity}" class="form-control qty-input" />
                                </div>
                                <div class="col-md-2 text-right price-text"><sup>$</sup>${item.p_price}</div>
                            </div>
                            `
                    });

                    document.getElementById('cartItemContainer').innerHTML = cartItemsTemplate;
                }
            },
            err => {
                console.error('Subscribe Error', err);
            },
            () => {
                console.info('Subscribe complete');
            }
        );

section(class='cart-content' id='cartItemContainer' data-json= cartItems) cartItemContainer

//- mixin cartItemsMixin(cartItems)
//-     div(id='cartItemContainer' data-json= cartItems) cartItemContainer
//-     //- div= #{JSON.stringify(cartItems)}
//-     div(data-json= cartItems)
//-     section.cart-content
//-         .row.cart-item-row
//-             .col-md-6
//-                 img.cart-thumb(src='../images/T1.jpg')
//-                 .cart-item-detail
//-                     h3 Solid green cotton tshirt
//-                     label Style #: MS13KT1906
//-                     label Colour: Blue
//-                 .cart-actions
//-                     a.jsEdit(href='javascript:void(0)') Edit
//-                     a(href='javascript:void(0)') X Remove
//-                     a(href='javascript:void(0)') Save for later
//-             .col-md-2.text-center S
//-             .col-md-2.text-center
//-                 input.form-control.qty-input(type='text', name='txtQty1', id='txtQty1', value='1')
//-             .col-md-2.text-right.price-text
//-                 sup $ 
//-                 | 11.00
//- +cartItemsMixin(cartItemsData)