Tips Posts

Some Laravel tips that we must need to know

1) Null safe operator

From PHP 8 you can use Null Safe Operator

How we are doing null checking code in PHP < 8.0

 $country =  null;

 if ($session !== null) {
     $user = $session->user;

     if ($user !== null) {
         $address = $user->getAddress();

         if ($address !== null) {
             $country = $address->country;
         }
     }
 }

PHP 8 allows you to write this:

 $country = $session?->user?->getAddress()?->country;

2) Ternary condition

We have used this ternary condition for checking null value

 isset($user->image) ? $user->image : null

We can short above condition like this

 $user->image ?? null

3) Clone a model

You can clone a model using replicate(). It will create a copy of the model into a new, non-existing instance.

 $user = App\User::find(1);
 $newUser = $user->replicate();
 $newUser->save();

4) Default Relationship Models

Laravel provides a handy withDefault() method on the belongsTo relationship that will return a model object even when the relationship doesn't actually exist.

 class Post extends Model
 {
     public function user()
     {
         return $this->belongsTo(User::class)->withDefault();
     }
 }

Now, if we try to access the $post->user relationship, we'll still get a User object even when it does exist in the database. This is known as the "null object" pattern and helps eliminate some of those if ($post->user) conditional statements.

For more information read Laravel withDefault() doc.

5) Save models and relationships

You can save a model and its corresponding relationships using the push() method.

 class User extends Model
 {
     public function phone()
     {
         return $this->hasOne('App\Phone');
     }
 }
 $user = User::first();
 $user->name = "Peter";
 $user->phone->number = '1234567890';
 $user->push(); // This will update both user and phone record in DB

Hope it will be helpful.

Thanks

December 30, 20221 minuteMitesh MakwanaMitesh Makwana
How to Increase Sales from Upwork

Upwork is a platform that connects freelancers and clients for a wide range of services including sales. If you're looking to increase your sales on Upwork, here are some tips that can help:

  • Build a strong profile

  • Improve your proposal

  • Be Responsive and Professional

  • Offer added value

  • Use Upwork's tools and resources

Build a strong profile

Your Upwork profile is essentially your online resume. Make sure it accurately reflects your skills, experience, and qualifications. Use a clear, professional profile picture and highlight any relevant certifications or achievements.

Improve your proposal

When you apply for a job on Upwork, you will need to write a proposal explaining why you are the best candidate for the job. Read the job posting carefully and tailor your submission to the client's specific needs. Emphasize your relevant experience and skills and provide examples of your work.

Be Responsive and Professional

Once you've landed a job on Upwork, it's important to communicate effectively with your clients and meet deadlines. Respond to messages promptly and be respectful and professional in your interactions. This will help you build a positive reputation on the platform and increase your chances of getting repeat business or referrals.

Offer added value

In addition to getting the job done to the best of your ability, consider offering added value to your customers. This may be in the form of additional resources or advice or offering to complete additional tasks outside the scope of the original job. This can help you stand out from other freelancers and increase your chances of getting repeat business.

Use Upwork's tools and resources

Upwork offers a variety of tools and resources for freelancers, including the ability to track their time, create invoices, and manage their finances. Be sure to take advantage of these resources to streamline your work and make it easier for customers to do business with you.

Following these tips can increase your sales and build a successful freelance business on Upwork. Good luck!

December 22, 20222 minutesAnkit KalathiyaAnkit Kalathiya
Laravel hasOneThough & Laravel hasManyThough Relationships

Laravel HasOneTHough & Laravel HasManyThough Relationships

We generally know about the 4 basics Laravel Relations ships that laravel provides:

Now we are going to see the major missing relationships that we are thinking are "Hard to use", but in real cases, it's needed while developing a project.

Even though I was thinking that HasOneThough and HasManyThough Relationships were will be hard to understand, I was wrong. it's really easy to understand.

Understanding HasOneThough

Let's say there is a Library that wants to know the book issuer's name directly, in this case, we generally do :

  • Fetch Books
  • Fetch its related issuer by using the HasOne Relation

What if I say I can directly access the issuer name into the Library model, yes we can achieve this by using the has one though.

Library
- id
- name

Book
- id
- name
- library_id

Issuer
- id
- name
- book_id
public function issuer() {
    return hasOneThough(App\Issuer, App\Book, library_id, book_id)
}

Understanding HasManyThough

Let's say in the same example that there are multiple issuers of the same books, we can achieve it as follow.

public function issuer() {
    return hasManyThough(App\Issuer, App\Book, library_id, book_id)
}

Hope it will be helpful.

Thanks

December 10, 20221 minuteVishal RibdiyaVishal Ribdiya
[Best-Practices] Securing NodeJS Express APIs with JWT Authentication and custom Authorization

Overview


A Node.js library for use as Express middleware to secure endpoints with JWTs. The implementation uses a JWT endpoint of an Authorization Server to get the keys required for verification of the token signature. There is also an example Express app that shows how to use the library.

Package: https://www.npmjs.com/package/jsonwebtoken

Using the JSON web token, we can simply authenticate each and every request on our server. As a standard / best practice, we can use JWT (JSON web token) middleware to validate all requests.

JWT Middleware


  const jwt = require('jsonwebtoken')

  module.exports = (expectedRole) => (req, res, next) => {

  const authHeader = req.get('Authorization')
  if (!authHeader) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  const token = authHeader.split(' ')[1]
  if (!token) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  let decodedToken
  try {
    decodedToken = jwt.verify(token, process.env.SECRET_KEY)
  } catch (error) {
    error.statusCode = 401
    throw error
  }

  if (!decodedToken) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  const role = decodedToken.role

  const authorised = expectedRole.includes(role)
  if (!authorised) {
    const error = new Error('Not authorised.')
    error.statusCode = 401
    throw error
  }

  req.user = decodedToken
  next()
}

This middleware has been prepared and exported. Therefore, we need to include it in our routes file and pass it to the expected role, so in our JWT middleware, we will validate the request with the JWT token, then verify that the user has access to an expected role (this role saved in the database) to this endpoint.

Routes File


 const express = require('express')
 const router = express.Router()

 const auth = require('./auth/index')
 const admin = require('./admin/index')
 const common = require('./common/index')
 const authorize = require('../middleware/jwtAuth')

 router.use('/auth', auth)
 router.use('/admin', authorize(['admin']), admin)
 router.use('/common', authorize(['admin', 'user']), common)

 module.exports = router 

Now that we have set up our authentication and authorization middleware in our routes, we are passing the required role to access these routes. These roles will be checked against our user role.

Our middleware simply next() the request if the user has a valid JWT token and is authorized to access this route, otherwise, it will throw the global error that is caught by the express global error handler.

November 08, 20222 minutesSmit GajeraSmit Gajera
How to Get Leads from LinkedIn

Add connections to your network

If you spend a minute or more each workday clicking the "Connect" button on the "People You May Know" list that LinkedIn posts in your feed, you'll expand your network, and you'll be known as a network expander. will, which is equally important.

Remember: Everyone you talk to about business or meet during a business day is a potential LinkedIn connection.

Build your lead list

Spend five minutes a day checking your contacts' connections to see who you don't know personally but would like to meet. Note down who you want to introduce. Start with the "recommendations" first, as those are likely the strongest connections of the LinkedIn user you're looking at.

Ask for recommendations outside of your LinkedIn account via email or phone. You will get a quick reply. (And you'll get a chance to quickly reconnect with your connections.)

Follow up with your current customers and prospects

Spend another two minutes each day searching for your current clients and top prospects. Find out if they have a company page. If they do, follow through and monitor.

Join groups

LinkedIn lets you connect with people who are in groups with you. Use this as a targeted way to add value to others, share insights, and build your network with prospects. Invest five minutes in this every day.

Use LinkedIn to celebrate the achievements of others

When you see a news story or post that provides good news about your client or prospect or any key contact, share the news as a status update. Identify a person with an "@" reply. It will ensure that they receive the mentioned notification. Spend a minute a day on this.

Write a recommendation

Securing LinkedIn recommendations is often difficult, if only because it takes time for the author to log in, write, and post.

Instead of waiting for someone to recommend you, take five minutes a day to write and post (reality-based) recommendations for your customers and key contacts. Once your contact approves the text, the recommendation will appear on his/her LinkedIn account.

September 30, 20222 minutesAnkit KalathiyaAnkit Kalathiya
How to write an email to a potential client

Reaching sales prospects over email is an opportunity to sell and develop a working relationship with a new client.

Write a subject line

The first step in writing a strong email to a prospect is to consider the subject line. The first thing a potential client will see in an email is the subject line, so it's important that it persuades the recipient to open the email. Here are some strategies you can use to write a compelling subject line:

Here's what you should do if you want to write good email subject lines:

  • Use personalization.
  • Ask an engaging question.
  • Use concise and action-oriented language.
  • Take advantage of scarcity and exclusivity.

Give information about yourself.

You will more likely gain traction if they already know, like, and trust you. But everyone has to start somewhere, right?

If they've never received a communication from you, tell them a little about yourself in a way that feels warm and authentic. You must convey who you are and why they should listen to you. At the same time, it's essential to make it about them. For example, your email sales introduction could look something like this:

"My name is [name], and I'm contacting you because..."

Close the email with a salutation

You can include a closing salutation that matches the level of formality you used to open the email. Here are a few examples of closing salutations for professional emails:

  • Thank You
  • Best wishes
  • Regards
  • Looking forward to hearing from you
  • Sincerely
August 16, 20221 minuteAnkit KalathiyaAnkit Kalathiya
Difference between Eager Loading and Lazy Loading

We often listen to the words "Eager Loading" & "Lazy Loading" in Laravel. but maybe some of how still don't know what that actually stands for.

What Lazy Loading means?

I worked with many projects that is developed by some other developers and the common problems in code I found us Lazy Loading queries everywhere.

To understand it more easily let's take one simple example.

Let's say There is Post model and Comments Model.

So basically post->hasMany('comments')

So let's say we are fetching 10 posts and now we want the comments of each post. what we will do is :

$post->comments()->get() (LAZY LOADING)

Lazy loading cause N+1 queries issues as every time we are fetching comments of each post and it will block the execution too for while as its queries from the DB.

What Eager Loading means?

Eager loading is very useful when we are working with large-scale projects. it saves lot's of execution time and even DB queries too :)

Let's take the above example to understand the Eager loading.

$posts = Post::with('comments')->get()

$post->comments (EAGER LOADING)

here when we retrieve the posts at that time we are fetching its comments too on the same query. so when we do $post->comments it will not again do query into DB or not even block execution as the comments are already there in model instance.

So this is how Eager loading saves your time and also prevents N+1 Query.

Hope that helps.

August 13, 20221 minuteVishal RibdiyaVishal Ribdiya
Top Laravel packages that you need in 2022

What is Laravel?

Laravel is the most popular PHP framework right now to develop web applications, it offers a very easy environment and services for developers.

In this blog, we are going to know about the packages that we must have to use while developing any laravel application.

Best Laravel Packages

Here we are going to see some best and top laravel packages that will help you to optimize your application performance and it's also very useful while doing the development.

IDE Helper

Github: https://github.com/barryvdh/laravel-ide-helper

It's a very helpful package and saves lots of time for the developer.

It will generate the helper file which enables our IDE to provide accurate autocompletion while doing the development.

Laravel Debugbar

Github : https://github.com/barryvdh/laravel-debugbar

This is very helpful when we have to check the page performance, in sense of how many queries are firing on the specific page? , how many models are loading? etc.

We can show the total processing time of the page, and the query results time too. by using that results we can do some refactor to our code and make our application more optimized.

Spatie Medialibrary

Github : https://github.com/spatie/laravel-medialibrary

This package is very useful when we are doing file uploads. also, it allows us to upload files to the s3 (AWS) very easily by changing just the file system driver.

The main functionality it has is it allows us to associate files with the Eloquent models.

Spatie Role Permission

Github : https://github.com/spatie/laravel-permission

It's 2022 and still, lots of developers are using the custom roles/permissions management. they even didn't familiar that this package have capabilities to manage each role/permissions management with a specific Eloquent model too.

We can assign roles or permissions to the user model or even any model. later we can check it via the middleware that this package is providing.

Ziggy

Github : https://github.com/tighten/ziggy

Before using this package you must need to implement the named routes into your laravel application.

Normally people can just provide a hardcoded URL into the JS file while doing the AJAX calls. But with this package, you can use the route we are using in blade files.

This allows us to use the route() helper method in the JS files.

June 09, 20222 minutesVishal RibdiyaVishal Ribdiya