Categories
Learning

How to update in Laravel 8 all columns in database for form fields required and non required?

Hello, welcome to this question post.

I was looking for quick and succint turn around for this question and after searching lot on this one of post gave me any idea to update my rest of non-validate fields of form and also which don’t have validate rules at laravel model or controller level.

So here if my modified update() function from laravel Controller to update non required form fields or rules set in laravel controller or model, with in easy simple PHP style.

public function update(Request $request, $id)
    {
        
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'price' => 'required',
        ]);
        
        $nonRequiredFields = [
            'discount' => $request->discount,
            'qty' => $request->qty,
            'tax'=> $request->tax,
            'shipping' => $request->shipping,
            'handling' => $request->handling,
        ];
        
        Food::where('foodId', '=', $id)->update(array_merge($validatedData, $nonRequiredFields));
        
        return redirect()->route('food.index')->with('success', 'Food successfully updated');

}

In the code above I have given readable name to variable ($nonRequiredFields) which can be easily understand and I found this way the solution is working!

If you know more better approach kindly send me a not or if comments are open to this post please do comment.

Thanks for visiting and reading the post.

Categories
Learning

What to do when get nextjs server error when loading image from scss/sass variable in nextjs Image component?

Server Error
Error: Failed to parse src ""https://yourdomain.com/develop-app/assets/images/body-bg5.png"" on `next/image`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)

I was facing this error recently on my nextjs project, I wanted to load the background Image path from SCSS variable into the NextJs Image components.

Before this error occurred, I was hunting on google for the answer and found it that how to import scss variables into react component, and I found we can import scss variable by declaring in scss file itself using :export directive of scss

//Example of exporting variable from scss file

$BODY_BG: "https://yourdomain.com/develop-app/assets/images/ka-body-bg.png";
$BODY_BG_OPT1: "https://yourdomain.com/develop-app/assets/images/ka-body-bg1.png";

:export {
    BODY_BG: $BODY_BG;
    BODY_BG_OPT1: $BODY_BG_OPT1;
}

and then can import easily into react component by installing node-sass npm package and then import the file of scss variable into react component like :


import backgroundVar from "../styles/background.module.scss";

//(note: I have used backgroundVar as my variable import name for all the scss variables exported from background.module.scss file)

and use it like this in your react state hook or directly in react component

const homeBodyBg = trimOutThis(backgroundVar.BODY_BG_OPT5 && backgroundVar.BODY_BG_OPT5, /"/g, '');

const [bgImage, setBgImage] = useState(homeBodyBg || '');

To fix the error of nextjs error of:

Error: Failed to parse src ""https://yourdomain.com/develop-app/assets/images/body-bg5.png"" on `next/image`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)

I wrote small function to trim off the double quotes “” which we get from scss variable declaration for path, here is that function below and you may notice in above code, I am already trimming the double quotes with empty string and then it works like charm!

//Function to replace any string pass to an empty string or to be replaceable by something else

export const trimOutThis = (str, regx, replaceValue = "") => {
  if (!str.length || !regx) return '';


  return str.replace(regx, replaceValue);
}
//Function invoking example


const homeBodyBg = trimOutThis(backgroundVar.BODY_BG_OPT5 && backgroundVar.BODY_BG_OPT5, /"/g, '');


output without double quotes ” for NextJS image src

Hope this will help you in your search and solving issues.


Have nice day & Happy Learnings.

Thanks for visiting.

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
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 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!