Posts
Laravel hasOneThough & Laravel hasManyThough RelationshipsLaravel

Laravel hasOneThough & Laravel hasManyThough RelationshipsLaravel
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
[Best-Practices] Securing NodeJS Express APIs with JWT Authentication and custom AuthorizationNodeJS
![[Best-Practices] Securing NodeJS Express APIs with JWT Authentication and custom Authorization](https://d37y9b4kfek2hl.cloudfront.net/blog/images/posts/231/best-practices-securing-nodejs-express-apis-with-jwt-authentication-and-custom-authorization.gif)
[Best-Practices] Securing NodeJS Express APIs with JWT Authentication and custom AuthorizationNodeJS
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.
Useful Figma Tricks to Work FasterDesign

Useful Figma Tricks to Work FasterDesign
Whether you're new to Figma or an expert user, you've probably realised that there are always more effective methods to go about your task. Speaking of effective work, here are several strategies you may or may not be aware of that might increase your productivity on Figma, or at the very least make navigating less stressful.
1. Math in Fields
Spend less time trying to manually resize items to get the right measurement. You may employ percentages like 100%. Math operations like plus (+), minus (-), multiplication (*), and division (/) are also possible.
2. Adjust Opacity Quickly
To easily adjust the opacity of shapes or other objects, all you have to do is click on it and choose the desired percentage, which saves you from having to repeatedly move the mouse. That is 10 for 10%, 25 for 25%, and so on.
3. Resizing Tips
The scale tool would be activated if you pressed K while choosing a frame or element. use of it? It gives you the option to resize the chosen content while keeping its proportions. When resizing, holding the alt or option buttons would make it larger from the center.
4. Collapse All Layers
In the past, I've been guilty of leaving groups after groups and elements after elements open in my Layers panel, which makes it more difficult to discover anything there. Use the convenient keyboard shortcut Alt + L to periodically collapse all Layers to keep your panel appearing nice and orderly and to maintain your attention on the current project.
5. Quicker Layers Navigation
Use the keyboard commands Enter and Tab to rapidly navigate between the Layers panel's items and locate what you're looking for. To navigate back up through your Layer groups and parent containers, hold Shift while using the keyboard keys I just mentioned.
6. Add Images in Bulk
This Figma shortcut gives you quick access to the Place Image tool, which makes it simple to add photographs to a Figma document. Press Ctrl + Shift + K, then select the required images and place them on canvas. You may import a photo straight onto the frame to keep it at its original size, or you can upload a photo inside a design form to scale it to match the shape. You may add a lot of photographs to your design at once.
How to implement Laravel impersonateLaravel

How to implement Laravel impersonateLaravel
What is user impersonate and why we use it in projects?
- User Impersonate is useful when we want to login on behalf of admin user.
- When we are a super-admin and we want to know about our users what they do in their account then this package is useful to check their activity.
- If you implemented impersonate in your project then you need to maintain it because it may cause a security issue as well as user's privacy issue.
Here is a full documentation of laravel impersonate: https://github.com/404labfr/laravel-impersonate
So let's start with installing impersonate on your project copy the below code where we will install this package using composer.
composer require lab404/laravel-impersonate
Add the service provider at the end of your config/app.php
:
'providers' => [
// ...
Lab404\Impersonate\ImpersonateServiceProvider::class,
],
Add the trait Lab404\Impersonate\Models\Impersonate
to your User model.
Using the built-in controller
In your routes file, under web middleware, you must call the impersonate
route macro.
Route::impersonate();
// Where $id is the ID of the user you want impersonate
route('impersonate', $id)
// Or in case of multi guards, you should also add `guardName` (defaults to `web`)
route('impersonate', ['id' => $id, 'guardName' => 'admin'])
// Generate an URL to leave current impersonation
route('impersonate.leave')
Blade
There are three Blade directives available.
When the user can impersonate
@canImpersonate($guard = null)
<a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
@endCanImpersonate
When the user can be impersonated
@canBeImpersonated($user, $guard = null)
<a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
@endCanBeImpersonated
When the user is impersonated
@impersonating($guard = null)
<a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
@endImpersonating
That's it. Enjoy.
Use Laravel localization key into your Javascript codeLaravel

Use Laravel localization key into your Javascript codeLaravel
Generally, we cannot use the laravel localization key in its javascript. is that possible to use laravel localization in javascript?
Yes, now you can use laravel localization into laravel, thanks to the rmariuzzo/Laravel-JS-Localization package.
In this tutorial, we will learn how to use laravel localization in javascript, so let's get started.
Install the package
composer require mariuzzo/laravel-js-localization
In your Laravel app go to config/app.php
and add the following service provider:
Mariuzzo\LaravelJsLocalization\LaravelJsLocalizationServiceProvider::class
Usage
The Laravel-JS-Localization package provides a command that generates the JavaScript version of all your messages found in app/lang (Laravel 4) or resources/lang (Laravel 5) directory.
Generating JS messages
php artisan lang:js
The resulting JavaScript file will contain all your messages plus messages.js in your public directory.
Link that js file into your main layout.
<script src="{{ asset('messages.js') }}"></script>
Documentation
Getting a message
Lang.get('messages.home');
Getting a message with replacements
Lang.get('messages.welcome', { name: 'Joe' });
Changing the locale
Lang.setLocale('es');
How to Get Leads from LinkedInSales

How to Get Leads from LinkedInSales
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.
UUIDs as Primary Keys with a Trait in Laravel 9Laravel

UUIDs as Primary Keys with a Trait in Laravel 9Laravel
What are UUIDs?
UUIDs stands for Universally Unique Identifiers and are 128 bits values used to uniquely identify some record in our database. UUIDs are represented as a hexadecimal string split into five groups separated by hyphens.UUIDs are universally unique alphanumeric identifiers that are 36 characters long.
Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead.
Updating Migration File
It is a very important step to update our migration file, I want to use the UUIDs in my User class so I will make changes to my User’s migration class.
$table->id();
to this:
$table->uuid('id')->primary();
If you are using a UUID primary key as a foreign key in another table, you need to change the column type to UUID, where the foreign key is defined. from this:
$table->unsignedBigInteger('user_id')->unsigned();
to this:
$table->uuid('user_id');
Using Trait in Our Model Class
you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model.
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasUuids;
// ...
}
$user = User::create(['name' => 'John','email' => 'john@doe.com']);
$user->id; //72106479-5367-4853-9b44-b8b7a1e94f01
By default, The HasUuids trait will generate "ordered" UUIDs for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically.
Why use UUIDs over regular IDs?
- UUIDs are safer than using regular numeric IDs because they are not easy to spoof. Regular IDs make it easy to get information about the application, like how many users the application has.
- Using UUID is a great solution for multi-tenancy applications.
I hope you will find this post useful.
How to start activity using Animation?Android Development

How to start activity using Animation?Android Development
Material design apps use activity transitions to connect different states with motion and transformations. Entry and exit transitions, as well as transitions between shared elements, can be animated.
Android supports these enter and exit transitions
1] Explode :
- Views are moved in or out of the scene's center.
2] Slide :
- Views are moved in or out from a scene's edge.
3] Fade
- Changes the opacity of a view to add or remove it from the scene.
These transitions are also supported on Android
ChangeBounds :
- Makes target views' layout bounds change.
ChangeClipBounds :
- Animates changes made to the clip boundaries of target views.
ChangeTransform :
- Initiates the scale and rotation change of target views.
ChangeImageTransform :
- Images have a change in size and scale as a result of animation.
Check on versions compatibility
// Check if we're running on Android 5.0 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Apply activity transition
} else {
// Swap without transition
}
Create custom transitions
- When you define a style that inherits from the material theme, enable window content transitions with the
android:windowActivityTransitions
attribute.
<style name="BaseAppTheme"
parent="android:Theme.Material">
<!-- enable window content transitions -->
<item name="android:windowActivityTransitions">true</item>
<!-- specify enter and exit transitions -->
<item name="android:windowEnterTransition">@transition/explode</item>
<item name="android:windowExitTransition">@transition/explode</item>
<!-- specify shared element transitions -->
<item name="android:windowSharedElementEnterTransition">
@transition/change_image_transform</item>
<item name="android:windowSharedElementExitTransition">
@transition/change_image_transform</item>
</style>
This example defines the change_image_transform transition as follows:
<!-- res/transition/change_image_transform.xml -->
<!-- (see also Shared Transitions below) -->
<transitionSet
xmlns:android="http://schemas.android.com/apk/res/android">
<changeImageTransform/>
</transitionSet>
In your code, enable window content transitions by calling Window.requestFeature()
:
// inside your activity (if you did not enable transitions in your theme)
getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
// set an exit transition
getWindow().setExitTransition(new Explode());
Use transitions to start an activity
startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
Let someone start a new activity with a shared element
To make a screen transition animation between two activities that have a shared element:
final View imgContainerView = findViewById(R.id.img_container);
// get the common element for the transition in this activity
final View androidRobotView = findViewById(R.id.image_small);
// define a click listener
imgContainerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(this, Activity2.class);
// create the transition animation - the images in the layouts
// of both activities are defined with android:transitionName="robot"
ActivityOptions options = ActivityOptions
.makeSceneTransitionAnimation(this, androidRobotView, "robot");
// start the new activity
startActivity(intent, options.toBundle());
}
});
An activity with multiple elements is an excellent start
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,
Pair.create(view1, "agreedName1"),
Pair.create(view2, "agreedName2"));