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
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
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)
Categories
Blog Tech

how to solve basic development issues and steps to getup application working

These are the random solution to the issues, faced while developing the application in front-end and these are just the hand tools to fix issues and refer anytime in need. Hope it helps you in your search for solutions. Will keep updating with more and were need of improvement required to this page.


ANGULAR – To use on CLI


//to run server with proxy file optionally can be set under angular.json > server > options >
ng serve –proxy-config proxy.config.json

//if need to add port optionally
ng serve –proxy-config proxy.config.json –port 9999


EXPRESS – To use on CLI


express –view=pug spar-api

create : spar-api\
create : spar-api\public\
create : spar-api\public\javascripts\
.
.

change directory:
> cd spar-api

install dependencies:
> npm install

run the app:
> SET DEBUG=spar-api:* & npm start

On Windows use this command
set DEBUG=myapp:* & npm start

On Mac or linux
DEBUG=myapp:* npm start


TO CREATE SECRECT KEY


Window terminal side of code:

node -e “console.log(require(‘crypto’).randomBytes(256).toString(‘base64’)); #not working with jwt token signing trying other way below:

Source: https://gist.github.com/Holger-Will/3edeea6855f1d69a5368871bce5ea926

(tried on windows 7, working find with angular-jwt app)

generate private key

openssl genrsa -out private.pem 2048

extatract public key from it

openssl rsa -in private.pem -pubout > public.pem


Express side of code:

//Normalizing the path for windows environment
var normalPKPath = path.normalize( __dirname + ‘/private.key’);

const RSA_PRIVATE_KEY = fs.readFileSync(normalPKPath, ‘utf8’);



FIREBASE SETUP FOR ANGULAR CLI PROJECT


Create project in firebase console web page; https://console.firebase.google.com/

install firebase tool

npm install -g firebase-tool

firebase login

Google will try to login with your google account

(prior to init everytime, you have to make angular prod build ready and do firebase init each time for new deployment to firebase server)

firebase init

couple of questions will be asked after init command, type of deployment for web choose Hosting by presseing space bar key after selecting the option in list.
next publish folder path to be, in angular cli its dist folder for production build, type dist and hit enter
next it will ask you is your app is singple page app or not? type yes and hit enter
next it will ask do you want to replace existing index.html with firebase choose now? because our prod build as created file under dist folder.
next will create necessary files in your app directoy related to firebase/

make sure you update enviorments.prod.ts with firebase configuration detail, which you will get object from firebase console Create app for web page by clicking on it,

under project overview page.

next finially execute

firebase deploy

optionally you may use firebase deploy –proiect

if everything fine you will see app running under firebase server


ZEIT NOW – ISSUE SOLUTION


Build failing for typescript file: giving error Error: Cannot find module ‘typescript’

Fix to use @now/node@0.4.28-canary.6: in now.json file to make a build :
solution source: Github Issue https://github.com/zeit/now-builders/issues/181

Example: { “src”: “./src/app/server/*.ts”, “use”: “@now/node@0.4.28-canary.6”}