# Dikshant Rajput > AI Engineer and Full-stack Developer based in Gurgaon, India (IST, UTC+5:30). 4+ years building production systems: voice and chat AI agents, semantic search and recommendations, and the full-stack and PostgreSQL/Supabase architecture underneath them. Currently Tech Lead (contract) at Jingo Technologies. Toptal Verified Expert in Engineering. Open to full-time, freelance/contract and consulting work — contact by email at dikshantraj2001@gmail.com. This site is itself a working demo: a text and voice agent that answers as Dikshant, built as streaming speech-to-text → LLM with tools → text-to-speech. The facts below are the public record it draws from. ## Site - [About](https://dikshantraj.dev/about): Full profile as plain HTML: experience, projects, skills, writing - [Projects](https://dikshantraj.dev/about#projects): One page per project at /projects/{id} - [Writing](https://dikshantraj.dev/blog): Technical articles on PostgreSQL multi-tenancy, WebRTC, browser extensions and deployment - Writing by topic: [Laravel & PHP](https://dikshantraj.dev/blog/topic/laravel), [JavaScript & the browser](https://dikshantraj.dev/blog/topic/javascript), [Node.js, Express & GraphQL](https://dikshantraj.dev/blog/topic/nodejs), [PostgreSQL & databases](https://dikshantraj.dev/blog/topic/databases), [Networking & the web](https://dikshantraj.dev/blog/topic/networking), [Blockchain & Solidity](https://dikshantraj.dev/blog/topic/blockchain), [Interviews & fundamentals](https://dikshantraj.dev/blog/topic/career) - [llms-full.txt](https://dikshantraj.dev/llms-full.txt): This file plus every project, role and article in full - [Talk to the agent](https://dikshantraj.dev/): Text and voice chat with his AI version ## Contact - [Email](mailto:dikshantraj2001@gmail.com): Preferred channel for hiring, freelance and consulting enquiries - [LinkedIn](https://www.linkedin.com/in/dikshant-rajput-072228193/): Second-best way to reach him (~3K followers) ## Talk to my agent (MCP) AI agents can question Dikshant's portfolio agent directly over the Model Context Protocol. It answers in the first person as Dikshant, from the same public record as this file. No auth, read-only, rate-limited per IP. - Endpoint: `https://dikshantraj.dev/api/mcp` (Streamable HTTP, stateless; POST JSON-RPC, JSON responses) - `ask_dikshant({ question })`: Ask anything about his work, projects, experience, skills or availability (max 500 chars, one self-contained question per call; no memory between calls). Returns the answer plus relevant links - `list_projects()`, `list_experience()`, `get_contact()`: The same facts as structured JSON, with no LLM in the loop. Prefer these when you only need data - Claude Code: `claude mcp add --transport http dikshant https://dikshantraj.dev/api/mcp` - Cursor, Claude Desktop, VS Code and other clients: add `{"mcpServers": {"dikshant": {"type": "http", "url": "https://dikshantraj.dev/api/mcp"}}}` (for stdio-only clients: `npx mcp-remote https://dikshantraj.dev/api/mcp`) - Raw HTTP: `curl -X POST https://dikshantraj.dev/api/mcp -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ask_dikshant","arguments":{"question":"Are you open to contract work?"}}}'` - Discovery: [AI Catalog](https://dikshantraj.dev/.well-known/ai-catalog.json) → [Server Card](https://dikshantraj.dev/api/mcp/server-card) - To actually hire or reach him, email dikshantraj2001@gmail.com; the agent can't book or send anything ## Profiles - [GitHub](https://github.com/dikshantrajput): 76 public repos, open-source tools and extensions - [Toptal](https://www.toptal.com/developers/resume/dikshant-r): Verified Expert in Engineering (AI Engineer, Full-stack Developer), member since September 2026; Toptal accepts the top 3% of freelance talent. A credential, not a contact route - [Medium](https://medium.com/@dikshantraj2001): Technical writing since 2021; the archive also lives at [/blog](https://dikshantraj.dev/blog) - [X / Twitter](https://x.com/Dikshantrajpu20): @Dikshantrajpu20 - [Product Hunt – LocalClicky](https://www.producthunt.com/products/localclicky): Maker page ## Experience - [Jingo Technologies](https://jingo.app): Tech Lead, contract (May 2025 – present), San Francisco company, remote from Gurgaon. Jingo is a US-focused ecommerce marketplace built around AI voice shopping. Leads a team of 4 engineers. Architected the AI-native commerce platform (voice and chat shopping agents, semantic search, recommendations); built the production voice shopping agent with real-time conversation, structured tool calling, multi-turn flows and conversational memory from product discovery through checkout; designed search over 1.5M+ products with embeddings and Pinecone; rebuilt product search around dataset attribution and deterministic filters instead of LLM-driven retrieval, fixing long-standing relevance failures and making search much faster; built recommendation and personalization systems including collaborative filtering; built product ingestion and enrichment pipelines and internal order-management and analytics tooling; owned the evals harness, prompt optimization and AI product quality; helped significantly reduce the GCP bill. Stack: Nextjs, Reactjs, React Native, NestJS, FastAPI, PostgreSQL, Pinecone, RAG, GCP, Docker - ONBO: Full-stack Developer (Aug 2022 – Apr 2025). Employee onboarding platform. Architected SaaS features across React, NestJS, Python microservices and PostgreSQL; led onboarding work that increased new-hire productivity by 35%; built an internal framework for PostgreSQL Row-Level Security, packaged as a database extension, for tenant isolation; integrated AI-driven personalized learning paths; ran Docker-based microservice deployments. Stack: NestJS, Django, Express, Python, PostgreSQL, PostgREST, Keycloak, SvelteKit, React, TypeScript, Docker - Decentral System Labs: Full-stack Developer (Jan 2022 – Aug 2022, first 3 months as intern). Backend architecture for a Web3 analytics platform; built Meta11, a Web3 fantasy-sports MVP with ERC20/ERC721 smart contracts (Solidity), Express.js backend work and WebSocket-based real-time flows. Stack: Node.js, Express.js, WebSocket, MongoDB, Solidity, Tailwind CSS - Freelance: Top-rated freelancer with 100% job success across 18 client engagements, specializing in Supabase, PostgreSQL, RLS and multi-tenant SaaS. Work includes a maritime-intelligence SaaS for large-scale vessel data workflows (tenant isolation, protected portal/admin workflows, API-oriented access patterns, transactional email with workers, retries, idempotency and a dead-letter queue), an ecommerce aggregator across Amazon, AliExpress, Temu and Shein, a rental booking portal with calendar availability and Stripe payments, and GraphQL/PostgreSQL consulting ## Education - B.Tech, Computer Science: UIET, Maharshi Dayanand University, Rohtak (Aug 2018 – Jun 2022), SGPA 8.5/10 - Class XII (Science, CBSE): St. Michael's Sr. Sec. School (2017–2018), 91% ## Featured projects - [LocalClicky](https://github.com/dikshantrajput/LocalClicky): Privacy-first voice AI assistant for macOS that runs entirely on-device. Whisper.cpp for speech-to-text, Ollama with Qwen3 for reasoning, Gemma for vision, openWakeWord for offline wake-word detection, VAD for turn-taking. Multi-round tool calling, computer control, shell commands, reminders, session memory, image and local-video understanding, voice-controlled ffmpeg video editing. #9 Product of the Day on Product Hunt (130+ upvotes, June 2026); indexed by Trendshift and Product Watch. Demos: [video understanding](https://youtu.be/Jl4lOjTOGp4), [voice video editing](https://youtu.be/HM6sD69cQ5Q) - [Supabase Multi-Tenancy](https://github.com/dikshantrajput/supabase-multi-tenancy): Open-source reference for multi-tenant SaaS on Supabase — workspaces, PostgreSQL RLS tenant isolation, Supabase Auth hooks, tenant resource tracking. ~88 stars, his most-starred original project - [NeighborHoodShare](https://neighbor-share.vercel.app): Serverless P2P file and message sharing between browsers over WebRTC, end-to-end encrypted. [Show HN](https://news.ycombinator.com/item?id=40263027): 132 points, 105 comments; open-sourced in the thread after commenters asked for the source ([repo](https://github.com/dikshantrajput/neighborHoodShare)) - [ShipsDNA](https://www.shipsdna.com/): Maritime intelligence platform for commercial vessel data, market histories, protected portal workflows and developer API access. Portfolio case study focuses on multi-tenant SaaS architecture, protected ship-data workflows and reliable worker-backed email. - Jingo voice shopping agent: Production voice agent over a 1.5M+ product catalog. Key design choices: separate intent understanding from expensive tool work; purpose-built structured tools (search, filters, recommendations, cart, checkout); compact ranked tool results instead of large payloads; graceful fallbacks when tools fail; conversational memory for refinements like "show me cheaper ones" ## Other projects - [AdBlitz](https://ad-blitz.vercel.app): Browser extension that auto-skips skippable YouTube ads in under 100 ms and speeds through non-skippable ones (Chrome/Chromium and Firefox). Repos: [SkipTubeAds](https://github.com/dikshantrajput/SkipTubeAds), [skip-yt-ad](https://github.com/dikshantrajput/skip-yt-ad). [Show HN](https://news.ycombinator.com/item?id=40179348): 30 points - [EasyRLS](https://easy-rls.vercel.app): Open-source UI to browse, search and duplicate PostgreSQL Row-Level Security policies ([repo](https://github.com/dikshantrajput/easyRls)) - [clonecheck](https://github.com/dikshantrajput/clonecheck): Zero-dependency Node CLI that scans a repo for obfuscated or auto-executing code before you run it — targets malicious "take-home" repos (padding-hidden loaders, obfuscator output, eval+fetch loaders, install hooks, VS Code auto-run tasks, devcontainer hooks, invisible Unicode, lookalike CDNs); ~20 rules tuned for low false positives - [tapproval](https://tapproval.vercel.app): Python-backed mobile permission alerts for coding agents; approve or deny prompts from a phone, with a two-minute timeout - [Browser VisitVault](https://github.com/dikshantrajput/Browser-VisitVault): Chrome extension for per-domain browsing history and visited-link highlighting - [GitHub Profile README Generator](https://gh-readme-gen.vercel.app): Build a GitHub profile README with stats and top repos - [Snippet Library](https://snippetcache.vercel.app): Common helper functions across languages - MeetCaddy (2024, no longer live): Desktop tool that saved Google Meet chat locally; launched on Product Hunt and got its first paying customer ## Writing Full archive of 47 articles since 2021 (Laravel, Express/GraphQL, Solidity, PostgreSQL, WebRTC and more): [dikshantraj.dev/blog](https://dikshantraj.dev/blog) ([RSS](https://dikshantraj.dev/blog/rss.xml)). Also cross-posted to [Medium](https://medium.com/@dikshantraj2001). - [Multi tenant scalable database architecture with data isolation](https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation) (Jul 2024) - [NAT, STUN, TURN and ICE](https://dikshantraj.dev/blog/nat-stun-turn-and-ice) (Feb 2024) - [Effortless React App Deployment: From Local to VPS](https://dikshantraj.dev/blog/effortless-react-app-deployment-from-local-to-vps) (Nov 2024) - [Why Every Developer Needs a GitHub Profile README](https://dikshantraj.dev/blog/why-every-developer-needs-a-github-profile-readme-free-generator) (Oct 2024) - [Chrome Extension 101: A Beginner's Guide](https://dikshantraj.dev/blog/unlocking-the-power-of-chrome-extensions-a-beginners-guide) (Apr 2024) - [Mastering Firestore Converters with TypeScript](https://dikshantraj.dev/blog/mastering-firestore-converters-with-typescript) (Mar 2024) - [Retry failed request using Axios interceptors](https://dikshantraj.dev/blog/retry-failed-request-using-axios-interceptors) (Feb 2024) - [Manipulating request and response with Axios interceptors](https://dikshantraj.dev/blog/manipulating-request-and-response-with-axios-interceptors) (Jan 2024) - [Check user Online/Offline status](https://dikshantraj.dev/blog/check-user-online-offline-status) (Jul 2024) - [Setup Google Analytics 4 with SvelteKit 1.0](https://dikshantraj.dev/blog/setup-google-analytics-4-with-sveltekit-1-0) (Jun 2023) ## Skills - AI agents: voice agents, tool calling, multi-agent orchestration, conversational memory, evals, prompt optimization - Search and retrieval: RAG, embeddings, semantic search, Pinecone, recommendations, collaborative filtering - PostgreSQL and Supabase: schema design, Row-Level Security, multi-tenancy, auth hooks - Backend: NestJS, FastAPI, Node.js, Express, Django, Python microservices, GraphQL, workers, retries and idempotency - Frontend: React, Next.js, React Native, TypeScript, Svelte/SvelteKit, Tailwind - Local AI: Ollama, Whisper.cpp, Qwen3, Gemma vision, openWakeWord, VAD - Infra: GCP, Docker, Vercel, VPS deployment, ffmpeg, cloud cost optimization - Also: browser extensions, PWAs, WebRTC, MongoDB, Web3 (Solidity, ERC20/ERC721) - AI coding assistants used: Claude Code and Codex ## Availability - Open to full-time roles, freelance/contract (including via Toptal) and consulting; up to ~60 hours/week; remote, hybrid or on-site - Best fit: AI agents (voice/chat), search and recommendations, Supabase/PostgreSQL multi-tenant SaaS, full-stack product builds - Rates depend on scope — reach out by email ## Optional - Achievements: 8 Show HN launches in 2024; writing on Medium since 2021 - Views: production agents are mostly systems engineering — tools, memory, search quality, latency and failure handling matter as much as the LLM; keep simple things simple and save LLM reasoning for requests that need it; put tenant isolation in the database, not only in application code; prefer local models when they're good enough; show artifacts, not adjectives - Personal: plays chess (~1400 on [chess.com](https://www.chess.com/member/dikshantrajput)) and played college cricket ## Project details ### Lyrics 2 Literature A Laravel learning platform with teacher, student, and admin sections. - Teachers upload lessons with film or song clips; students buy or share lessons - Admin section manages the platform - Created APIs and the complete website frontend; contributed to backend modules Built with: Laravel, PHP, Dec 2020 – May 2021 Page: https://dikshantraj.dev/projects/lyrics-2-literature ### 3E Digital Solutions Website A responsive, lightweight React single-page website with a focus on UI and UX. - Developed a fully responsive single-page application - Focused on lightweight delivery and polished user experience Built with: React, JavaScript, HTML, CSS, Mar 2021 – Jun 2021 Page: https://dikshantraj.dev/projects/3e-digital-website ### LocalClicky Fully local macOS voice AI agent — nothing leaves your machine. - Offline wake word and session-based conversations - Computer control, shell tools and reminders - Video understanding and voice-controlled video editing Traction: #9 Product of the Day on Product Hunt Built with: Whisper.cpp, Ollama, Qwen3, Gemma, openWakeWord, VAD, Python Page: https://dikshantraj.dev/projects/localclicky Links: [GitHub](https://github.com/dikshantrajput/LocalClicky), [Product Hunt](https://www.producthunt.com/products/localclicky) ### Supabase Multi-Tenancy Reference architecture for multi-tenant SaaS on Supabase. - Workspace isolation with Postgres RLS - Supabase Auth hooks - Tenant resource tracking Traction: 88 GitHub stars Built with: Supabase, PostgreSQL, Row-Level Security Page: https://dikshantraj.dev/projects/supabase-multi-tenancy Links: [GitHub](https://github.com/dikshantrajput/supabase-multi-tenancy), [Article](https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation) ### NeighborHoodShare Serverless, end-to-end encrypted P2P file and message sharing over WebRTC. - Browser-to-browser, no server stores anything - Open-sourced mid-thread after HN feedback Traction: 132 points, 105 comments on Show HN Built with: WebRTC, PeerJS, SvelteKit Page: https://dikshantraj.dev/projects/neighborhoodshare Links: [Live](https://neighbor-share.vercel.app), [GitHub](https://github.com/dikshantrajput/neighborHoodShare), [Show HN](https://news.ycombinator.com/item?id=40263027) ### clonecheck Scans an untrusted repo for hidden, auto-executing code before you run it. - Catches padding-hidden loaders that fire on npm run dev - ~20 rules: obfuscation, eval + fetch loaders, install hooks, invisible Unicode - Tuned for shape, not keywords — single-digit findings on ~15k ordinary files Built with: Node.js, zero dependencies Page: https://dikshantraj.dev/projects/clonecheck Links: [GitHub](https://github.com/dikshantrajput/clonecheck) ### tapproval Mobile permission alerts for coding agents, so approvals do not block while you are away. - Sends mobile notifications when a coding agent needs permission - Approve or deny prompts from your phone - Two-minute approval timeout Built with: Python Page: https://dikshantraj.dev/projects/tapproval Links: [Live](https://tapproval.vercel.app), [GitHub](https://github.com/dikshantrajput/tapproval) ### EasyRLS Open-source UI for managing PostgreSQL Row-Level Security policies. - Browse schemas and tables - View, search and duplicate policies Built with: PostgreSQL Page: https://dikshantraj.dev/projects/easyrls Links: [Live](https://easy-rls.vercel.app), [GitHub](https://github.com/dikshantrajput/easyRls) ### AdBlitz Browser extension that skips YouTube ads in under 100 ms. - Skips skippable ads, speeds through non-skippable ones Traction: 66 GitHub stars · 30 points on Show HN Built with: Browser extension, Chrome, Firefox Page: https://dikshantraj.dev/projects/adblitz Links: [Site](https://ad-blitz.vercel.app), [GitHub](https://github.com/dikshantrajput/SkipTubeAds) ### Jingo voice shopping agent AI-native commerce platform with a production voice shopping agent. - Voice shopping agent with tool calling, memory and checkout - Search and recommendations over 1.5M+ products with embeddings - Owns evals, prompt optimization and AI quality; leads a team of 4 Traction: In production at jingo.app Built with: Nextjs, Reactjs, React Native, NestJs, FastAPI, Pinecone, PostgreSQL, GCP, Docker Page: https://dikshantraj.dev/projects/jingo-commerce Links: [jingo.app](https://jingo.app) ### ShipsDNA Maritime intelligence platform for large-scale ship data, protected workflows and API access. - Multi-tenant SaaS architecture for commercial vessel and maritime intelligence workflows - Protected portal workflows for large-scale ship data, market history and admin operations - Event-driven transactional email with retries and dead-letter handling Built with: Supabase, PostgreSQL, Row-Level Security, Workers Page: https://dikshantraj.dev/projects/shipsdna Links: [Website](https://www.shipsdna.com/) ## Role details ### Tech Lead (contract) — Jingo Technologies May 2025 – present · San Francisco (remote). AI-native commerce platform with voice and chat shopping agents. - Production voice shopping agent with tool calling, memory and checkout flows - Search and recommendations over 1.5M+ products with embeddings and Pinecone - Helped significantly reduce cloud costs - Lead a team of 4; own evals, prompt optimization and AI quality Stack: Nextjs, Reactjs, React Native, NestJs, FastAPI, PostgreSQL, Pinecone, GCP, Docker ### Full-stack Developer — ONBO Aug 2022 – Apr 2025. Employee onboarding and enablement SaaS. - Raised new-hire productivity by 35% - Built an internal Postgres RLS framework, shipped as a database extension - AI-driven personalized learning paths Stack: NestJS, Django, Python, PostgreSQL, PostgREST, Keycloak, SvelteKit, Docker ### Full-stack Developer (first 3 months as intern) — Decentral System Labs Jan 2022 – Aug 2022. Web3 analytics and fantasy sports. - Backend architecture for a Web3 analytics platform - Meta11: Web3 fantasy-sports MVP with ERC20/ERC721 contracts - Real-time backend flows with Express.js and WebSocket Stack: Node.js, Express.js, WebSocket, MongoDB, Solidity ### Full-stack Developer Intern — 3E Digital Solutions Oct 2020 – Jul 2021 · Remote. Progressive web apps and full-stack websites built with React and Laravel. - Created progressive web apps - Built website frontends with HTML, CSS, JavaScript, and React - Developed Laravel/PHP backends and custom REST APIs - Learned deployment on AWS Stack: HTML, CSS, JavaScript, React, Laravel, PHP, AWS ### Backend Developer Intern — Cillyfox Jul 2020 – Sep 2020 · Remote. PHP backend development for an intern management platform. - Developed the backend of an intern management platform using PHP - Completed assigned tasks ahead of deadlines Stack: PHP ## Articles ### Effortless React App Deployment: From Local to VPS 2024-11-13 · https://dikshantraj.dev/blog/effortless-react-app-deployment-from-local-to-vps Deploying a frontend application with a single click has become the new norm. These one-click solutions are powerful — they automate setup, build, and deployment processes, making it easy to get your site online with minimal effort. However, while these platforms simplify deployment, it’s valuable to understand the mechanics behind them, especially if you want more control over your hosting environment. React also makes deployment straightforward by allowing you to generate an optimized build for production. This build is a set of static files that can easily be served on any web server. When you run `npm run build` in your React project, React compiles and optimizes your app, creating files that are ready to deploy anywhere. In this guide, I’m using DigitalOcean, but you can use any cloud service provider or VPS provider. You just need SSH access. ![](https://dikshantraj.dev/blog/effortless-react-app-deployment-from-local-to-vps/1.png) 1. **Setup your digital ocean droplet** There are many guides available on how to provision a droplet on DigitalOcean, so you can follow one of those to get your droplet up and running. For the specifications, you don’t need anything too powerful — you’re not running an Iron Man suit here; you’re simply deploying a static application. For this purpose, any droplet with **1GB RAM**, **1 vCPU**, and **Ubuntu** installed will be sufficient. 2. **Connect to droplet using ssh** ```bash ssh root@your_droplet_ip ``` 3. **Installing Nginx, Node, and npm** We’ll need to install **Nginx **on our server to handle web traffic. Along with that, we’ll also install** Node.js **and** npm** to manage our packages and enable us to run the build process directly on the VPS. This setup will be useful if we want to establish a continuous integration (CI) process in the future, as it eliminates the need to manually copy the build directory to the VPS each time. ```bash sudo apt update && sudo apt upgrade -y curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - sudo apt install -y nodejs sudo apt install nginx -y sudo apt install git -y ``` 4. **Create a build of your application** React provides all the necessary tools to build your application, with the build command already defined in the `package.json` file. To create an optimized, production-ready build, simply run: ```bash npm run build ``` and you get the static files ready to be served. You can either create these static files on your local system and copy them to the server or build them directly on the VPS. To build on the VPS, clone your project repository, install dependencies, and follow the same build steps as you would locally. If you’d prefer not to create the build on the VPS, you can copy the locally-built static files directly to the server with this command: ```bash scp -r build/* root@your_droplet_ip:/var/www/your_project ``` **Permissions:** After copying files to `/var/www/your_project`, ensure the directory has the correct permissions to allow Nginx to access them: ```bash sudo chown -R www-data:www-data /var/www/your_project sudo chmod -R 755 /var/www/your_project ``` 5. **Configure nginx** a. **SSH into the VPS** Log in to your VPS via SSH: ```bash ssh root@your_droplet_ip ``` b. **Create a Server Block for Serving Your Application** Create a new Nginx configuration file for your project: ```bash sudo nano /etc/nginx/sites-available/your_project ``` Paste the following configuration: ```nginx server { listen 80; server_name your_domain_or_ip; root /var/www/your_project; index index.html; location / { try_files $uri /index.html; } } ``` c. **Enable the Configuration** Create a symbolic link from the `sites-available` directory to the `sites-enabled` directory: ```bash sudo ln -s /etc/nginx/sites-available/your_project /etc/nginx/sites-enabled/ ``` d. **Test and Restart Nginx** Test the Nginx configuration to ensure there are no syntax errors: ```bash sudo nginx -t ``` If the test is successful, reload Nginx to apply the changes: ```bash sudo systemctl reload nginx ``` That’s it! Now, you can visit your IP address or domain (as set in the Nginx server block) in a browser to check if your React app is up and running. If you don’t see your site as expected, it might be due to the firewall not being set up properly. To fix this, enable the firewall and allow traffic for Nginx by running the following commands on your server: ```bash sudo ufw allow 'Nginx Full' sudo ufw enable ``` This will allow **HTTP **and** HTTPS** traffic to reach your server. If you want to automate the deployment process using **Continuous Integration (CI)**, I will be writing a separate blog on that. The key difference would be serving the files from within the server using tools like `pm2` or `serve` for a more dynamic and automated approach. If you have any questions or doubts, feel free to leave a comment below. And if you found this blog helpful, don’t forget to give it a thumbs up! Your feedback is appreciated. Connect with me: 1. Twitter: [https://x.com/Dikshantrajpu20/](https://x.com/Dikshantrajpu20/) 2. Github: [https://github.com/dikshantrajput](https://github.com/dikshantrajput) 3. Medium: [https://dikshantraj2001.medium.com/](https://dikshantraj2001.medium.com/) ### Why Every Developer Needs a GitHub Profile README (+ Free Generator) 2024-10-21 · https://dikshantraj.dev/blog/why-every-developer-needs-a-github-profile-readme-free-generator In today’s competitive tech industry, every developer needs more than just great coding skills — they need a personal brand. GitHub, the world’s leading platform for open-source collaboration, is not only a place to host your code but also a window into who you are as a developer. A well-crafted GitHub profile README can play a crucial role in this. In this blog post, I’ll walk you through why every developer should have a GitHub profile README, the benefits of having one, and how you can easily create yours with my free **GitHub Profile README Generator**. ![](https://dikshantraj.dev/blog/why-every-developer-needs-a-github-profile-readme-free-generator/1.jpeg) _GitHub Profile_ #### What is a GitHub Profile README? A GitHub profile README is a special markdown file that appears at the top of your GitHub profile when created. It’s like a mini website that introduces you to anyone who views your profile. You can add stats, links to your projects, information about your skills, and even fun facts about yourself. Think of it as your developer portfolio, but embedded in the platform where you actually write code. #### Why Every Developer Needs One ##### 1. First Impressions Matter Your GitHub profile is often the first place potential employers, recruiters, or fellow developers will visit when they hear your name. While your code and projects are crucial, a well-structured profile README shows that you care about presentation. It’s an opportunity to communicate who you are, what you’ve worked on, and what you’re passionate about. ##### 2. Showcase Your Skills and Experience You can list your most used technologies, feature your top repositories, and display cool statistics like the number of stars and forks on your repositories. This transforms your profile from just a list of projects to a personal portfolio. Imagine browsing through your repositories and seeing an organized summary of your key skills — this instantly gives others a snapshot of your experience. ##### 3. Personal Branding In an age where personal branding is important, having a professional GitHub profile is essential. Your profile README can highlight what you’re currently working on, projects you’re most proud of, and even your thoughts on development trends. It’s a place to showcase your personality while letting others know what kind of developer you are. ##### 4. Get More Opportunities A well-maintained GitHub profile can lead to real opportunities. Open-source contributors, employers, and collaborators often search for developers on GitHub. A profile README can help you stand out by highlighting your most impressive work and providing context for your contributions. #### How to Manually Set Up a GitHub Profile README Setting up a GitHub profile README is straightforward. Here’s how you can do it in just a few simple steps: 1. **Create a New Repository:** - Go to GitHub and create a new repository. - Name the repository exactly as your GitHub username. For example, if your GitHub username is “dikshantrajput”, the repository should be named “dikshantrajput”. **2. Make the Repository Public:** - Ensure the repository is set to “Public.” This is important so that anyone can see your profile README. **3. Initialize the Repository with a README File:** - Check the box to initialize the repository with a README file. This file will act as your profile README. **4. Edit the README File:** - Once the repository is created, click on the `README.md` file. - Edit the file to add any information you’d like to showcase, such as a brief introduction, your skills, featured repositories, and more. **5. Commit Your Changes:** - Once you’re satisfied with your content, click “Commit changes” to save the file. Your README will now appear on your GitHub profile! **6. Optional Enhancements:** - You can customize your README further by adding badges, GitHub statistics, and dynamic content like most used languages, which make your profile stand out even more. #### Introducing the GitHub Profile README Generator While creating a GitHub profile README manually is easy, customizing it to make it professional and visually appealing can take time. To save you the hassle, I’ve built the **GitHub Profile README Generator**, a free tool that helps you create a personalized profile README with just a few clicks. With my free tool, you can create a well-crafted README file without worrying about markdown formatting or manually adding stats and visuals. Here’s what it offers: ##### Key Features of the GitHub Profile README Generator: - **Profile Stats**: Showcase your GitHub stars, forks, and contributions. - **Top Repositories**: Feature your most important projects. - **Technologies & Tools**: Display the programming languages and tools you use. - **Social Links**: Make it easy for others to connect with you on Twitter, LinkedIn, and more. - **Contributions graphs** - and much more… ##### How to Use the Generator: 1. **Login with GitHub**: Use your GitHub account to quickly access the tool. 2. **Generate and Preview**: Instantly see how your new profile README looks. 3. **Edit markdown:** Instantly edit your README markdown for minor modifications. 4. **Copy and Commit**: Once you’re happy with the result, copy the markdown file and commit it to your GitHub repository. It’s that easy! In just a few minutes, you can have a professional, eye-catching profile README that boosts your GitHub presence. With the **GitHub Profile README Generator**, creating a standout profile has never been easier. Whether you’re showcasing your skills, connecting with others, or landing your next opportunity, a well-designed profile README can make all the difference. Try it out here: [https://gh-readme-gen.vercel.app](https://gh-readme-gen.vercel.app) #### Contribute & Support If you like what you see, I’d really appreciate it if you could leave a ⭐ on the [GitHub Profile README Generator repository](https://github.com/dikshantrajput/github-profile-readme-generator). It helps spread the word and keeps me motivated to add more awesome features! I’ve also added some **good first issues** in the repository that anyone can work on. If you want to contribute or make modifications to suit your needs, feel free to dive in! Your contributions not only help improve the tool but also benefit others in the community. Let’s build this together and make GitHub profiles shine for everyone! ### Multi tenant scalable database architecture with data isolation 2024-07-17 · https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation **What is a multi tenant system:** A multi-tenant system allows multiple distinct groups (or tenants) to use the same software application without interfering with each other. Think of your database as a building with four floors, each rented out to a different tenant. Ideally, each tenant should only have access to their floor and not the others. #### Example Scenario Imagine you have a product where different organizations manage their internal knowledge bases. Naturally, each organization would not want others to access their data. This scenario exemplifies a multi-tenant product. There are 2 raw ways if you think of non overlapping access to the organization. ![](https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation/1.png) #### 1. Custom Logic in the Backend You can write custom logic to handle access control, ensuring users only access their organization’s data. Here’s an abstract example of such a function: ```js const userToken = request.headers["Authorization"]; const user = userToken.decode(); // Check if the user belongs to the organization by querying the database const organization = get_org_use_case(user.id, user.orgId); if (!organization) { throw new Error("User does not belong to the organization."); } ``` This logic needs to be implemented in each route. Using middleware can help streamline this process, but if you forget to add the middleware, it can lead to security issues. #### 2. Offload the Task to the Database This article focuses on implementing multi-tenancy at the database level. There are three straightforward ways to achieve this: There are 3 major straight forward ways: ##### Separate Database for Each Tenant ![](https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation/2.png) In this approach, a separate database is created for each new organization that signs up. This method provides strong data isolation since each organization’s data resides in a separate database. A high level code for this looks like: ```js const userToken = request.headers["Authorization"]; const user = userToken.decode(); const dbConn = // establish database connection with proper database depending on organization const queryResponse = await dbConn.query("Select * from xyz;") console.log(queryResponse) ``` Pros: - Strong isolation and security. Cons: - High cost and resource usage. ##### Separate Schema for Each Tenant ![](https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation/3.png) Schemas in a database act as logical groupings of resources, like directories containing files. By default, operations occur in a public schema. You can create a separate schema for each organization and switch to the appropriate schema based on the request. Let’s say organization A tables are in schema A and organization B tables are in schema B. Each time a request comes to database we will be selecting a specific schema for organization and then making subsequent queries. For keeping separate schema, you need to switch to the org schema when request comes in. This can be achieved by setting the search_path for each user database transaction or at request level. A high level code for this looks like: ```js const userToken = request.headers["Authorization"]; const user = userToken.decode(); await dbConn.query(`set search_path to ${user.orgSchema}`) // make subsequent calls ``` Add a middleware for switching the schema on runtime. So in every request this will run and for the subsequent request the schema will be set. Now you will say how is it different from the custom logic at code level. In this if you forget to add middleware it will result in no result as tables belongs to a particular schema this keeping tenant data isolated. Pros: - Good isolation with less overhead than separate databases. Cons: - Heavy implementation and management complexity. ##### Same Database, Same Schema, Same Table for Each Tenant ![](https://dikshantraj.dev/blog/multi-tenant-scalable-database-architecture-with-data-isolation/4.png) This approach uses a single database, schema, and set of tables for all tenants. Introduce a `tenant_id` column in each table to differentiate the data. Data isolation is enforced using **Row-Level Security (RLS)**, which applies policies to control data access at the row level. In RLS, each row is secured with a policy to access the data. If policy allowed the access, the data will be returned else no data will be returned. Think of this as a society security guard checking the access card before letting you go in. Pros: - Cost efficient and efficient Cons: - Designing scalable policies #### Conclusion Choosing the right multi-tenant architecture for your application depends on your specific needs and constraints. Whether you opt for separate databases, schemas, or a single database with row-level security, each approach offers unique advantages and challenges. I hope this article has provided a clear overview of the options available and helped you understand how to implement a scalable multi-tenant system. If you found this blog helpful, please like and share it. I would love to hear your thoughts and experiences with multi-tenant architectures, so feel free to leave a comment below. If you have any questions or need further clarification, don’t hesitate to reach out! ~ Dikshant Rajput ### Check user Online/Offline status 2024-07-04 · https://dikshantraj.dev/blog/check-user-online-offline-status Checking the online/offline status of a user is an essential feature for applications that heavily rely on network connectivity. Almost all websites today use APIs to fetch data from a server or third-party services. To ensure a smooth user experience, it is important to notify users when their network connection is lost or unstable. ![](https://dikshantraj.dev/blog/check-user-online-offline-status/1.png) There are multiple ways to check if a user is online or not: 1. **Polling**: In this method, a request is made at frequent intervals to a server or any domain address. If a successful response is received, the user is considered online. If an error occurs while calling the API, and the error is related to a network issue, the user is considered offline. 2. **Navigator**: The Navigator is a set of web APIs available in almost all browsers to help with commonly used tasks involving Bluetooth, clipboard, geolocation, etc. It also provides an `onLine` API to check whether the user is online or not. Additionally, the `window` object can be used to listen for the `online` and `offline` events. There are other methods like using WebRTC, but to keep things simple, let’s focus on the two methods mentioned above: 1. Polling: ```js let intervalId; const API_URL = 'http://localhost:5500/test.json'; const POLLING_INTERVAL = 3000; function checkOnlineStatus() { return fetch(API_URL, { method: 'GET', // to tell browser not to cache headers: { 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Expires': '0' }, cache: 'no-store' }) .then(response => { if (response.ok) { console.log("user is online"); return true; } throw new Error('Network response was not ok'); }) .catch(error => { console.log("user is offline"); return false; }); } function startPolling() { intervalId = setInterval(() => { checkOnlineStatus() .then(isOnline => { // do something like show toast or anything else to inform user about offline }); }, POLLING_INTERVAL); } startPolling(); // for cleanup window.addEventListener("beforeunload", () => { if (intervalId) clearInterval(intervalId) }) ``` In the above code, we are hitting `localhost:5500/test.json` file. We can make requests to any available URL that does not ends up in **CORS** error, such as small image files. The resource size should be small to minimize the overhead. Making an API call to a small public file, such as an empty file, is recommended. We have a `startPolling` function that makes an API call to check if `test.json` exists. If a response is received, the user is online. If no response is received, the user is offline. These API calls are made every 3 seconds, which is the essence of polling. **Note**: Be cautious about the resource consumption, as making API calls every few seconds can cause multiple issues. It is recommended to use the below method and fallback to polling if necessary. 2. Navigator.onLine ```js window.addEventListener('load', () => { function checkOnlineStatus() { if("onLine" in navigator){ const isOnline = navigator.onLine; if (isOnline) { console.log("User is online"); } else { console.log("User is offline"); } }else{ // fallback to polling } } window.addEventListener('online', checkOnlineStatus); window.addEventListener('offline', checkOnlineStatus); }); ``` In the above code, we use the window event listeners for `online` and `offline` events and the `navigator.onLine` property to check if the user is online or offline. Whenever there is a change in the network status, either online or offline, the window event will be fired. This method is simpler and does not involve any overhead. The `onLine` method in the navigator is available in almost all browsers, and if for some reason it is not available, you can fallback to polling. Thank you for reading! If you liked this blog, please hit the clap icon and follow me for more such hacky blogs. _~_** _Dikshant Rajput_** ### Chrome Extension 101: A Beginner’s Guide 2024-04-07 · https://dikshantraj.dev/blog/unlocking-the-power-of-chrome-extensions-a-beginners-guide **What is a browser extension?** Extensions are small software programs that customize the browsing experience. They enable users to tailor browsers functionality and behavior to individual needs or preferences. They are built on web technologies such as HTML, JavaScript, and CSS [source: Google]. In simpler terms, extensions are add-ons built on top of existing browsers to enhance the experience and smoothen functionalities that might not be provided by the browser itself. **What Powers a Chrome Extension?** The main driving force behind browser extensions are the Developer APIs that different browsers provide. Let’s take Google Chrome, a chromium-based browser, as an example to explore the APIs it offers for extension development: - [Tabs API](https://developer.chrome.com/docs/extensions/reference/api/tabs): This API enables you to manage tabs, including creating them, navigating between them, moving them, and performing other operations. Example: Let’s say you always want a particular webpage to be the first tab. You can use the `.move` function provided by the Tabs API to achieve this. - [Storage API](https://developer.chrome.com/docs/extensions/reference/api/storage): This is a powerful API offered by Chrome that allows you to use the browser’s local storage. It provides various functions like `.local`, `.managed`, `.session`, and `.sync`. This can be used for various purposes. Example: Imagine building a more advanced bookmarking system than Chrome’s default one. You could allow users to bookmark specific sections of a webpage. You could then leverage `.local` or even `.sync` to synchronize data across different devices. - [Runtime API](https://developer.chrome.com/docs/extensions/reference/api/runtime): This API allows you to execute code based on events in the extension’s lifecycle, such as installation, startup, or receiving messages. This can be used to perform actions like tracking user actions or executing background processes. There are many other APIs available, but these are some of the most commonly used ones. **Things required to create a chrome extension: Required Files:** - manifest.json - popup.html - content.js - background.js Let’s see what does all these contains: - **Manifest (version 3):** This JSON file contains metadata about your extension, including its name, description, version, icons, permissions, and which files are needed for different functionalities. ```json { "name": "", "description": "", "version": "", "manifest_version": 3, "icons": { "16": "path/to/image", "32": "path/to/image", "48": "path/to/image" }, "action": { "default_popup": "popup.html", "default_icon": "path/to/image" }, "background": { "service_worker": "path/to/sw", "type": "module" }, "content_scripts": [ { "js": [ "path/to/js" ], "matches": [ "*", "urls" ] } ], "permissions": [ "activeTab", "storage" ] } ``` “action”: This handles the appearance of the extension. “background”: This handles the service worker registration for handling events “content_scripts”: This specifies the js, css files and urls matches that tells on which url will these scripts be injected “permissions”: Shows what all api permissions are provided to this extension. - **popup.html:** This HTML file defines the content that appears when the user clicks on the extension icon. ![](https://dikshantraj.dev/blog/unlocking-the-power-of-chrome-extensions-a-beginners-guide/1.png) _Screenshot of extension’s popup appearing on click of icon_ - **content.js:** File containing javaScript code that will be getting executed having main logic for the extension. Example: ```js const findMultipleAdsComponent = () => { const multipleAdsComponent = document.querySelector(".abc") if (multipleAdsComponent) { const durationOfFirstAdComponent = document.querySelector(".xyz") if (durationOfFirstAdComponent) { const duration = durationOfFirstAdComponent.textContent return true } } return false } findMultipleAdsComponent() ``` - **background.js**: File in which we can register our service worker to listen to events. Example: ```js chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { if (message.action === 'adSkipped') { chrome.storage.local.get('adCount', function(data) { const adCount = data.adCount || 0; chrome.storage.local.set({ 'adCount': adCount + 1 }); }); } }); ``` The above file listens for event having object with a key names “action” and value “adSkipped”. Then we are just getting the local storage value with key ‘adCount’. Then we are just incrementing and setting that back again to local storage. In this blog post, we’ve explored the basics of Chrome extensions. In the next installment, I’ll be diving deeper and explaining how I built my YouTube ad skipper extension from scratch. In the meantime, feel free to check out the YouTube ad skipper extension here: [YouTube Skipper Chrome Extension](https://dikshantrajput.github.io/skip-yt-ad/) I’m eager to hear your feedback! Whether you have questions, comments, or suggestions, feel free to leave them below. I hope this blog post provided a valuable introduction to Chrome extensions. If you’d like to learn more or have any issues, feel free to leave a comment. Additionally, don’t forget to subscribe for updates on the next part of the series, where I’ll be building a YouTube ad skipper extension! ### Mastering Firestore Converters with TypeScript 2024-03-13 · https://dikshantraj.dev/blog/mastering-firestore-converters-with-typescript In this blog, I will cover how we can use Firestore converters and add types to our documents without relying on the `as` keyword. Let's begin ![](https://dikshantraj.dev/blog/mastering-firestore-converters-with-typescript/1.png) **What is a Firestore converter?** As specified in their [official docs](https://firebase.google.com/docs/reference/js/v8/firebase.firestore.FirestoreDataConverter), a converter allows you to specify generic type arguments when storing and retrieving objects from Firestore. In short, converters function as interceptors or middlewares between your code and Firestore. So basically, a converter is just a function returning an object with two keys: `toFirestore` and `fromFirestore`. The value of these keys are themselves functions that help manipulate types or data that we post to Firestore or retrieve from it. Let’s delve into how they work. ![](https://dikshantraj.dev/blog/mastering-firestore-converters-with-typescript/2.png) Let me illustrate this with an example. Suppose we have a Firestore collection named “post.” Now, whenever we insert a new document into the “post” collection, we want it to automatically have a `createdAt` timestamp field. Additionally, when we fetch any document from this collection, we want the document's ID to be included in the `data()` method of the document. Furthermore, we want the `createdAt` field to be converted into a Date object automatically, eliminating the need for explicit type casting elsewhere in our code. To achieve this, we can utilize the following code snippet: ```ts import { serverTimestamp, } from "firebase/firestore"; const postFirestoreConverter = { toFirestore: (item) => { return { ...item, createdAt: serverTimestamp() }; }, fromFirestore: (snapshot, options) => { const data = snapshot.data(options); return { ...data, id: snapshot.id, createdAt: data.createdAt?.toDate() }; } };ja ``` In the provided code, on line 6, the `toFirestore` property of the object is assigned a function that takes an `item` as input and returns an object with the `createdAt` field added to it. On line 12, the `fromFirestore` property of the object is assigned a function that takes a document snapshot's data as input and adds the `id` field to it. Additionally, it typecasts the `createdAt` field into a Date object. Now let’s try to create a generic document Firestore converter that can be used for any type with the above functionality with typescript: ```ts import { serverTimestamp, type QueryDocumentSnapshot, type SnapshotOptions, Timestamp } from "firebase/firestore"; import type { IPost } from "./x"; import type { IUser } from "./x"; const createFirestoreConverter = () => { return { toFirestore: (item: T) => { return { ...item, createdAt: serverTimestamp() }; }, fromFirestore: (snapshot: QueryDocumentSnapshot, options?: SnapshotOptions) => { const data = snapshot.data(options); return { ...data, id: snapshot.id, createdAt: data.createdAt?.toDate() }; } }; }; export const userFirestoreConverter = createFirestoreConverter(); export const postFirestoreConverter = createFirestoreConverter(); ``` In the provided code snippet, a utility function has been crafted to generate Firestore converters for various document types. Let’s dissect the code: The helper function employs a generic type constraint, extending an interface featuring a `createdAt` key. The resultant object from this function encapsulates two keys as elaborated earlier, augmented with typed implementations. **How to use them?** ```ts const docRef = doc(firebaseDb, "users", "docId").withConverter(userFirestoreConverter); const user = await getDoc(docRef); const data = user.data(); ``` Firebase provide a method named `withConverter` to add a converter with the document. In the above code we are getting a user document. The type of data would be of `IUser`. ```ts await addDoc( collection(firebaseDb, "users").withConverter(userFirestoreConverter), payload ); ``` In the provided code snippet, when creating a user document using `userFirestoreConverter`, the converter automatically adds the `createdAt` field with the server timestamp to the Firestore document. Therefore, there's no need to include `createdAt` in the payload that is passed to Firestore. Thanks for reading the blog. If you found it helpful, don’t hesitate to show your appreciation by clicking the clap icon. For any further assistance or questions, feel free to leave a comment below. Your feedback is highly valued! ### NAT, STUN, TURN and ICE 2024-02-26 · https://dikshantraj.dev/blog/nat-stun-turn-and-ice In networking while building a p2p application, you might have heard about NAT, STUN , TURN and ICE. So what exactly are these? Let’s look into them with the help of an analogy. ![](https://dikshantraj.dev/blog/nat-stun-turn-and-ice/1.png) Let’s start by the definition first: [**NAT**](https://en.wikipedia.org/wiki/Network_address_translation)**: Network address translation **(**NAT**) is a method of mapping an IP [address space](https://en.wikipedia.org/wiki/Address_space) into another by modifying [network address](https://en.wikipedia.org/wiki/Network_address) information in the [IP header](https://en.wikipedia.org/wiki/IP_header) of packets while they are in transit across a traffic [routing device](https://en.wikipedia.org/wiki/Router_%28computing%29). [**STUN**](https://en.wikipedia.org/wiki/STUN)**: **(**Session Traversal Utilities for NAT**; originally **Simple Traversal of User Datagram Protocol (UDP) through Network Address Translators**) is a standardized set of methods, including a network protocol, for [traversal](https://en.wikipedia.org/wiki/NAT_traversal) of [network address translator](https://en.wikipedia.org/wiki/Network_address_translator) (NAT) gateways in applications of real-time voice, video, messaging, and other interactive communications. [**TURN**](https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT)**: Traversal Using Relays around NAT **(**TURN**) is a [protocol](https://en.wikipedia.org/wiki/Communications_protocol) that assists in traversal of [network address translators](https://en.wikipedia.org/wiki/Network_address_translator) (NAT) or [firewalls](https://en.wikipedia.org/wiki/Firewall_%28networking%29) for multimedia applications. It may be used with the [Transmission Control Protocol](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) (TCP) and [User Datagram Protocol](https://en.wikipedia.org/wiki/User_Datagram_Protocol) (UDP). It is most useful for clients on networks masqueraded by [symmetric NAT](https://en.wikipedia.org/wiki/Symmetric_NAT) devices. TURN does not aid in running [servers](https://en.wikipedia.org/wiki/Server_%28computing%29) on well known ports in the private network through a NAT; it supports the connection of a user behind a NAT to only a single peer, as in telephony, for example. [**ICE**](https://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment): **Interactive Connectivity Establishment **(**ICE**) is a technique used in [computer networking](https://en.wikipedia.org/wiki/Computer_networking) to find ways for two computers to talk to each other as directly as possible in [peer-to-peer](https://en.wikipedia.org/wiki/Peer-to-peer) networking. This is most commonly used for interactive media such as [Voice over Internet Protocol](https://en.wikipedia.org/wiki/Voice_over_Internet_Protocol) (VoIP), [peer-to-peer](https://en.wikipedia.org/wiki/Peer-to-peer) communications, video, and [instant messaging](https://en.wikipedia.org/wiki/Instant_messaging). These are the wiki definitions and one do not understands much in them. So let me try to explain what are these. So first of all the basic use case is that we need 2 parties to talk to each other with as less resource utilization as possible and also latency should be as minimal. Let’s say client1 wants to video call client2. The basic thing that one needs to enable 2 systems to talk to each other is a connection between them over the internet. One way to do this is by adding a server in the middle of 2 clients and letting them connect to the server. The server takes in data from client1 and sends it to client2.  If we were to do this, we need the server to be as close as possible to both the clients to reduce the latency. We can do this by adding multiple servers in different locations but that would cost a lot and also the resource needed to transfer data between 2 clients is heavy. Now let’s assume we have a way to connect the 2 devices to each other (the way will be discussed later). now the data that is being transferred does not have to jump between multiple locations so latency is less also the resource utilization will be relatively less. Now let’s talk about the basic protocols that are available to use for communication. i.e. TCP and UDP. [**TCP**](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) (Transmission control protocol) provides [reliable](https://en.wikipedia.org/wiki/Reliability_%28computer_networking%29), ordered, and [error-checked](https://en.wikipedia.org/wiki/Error_detection_and_correction) delivery of a [stream](https://en.wikipedia.org/wiki/Reliable_byte_stream) of [octets](https://en.wikipedia.org/wiki/Octet_%28computing%29) (bytes) between applications running on hosts communicating via an IP network. [**UDP**](https://en.wikipedia.org/wiki/UDP-based_Data_Transfer_Protocol) (user datagram protocol) is a high-performance data transfer protocol designed for transferring large volumetric datasets over high-speed [wide area networks](https://en.wikipedia.org/wiki/Wide_area_network). It is suitable for purposes where error checking and correction are either not necessary or are performed in the application. Within an IP network, UDP does not require prior communication to set up [communication channels](https://en.wikipedia.org/wiki/Communication_channel) or data paths. From these 2 protocols, UDP will be better as we do not need every data buffer to reach destination. We are okay if some data buffers are missed i.e. some frames in the video call is missed. So till now we have seen what we need. now let us see what all we need to establish a direct channel between 2 devices: - Ip’s of both the parties - Port number - Open Sockets Each device connected to internet have it’s IP address assigned and we need to share these addresses between 2 devices that are willing to share data. But there is 1 more caveat here, the devices that are connected to a NAT device or behind a firewall does not know it’s IP address and port Let’s consider a scenario where two clients, client1 and client2, are behind NAT devices (routers). Client1 has its private IP address, let’s call it “IP1,” but it’s not aware of it. Similarly, client2 also has a private IP address, say “IP2.” These clients are connected to the internet through their respective NAT devices, each with its own public IP address, let’s call them “Public IP 1” and “Public IP 2.” When client1 and client2 want to share data, they typically need to route their data through their NAT devices, acting as middlemen. However, if client1 and client2 were aware of their respective IP addresses, sharing data would be much simpler. This is where STUN (Session Traversal Utilities for NAT) servers come in handy. STUN servers serve a simple yet crucial purpose: they provide clients with their own IP addresses and port numbers upon request. Client1, for instance, can send a request to the STUN server, which will respond with its private IP address and port number. Similarly, client2 can obtain its information from the STUN server as well, even if it’s behind a NAT device or firewall. However, there are instances where STUN servers fail to fulfill this task effectively. In such cases, TURN (Traversal Using Relays around NAT) servers step in. TURN servers act as relays between two clients, allowing them to exchange data indirectly. While TURN servers operate similarly to traditional servers by receiving and transmitting data, they do so only between the connected clients, preserving their privacy. Nonetheless, when communication occurs via a TURN server, it is no longer a direct peer-to-peer connection. In practice, STUN and TURN servers are often used together to ensure efficient data transmission between clients, such as from client1 to client2, even when they are behind NAT devices. This combined approach helps overcome various network limitations and ensures seamless communication. **STUN Server:** In essence, a STUN server facilitates clients behind firewalls and NAT devices in establishing direct communication with other clients by providing them with their private IP address and port number. ![](https://dikshantraj.dev/blog/nat-stun-turn-and-ice/2.png) **TURN Server:** Similarly, a TURN server operates by relaying data from point A to point B, enabling communication between clients, especially when direct peer-to-peer connections are not feasible due to network constraints or any other failures in STUN. ![](https://dikshantraj.dev/blog/nat-stun-turn-and-ice/3.png) **ICE Protocol:** ICE (Interactive Connectivity Establishment) serves as a protocol orchestrating these connections. It empowers devices to explore various communication options (such as utilizing STUN or direct peer-to-peer connections) and selecting the most efficient one. ICE executes several essential functions, including gathering candidates, checking connectivity, negotiating, and ultimately establishing connections. This ensures optimal communication while minimizing reliance on intermediaries. Let me give an analogy now, Imagine **Rahul **and** Simran **are students in the 1st grade, and they want to talk to each other without involving any adults. Rahul needs to know where Simran sits in the classroom, and vice versa. However, being in the 1st grade, they might not remember their own desk numbers. So, they decide to ask their** teacher **for help, who then tells them their respective desk numbers. In this scenario, the teacher represents the** STUN** server, assisting Rahul and Simran in finding each other’s locations. Now, let’s say Rahul and Simran prefer not to ask the teacher for help. Instead, they decide to exchange letters directly. To do this, they write letters to each other and hand them to the school’s **postman**, who delivers the letters between their desks. This postman acts like a **TURN** server, relaying messages between Rahul and Simran when direct communication isn’t possible. In this setup, ICE (Interactive Connectivity Establishment) steps in to help Rahul and Simran establish a channel for communication. ICE coordinates the process, ensuring that Rahul and Simran can exchange messages efficiently, whether it’s through the teacher (STUN server), the postman (TURN server), or directly between themselves. ### Retry failed request using Axios interceptors 2024-02-07 · https://dikshantraj.dev/blog/retry-failed-request-using-axios-interceptors ![](https://dikshantraj.dev/blog/retry-failed-request-using-axios-interceptors/1.png) In my previous blog post, I discussed interceptors, including Axios interceptors. To continue with this blog post, it’s essential to have a quick read through the previous content or be familiar with the concept of Axios interceptors and how response interceptors function to intercept responses and continue the flow [Manipulating request and response with axios interceptors](https://dikshantraj.dev/blog/manipulating-request-and-response-with-axios-interceptors) Let’s start with the blog now. There may be cases where we need to retry certain requests if they fail or if there’s a need to resend the request. Some of the popular use cases are: - **Network failures** In cases where a user’s network is slow or disconnected, retrying the failed request could prove beneficial. - **Fallback to backup service** Imagine having two email clients, and if one fails for some reason, it’s prudent to retry the request with the second client. This situation can arise with both external dependencies and internal services. - **Throttled endpoints** Certain endpoints or APIs allow a user to hit them a limited number of times within a specific timeframe. Implementing middleware to retry failed requests after a delay can be advantageous if we encounter throttled errors. - **Rate limiting** Similar to throttled endpoints, there may be instances of rate-limited endpoints where requests are restricted within a certain rate. Let’s see how we can retry requests on specific errors _axios-retry-request-interceptor.js_ ```js function createAxiosInstanceForRetryingRequest(serviceBaseUrl, maxRetries = 3) { const axiosInstance = axios.create({ baseURL: serviceBaseUrl, }); let count = 1; axiosInstance.interceptors.response.use( undefined, function (error) { const requestConfig = error.config // retry current request with a different base url i.e. different service if (error.code === "ECONNREFUSED" && count++ <= maxRetries) { console.log({count, url: requestConfig.baseURL}) if(count === 1){ requestConfig.baseURL = "PAYMENT_SERVICE_BASE_URL_2" }else if(count === 2){ requestConfig.baseURL = "PAYMENT_SERVICE_BASE_URL_3" } return axiosInstance(requestConfig); } return Promise.reject(error); }, ); return axiosInstance; } (async () => { const instance = createAxiosInstanceForRetryingRequest( "PAYMENT_SERVICE_BASE_URL_1", ); try{ await instance.get('non-exsiting') }catch(error){ console.log("Failed with error: ",error.message) } })(); ``` In the provided code snippet, an Axios interceptor is implemented. Here’s an explanation of the key points: 1. Line 2: We utilize the `axios.create` method with the `baseURL` option to instantiate an Axios instance. 2. Line 8: Axios response interceptors are employed, accepting request and response callbacks. Since we only require the response callback, we specify `undefined` as the first parameter. The second parameter is a function responsible for handling response. 3. Line 13: We check if the error has a code of `ECONNREFUSED` indicating a timeout or refusal of connection by the service. Additionally, a count is maintained to track the number of retry attempts. If the count exceeds the maximum allowed retries, the request won’t be retried. 4. Line 16: Depending on the current retry count, the base URL is updated accordingly. For instance, if the count is 1, it updates to “PAYMENT_SERVICE_BASE_URL_2”; if it’s 2, it updates to “PAYMENT_SERVICE_BASE_URL_3”. 5. Line 20: The instance with the updated configurations is returned. 6. Line 22: If none of the retry attempts are successful or the maximum retry count is reached, the promise is rejected with the encountered error. Note: It’s crucial to exercise caution when implementing retry mechanisms to prevent potential infinite loops. Always verify the type of error encountered before attempting a retry. Additionally, consider introducing a delay between retries to mitigate potential issues. If you’re interested, I can provide code for incorporating a delay between retry attempts. Feel free to experiment with the provided guidance and share your findings in the comment section below. Thanks for reading the blog. If you found it helpful, don’t hesitate to show your appreciation by clicking the clap icon. For any further assistance or questions, feel free to leave a comment below. Your feedback is highly valued! ### Manipulating request and response with axios interceptors 2024-01-29 · https://dikshantraj.dev/blog/manipulating-request-and-response-with-axios-interceptors Axios interceptors can be used to handle errors throughout the application and as today’s state of backend demands multiple microservices for different use cases/ features, These come at a cost for frontend applications to handle multiple api urls built by different developers. Along with this, frontend will also need to handle multiple types of authentications, errors and responses coming from these microservices and this lead to increasing complexity in project as well as increasing variability throughout. Error handling is always a part that no one likes to do but has to as stated in [**Murphy’s law**](https://davetgc.com/Murphys_Law.html) > Anything that can go wrong will go wrong. ![](https://dikshantraj.dev/blog/manipulating-request-and-response-with-axios-interceptors/1.png) **Authentication:** There are different methods for a backend application to authenticate a request and determine which user called the service. The most commonly used method is by a [JWT](https://jwt.io/introduction) token where the backend expects an encoded token. While using Oauth 2.0 [Bearer tokens](https://oauth.net/2/bearer-tokens/) are the widely used tokens. It simply means attaching a `Bearer` string to the jwt token. **Error Handling:** There are different standards of errors being thrown. Different organizations use different formats. Also any third party api provider will have their fixed set of errors. To handle these many types of errors and convert them into a type that our frontend understands often becomes a cumbersome task. **Response modifications:** Frontend tends to use responses in a certain format and different microservices send data in different formats. Let’s say we need to show a list of tasks to be done by the user today. Some might send data in this format: ```json { "count":"20", "data": [...] } ``` While others might send data like this: ```json { "results":[] } ``` **Retry certain requests:** There may be cases where one needs to retry a request whether it is after failure or in any other case. This one, I will be discussing in my next blog. So handling state of request as well as responses coming from different microservices becomes a crucial part of every frontend application. There are multiple ways to do that: - Creating helpers for making api calls and then handling responses as well as errors - Extending the fetch method - Using axios interceptors Today, we will be discussing about [**axios interceptors**](https://axios-http.com/docs/interceptors) Axios is the most popular library for making requests to web urls. As the name suggests, it is an interceptor. Axios provides a way to intercept the ongoing request as well as the incoming response to either modify it or reuse it. 1. Let’s create a request interceptor to send authorization tokens in headers in each request while hitting the api of authentication microservice. _axios-interceptor-for-adding-token.js_ ```js // interceptor for setting token in every request of authenticationService function createAxiosInstance(serviceBaseUrl){ const axiosInstance = axios.create({ baseURL: serviceBaseUrl }) axiosInstance.interceptors.request.use(function (request) { // depending on service, add token to request if we are calling base url of auth service if(serviceBaseUrl === autheticationServiceBaseUrl){ const token = "xxx.xxx.xxx" request.headers.Authorization = `Bearer ${token}` } return request; }, function (error) { return Promise.reject(error); }); return axiosInstance } ``` In the above code snippet, we have created a function that returns an axios instance that has a request interceptor attached to it for adding a Bearer token to request headers with Authorization key if the service is an authentication service. 2. Let’s create an interceptor for modifying the response in the format we need. _axios-interceptor-for-response-modification.js_ ```js function createAxiosResponseConvertorInstance(serviceBaseUrl){ const axiosInstance = axios.create({ baseURL: serviceBaseUrl }) const authenticatedUser = { id: "user-id", name: "sample-name", profilePic: "https://abc.com/profile-pic.jpg" } // let's say we always need a response with service name that produces the response axiosInstance.interceptors.response.use(function (response){ if(serviceBaseUrl === autheticationServiceBaseUrl){ const data = response.data if(Array.isArray(response.data)){ response.data = { service: "authentication", items: data } }else{ // assuming data to be an object response.data.service = "authentication" } } // let's say in payment service we always need a response which have current user details attached to it if(serviceBaseUrl === paymentServiceBaseUrl){ // assuming data to be an object response.data.user = authenticatedUser } return response; }, function (error){ return Promise.reject(error); }) return axiosInstance } ``` In the above code snippet, we have created a function that returns an axios instance that has a response interceptor attached to it for adding service name if we are calling authentication service else if we are calling payment service, adding a user object to response. 3. Let’s create an interceptor for handling errors occuring in api call of different microservices _axios-interceptor-for-response-error-handling.js.js_ ```js class CustomError extends Error{ constructor(message, code, service){ super(message) this.statusCode = code; this.message = message; this.service = service; } } function createAxiosInstanceForErrorHandling(serviceBaseUrl) { const axiosInstance = axios.create({ baseURL: serviceBaseUrl, }); axiosInstance.interceptors.response.use( function (response) { return response; }, function (error) { // if error is a type of axiosError if(error instanceof axios.AxiosError){ // depending on service, handle error or throw custom error of your format if (serviceBaseUrl === autheticationServiceBaseUrl){ throw new CustomError(error.code, error.message, "authentication") }else if(serviceBaseUrl === paymentServiceBaseUrl){ throw new CustomError(error.code, error.message, "payment") } } return Promise.reject(error); }, ); return axiosInstance; } ``` In the above code snippet, we have created a function that returns an axios instance that has a response interceptor attached to it for throwing custom errors if anything went wrong. It can be enhanced to handle errors more gracefully and manage state in frontend applications. Thanks for reading the blog. If you like it, don’t forget to hit the clap icon. If you need any help leave a comment below. ### Setup google analytics 4 with Sveltekit ^1.0 2023-06-25 · https://dikshantraj.dev/blog/setup-google-analytics-4-with-sveltekit-1-0 ![](https://dikshantraj.dev/blog/setup-google-analytics-4-with-sveltekit-1-0/1.png) Since Google Analytics introduced GA 4, there is many changes in the basic setup of a Google project, They have introduced the concept of properties and streams to differentiate between different parts of the application which is far superior to the universal one. Today, I will be explaining the code for integrating of google analytics 4 with Sveltekit 1.0 + which has folder-based routing. The blog does not cover setting up a project and getting the integration script from the analytics console. There are many resources that will help you get it done. #### **Approach** Let me explain the basic approach first, In the parent +layout.svelte, we will be adding our script for google analytics that we get from the dashboard. For this, we will simply create a component and include that component in our layout file. Then we will be creating a store for storing all the events and will just subscribe to that store in the component and send the event to the google analytics platform. On whichever page(+page.svelte) we want to add events, we will just add the event data to the store and due to subscription, the store will execute that event. Think of something like a queue. One thing to note is that we can not send data from our +layout.ts or +page.ts directly to analytics as the GA script will not be initialized in these ts files. Though we can send data if the user changes route from within the application but on refresh we can not send data #### **Code** As the approach, we will first be creating a Analytics.svelte file and the code of this file is: _Analytics.svelte_ ```svelte ``` In the above file, we are adding the script tag in `svelte:head` tag so that it gets attached to tag in HTML on render. I will be explaining the analyticsStore subscription code after I explain how we will be adding data to the store. _analyticsStore.ts_ ```ts import { writable } from 'svelte/store'; export const analyticsStore = writable([]); ``` In the above code, we are just creating a store and assigning an empty array as the initial value _+layout.svelte_ ```svelte ``` In the +layout.svelte file, we are just importing and calling the Analytics component In any +page.svelte file, add the following code _+page.svelte_ ```svelte import { analyticsStore } from '...'; const new_event = { id: "any-random-id", data: {}, //anything you want to send to GA, event: "name-of-your-event", type: "event", } analyticsStore.update(existing_events => [ ...existing_events, new_event ]) ``` This will add a new event object to the store and the event will be sent to the google analytics platform. Now as we have seen the addition of data to analyticsStore(basically updating the store). Let’s get back and understand what we were doing while subscribing to the store _store_subscription_snippet.ts_ ```ts // subscribe to store and see if there is any event in store(array) then run that event analyticsStore.subscribe((queue) => { let next = queue && queue.length && queue.shift(); let retries = 3; let previousExecutedOperationId; while (next) { const { type, event, data, id } = next; if (!type || !event || !data || !id) { console.log('Incorrect analytics event data'); next = queue.shift(); continue; } // if current id is not equal to previous id then reassign retries to 3 if (id && id !== previousExecutedOperationId) retries = 3; previousExecutedOperationId = id; // @ts-ignore if (typeof gtag !== 'undefined') { // @ts-ignore gtag(type, event, data); console.log('event created with data', next); } else { // gtag not found, retry till retries become 0 if (retries > 0) { retries--; continue; } else { console.log('Analytics event failed to reach server with: ', next); } } next = queue.shift(); } }); ``` Let’s go line by line, 2. I am just subscribing to the store, In Sveltekit when you subscribe to a store, you get notified when anything in it gets changed, We will take advantage of this. 3. We are just considering that the value we get as a part of the queue(natively array for us). In the variable named `next` we are adding the first value of the array that is present in the updated store (There can be multiple events at once that are pushed to the store. It is important to send all the events in the same order) 4. `retries` is a variable that keeps track of retry for the current transaction i.e. a current event that is failed 5. We are checking if the data is correct or not i.e. it has id, event, data to send and type of event to be sent. If anything is missing we will just replace the value of the next variable and continue from the while loop. 18. We are checking whether the previous id value is the same as the current one or not. If not then we will increase the retries to again 3. 20. Then we are assigning the previous id variable to the current id 25. We are checking whether gtag is available or not i.e. script has been loaded or not 29–31. We are checking if the retries are greater than 0 then reduce the retries and again run the while loop for the same item/event. 36. We are updating the next variable to hold the next value in the array. **Note:** This is not the best approach and it can be improved further by adding time-based retries. If you have any issues or want to ask anything, do comment below and If you like the blog, don’t forget to hit the clap icon. ### Deploying svelte kit application 2022-12-20 · https://dikshantraj.dev/blog/deploying-svelte-kit-application ![](https://dikshantraj.dev/blog/deploying-svelte-kit-application/1.png) With the announcement of the stable release of sveltekit 1.0, there are many movements going around in svelte space and I have been exploring svelte and sveltekit for a while. Deploying a sveltekit app is not explained anywhere properly. So, in this blog, I will be explaining how to deploy a sveltekit application. **Prerequisites** - A sveltekit application. - A server to host or an instance to deploy(digital ocean, AWS ec2, etc). Once you are ready with both of these, let’s get started and deploy our sveltekit application. - Add your application to the server via GitHub or a zip file. - Install all required packages. - Install sveltekit node adapter from here [https://www.npmjs.com/package/@sveltejs/adapter-node](https://www.npmjs.com/package/@sveltejs/adapter-node) - In your svelte.config.js file, paste this content _svelte.config.js_ ```js import adapter from '@sveltejs/adapter-auto'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ out: 'directory-name' }), } }; export default config; ``` - Run `npm run build` - Check for errors if any. - Download `[pm2](https://pm2.keymetrics.io/)` for running node process in the background. - Travel to the directory where the build has been created. - Run `pm2 start index.js --name ` - Your site will start running on IP:3000. - If you want to change PORT, you can pass the HOST and PORT variables like this `HOST=127.0.0.1 PORT=4000 npm run build` NOTE: To check logs go to `pm2 logs ` Thanks for reading the blog. If you like it, don’t forget to hit the clap icon. If you need any help leave a comment below. ### GraphQL shield for authorization 2022-09-24 · https://dikshantraj.dev/blog/graphql-shield-for-authorization Shield is an easy way to add authorization on GraphQL. It’s a library that helps you create a permission layer for your server. e.g Let’s suppose you need to create a layer where you want your APIs to be secured from unauthorized access i.e who is accessing what? Authorization plays an important part in any website and in one way or another, one needs to implement authorization to prevent protected/forbidden pages from public view. Ways to add authorization in your GraphQL: - **In all resolvers** You can add permissions in each and every resolver and can respond according to that. But it won’t be a convenient way and will be against the DRY principles. ![](https://dikshantraj.dev/blog/graphql-shield-for-authorization/1.jpeg) Permissions are with every resolver and every resolver is accountable for handling authorization. - **Using GrapghQL Shield** GraphQL shield is a library that provides a way to set permissions at the server level and throws an error if permissions are not met for the current user. ![](https://dikshantraj.dev/blog/graphql-shield-for-authorization/2.jpeg) In this blog, I will be writing about how to use GraphQL shields. So let’s get started. **Install** ```bash npm install graphql-shield ``` **Set up permissions** _permissions.js_ ```js import { rule } from 'graphql-shield' export const isAuthenticated = rule({ cache: false })( async (parent, args, ctx) => { return ctx.user !== null } ) export const isAdmin = rule()(async (parent, args, ctx) => { if (ctx.user.role !== 'admin') return new Error('User is not admin') return ctx.user.role === 'admin' }) ``` I have defined two permissions currently in the file above - isAuthenticated — checks whether the user is logged in or not - isAdmin — checks whether the user is admin or not depending on the role. You can define more such permissions like isPublisher, isSuperAdmin, canUpdate, etc… **Create a middleware** _authMiddleware.js_ ```js import { shield } from 'graphql-shield' import { isAuthenticated } from './permissions.js' export const authMiddleware = shield({ Query: { users: isAuthenticated, } }) ``` shield accepts an object where we can define the permissions applicable on the different schema levels. Here user's schema query will only be visible to the user who is authenticated else it will throw an error. Like this, you can define more permissions and can authorize different schema based on the role of the user. You can also merge two permissions. Read more about the rules here [Rules - GraphQL Shield](https://www.graphql-shield.com/docs/rules#logic-rules) That’s it for this blog. If you have anything to ask, put it in the comments section and if you like this blog, don’t forget to hit the clap icon and follow me for more such blogs. Drink water. Keep smiling… ### Is using offset in SQL a hero or a silent evil? 2022-09-22 · https://dikshantraj.dev/blog/is-using-offset-in-sql-a-hero-or-a-silent-evil Pagination is one of the common things that every backend dev has to perform on API whether it is REST or GraphQL. Pagination is the process of dividing the huge set of data into small pieces called pages. Let’s suppose you have 10,000 rows of posts in DB. You won’t be emitting everything at one go as it can easily bottleneck your server and the loading time would be also high. In this case, you should divide your data into small pieces like in sets of 10, 20, or as you wish. > Dividing a huge chunk of data into small chunks is called pagination. An approach for pagination is by using limits and offsets that almost every DB supports. In this approach, offset is the number from which the result should start, and limit is the number of items you want to get. ![](https://dikshantraj.dev/blog/is-using-offset-in-sql-a-hero-or-a-silent-evil/1.png) In the above image as you can see there is a total of 7 records and you have to show just 2 records at initial load, the query will become: ```sql select * from table offset 0 limit 2 ``` To get an offset of the next set of results just use this formula ```sql new_offset = limit + prev_offset ``` Most of the products that are in production use this approach to get data paginated from the database. This approach is the most basic and easiest to implement but it has a serious downside. **The downside of using offset** Do you know how the database engine gets data after offset value? > So a db engine have to do a complete lookup that means they have to traverse all the way from 0 to offset and get the results. This can have serious performance issues if we have a large dataset. Let’s suppose we have 1,00,000 rows in our DB and we want the last two results then our query will be something like: ```sql select * from table offset 99998 limit 2 ``` The DB engine will go all the way from the 0th row to the 99998th row until it finds the offset value and then gets the last two results which you might have guessed by now can have a huge impact on the performance of the query. A better approach can be using cursors that give better performance than this offset approach. I will explain that approach in the next blog. So that’s it for this blog. I hope you liked the blog and if you do, don’t forget to hit the clap icon and follow me for more such blogs. Drink water. Keep smiling… ### Sequelize with expressjs and postgres 2022-09-20 · https://dikshantraj.dev/blog/sequelize-with-expressjs-and-postgres In my previous blogs, I discussed setting up [expressjs](https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min), [middleware](https://dikshantraj.dev/blog/express-middlewares-in-2-min), and jwt token [authentication](https://dikshantraj.dev/blog/authentication-in-express-with-jwt-in-2-min). In this blog, I will be writing about connecting the express application with DB(Postgres) using the sequelize ORM library. Let’s get started. Prerequisites: - Postgres DB (download it from [here](https://www.postgresql.org/download/)) - expressjs application - sequelize ORM package I won’t be covering the setting up of express application as I have covered it in the past. I assume you have your express application configured. Let’s download the sequelize and node Postgres packages ```bash npm install pg npm install sequelize ``` Start the downloaded Postgres server and open up a command prompt and run ```sql postgres --version ``` Note: If you want to access Postgres in the command line write this command: ```sql psql or psql -U postgres ``` This will confirm that Postgres is installed on your system and remember the password set while installing the Postgres server. This will be used to connect with the DB. Create a file and name it db.js or anything you want. ![](https://dikshantraj.dev/blog/sequelize-with-expressjs-and-postgres/1.png) The Sequelize class expects 4 parameters - DB name - DB username - DB password - Object with DB host and dialect NOTE: dialect is the DB name like Postgres, MySQL, sequelite, etc. sequelize.authenticate() will check whether the connection is made successfully or not. Let’s create a user model and apply crud operations on it and expose it using API. Create a models directory and a User.js file in it _User.js_ ```js import { DataTypes, Model } from "sequelize"; import { sequelize } from "../db.js"; export default class User extends Model{} User.init({ id:{ type:DataTypes.BIGINT, allowNull: false, primaryKey:true, autoIncrement:true }, fname:{ type:DataTypes.STRING, allowNull:false }, lname:{ type:DataTypes.STRING, allowNull:true }, email:{ type:DataTypes.STRING, allowNull:false }, password:{ type:DataTypes.STRING, allowNull:false }, createdAt:{ type:DataTypes.DATE, allowNull:false, defaultValue: DataTypes.NOW }, updatedAt:{ type:DataTypes.DATE, allowNull:false, defaultValue: DataTypes.NOW } },{ sequelize:sequelize, timestamps:true, tableName:'users', modelName:'User' }) ``` Create a routes directory and a user.js file in it. _user.js_ ```js import { Router } from "express"; import User from "../models/User.js"; export const userRouter = Router() userRouter.get("/",async (req,res)=>{ const users = await User.findAll() return res.json({data:{users}}) }) ``` The above function will get all the users from db using the findAll() method. _user.js_ ```js userRouter.get("/:id",async (req,res)=>{ const {id} = req.params const user = await User.findOne({where:{id}}) return res.json({data:{user}}) }) ``` This will fetch a single user based on the id given. _user.js_ ```js userRouter.post("/",async (req,res)=>{ const {fname, lname, email, password} = req.body try{ const user = await User.create({fname,lname,email,password}) return res.json({data:{user}}) }catch(err){ if(err.name === 'SequelizeValidationError'){ return res.json({message:err.errors[0].message}) } console.log(err) return res.json(err) } }) ``` This will create a new user. _user.js_ ```js userRouter.put("/",async (req,res)=>{ const {id, fname, lname, email, password} = req.body try{ const isUpdated = await User.update({fname,lname,email,password},{ where:{ id } }) if(isUpdated[0]) return res.json({data:{message:true}}) }catch(err){ return res.json({err}) } return res.json({data:{message:false}}) }) ``` This will update the user based on the id given. _user.js_ ```js userRouter.delete("/",async (req,res)=>{ const {id} = req.body try{ const isDeleted = await User.destroy({ where: { id } }) if(isDeleted) return res.json({data:{message:true}}) }catch(err){ return res.json({err}) } return res.json({data:{message:false}}) }) ``` This will delete the user based on the id given. Check the database after performing all the operations. The complete file will look something like this: _user.js_ ```js import { Router } from "express"; import User from "../models/User.js"; export const userRouter = Router() userRouter.get("/",async (req,res)=>{ const users = await User.findAll() return res.json({data:{users}}) }) userRouter.get("/:id",async (req,res)=>{ const {id} = req.params const user = await User.findOne({where:{id}}) return res.json({data:{user}}) }) userRouter.post("/",async (req,res)=>{ const {fname, lname, email, password} = req.body try{ const user = await User.create({fname,lname,email,password}) return res.json({data:{user}}) }catch(err){ if(err.name === 'SequelizeValidationError'){ return res.json({message:err.errors[0].message}) } console.log(err) return res.json(err) } }) userRouter.put("/",async (req,res)=>{ const {id, fname, lname, email, password} = req.body try{ const isUpdated = await User.update({fname,lname,email,password},{ where:{ id } }) if(isUpdated[0]) return res.json({data:{message:true}}) }catch(err){ return res.json({err}) } return res.json({data:{message:false}}) }) userRouter.delete("/",async (req,res)=>{ const {id} = req.body try{ const isDeleted = await User.destroy({ where: { id } }) if(isDeleted) return res.json({data:{message:true}}) }catch(err){ return res.json({err}) } return res.json({data:{message:false}}) }) ``` The server.js file will look something like this: _server.js_ ```js import Express from 'express' import cors from 'cors' import bodyParser from 'body-parser' import { authMiddleware } from './middleware.js' import jwt from 'jsonwebtoken' import { userRouter } from './router/user.js' const app = Express() app.use(cors()) app.use(bodyParser.json()) app.get("/",(_,res)=>{ return res.json({hello:"HI"}) }) app.get("/hello",(_,res)=>{ return res.json({hello:"world"}) }) app.post("/login",(req,res)=>{ const email = req.body.email const password = req.body.password if(!email || !password) return res.status(419).json({message:"Improper Data provided"}) if(email !== "admin@gmail.com" || password !== "password") return res.status(401).json({message:"Invalid credentials"}) const payload = {user:{id: 1, name: 'user1'}} let token = '' try{ token = jwt.sign(payload,'secret-string',{expiresIn:60 * 60}) //get it from .env file in prod }catch(err){ return res.status(500).json({message:err.message}) } return res.json({token}) }) app.get("/protected",authMiddleware,(req,res)=>{ const user = req.auth.user return res.json({message:"Hello from protected route",user}) }) app.use('/users',userRouter) const port = 3000 app.listen(port,()=>{ console.log(`Server running on port http://localhost:${port}`) }) ``` Hit command npm start on the terminal and go to [http://localhost:3000/](http://localhost:3000/)users in postman and switch between the methods and test. That’s it. I hope you like the blog and if you do, hit the clap icon and do follow me for more such blogs. Drink water. Keep smiling… ### Authentication in express with JWT in 2 min 2022-09-18 · https://dikshantraj.dev/blog/authentication-in-express-with-jwt-in-2-min Authentication is one of the most important things for an application and JWT has become one of the best standards to make it possible. Authenticating is the process of determining who the user is. Every website or application has some sort of user involved and getting the logged-in user is one of the common things you would be doing while developing APIs or servers. In express, implementing JWT token authentication is just like a piece of cake. So without wasting any time let’s get started. In my previous articles, I discussed about setting up a [server](https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min) and adding [middleware](https://dikshantraj.dev/blog/express-middlewares-in-2-min) in Express. We will be using the reference from there for setting up middleware and server. We will be using jsonwebtoken npm package. So let’s install the package by running: ```bash npm i jsonwebtoken ``` We will generate a token if user logs in with correct credentials. generating is also known as signing a token. Signing a token is done by just using sign() method of jsonwebtoken package ![](https://dikshantraj.dev/blog/authentication-in-express-with-jwt-in-2-min/1.png) This will generate a token and send it as a response. To verify this token, we will be using the .verify() method in our middleware ![](https://dikshantraj.dev/blog/authentication-in-express-with-jwt-in-2-min/2.png) This middleware will verify the token and pass on the user to the request via the auth property. In every protected route, the user will be extracted from req.auth.user property. An example of protected route with user will look something like this: ![](https://dikshantraj.dev/blog/authentication-in-express-with-jwt-in-2-min/3.png) Use the user property everywhere required in your application. That’s it, you have protected your application routes with the JWT token authentication mechanism. I hope you like the blog and if you do, don't forget to hit the clap icon and follow me for more such blogs. Drink water. Keep smiling… ### Express middlewares in 2 min 2022-09-17 · https://dikshantraj.dev/blog/express-middlewares-in-2-min In the previous [blog](https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min), I explained about getting started with express.js in 2 min. In this blog, I will be explaining about express middlewares. Middleware is something that handles one of the most important business logic of any application whether it is related to authorization or authentication or logging or any other use case like adding something to the request. In lamen terms, middlewares are the thing that basically sits like a middleman between the request and the response. ![](https://dikshantraj.dev/blog/express-middlewares-in-2-min/1.jpeg) _middleware_ Express and middlewares go hand in hand. Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls. (acc to express docs). Creating a middleware in Express and using it in your routes is not a difficult task. So without wasting a second, let’s get started. We will be creating a middleware that will provide authentication to our APIs from a token and if invalid or no token is provided, it won’t let the request go further and will throw an unauthorized error upfront. Create a login route that will accept email and password and if that is correct we will generate a token and for now we will be using static values and not from any db. - /login ![](https://dikshantraj.dev/blog/express-middlewares-in-2-min/2.png) User will get a token after login that he will have to use in the protected routes. For this we will create an authMiddleware something like this ![](https://dikshantraj.dev/blog/express-middlewares-in-2-min/3.png) We will check for authorization header and if we get correct value, we will let the user request go further. generally in this middleware, if you have used jwt then jwt verification will happen or something similar to checking user request and deciding to let the request go further or not. Now the protected route will look something like this: - /protected ![](https://dikshantraj.dev/blog/express-middlewares-in-2-min/4.png) If you hit the endpoint ‘/protected’, you have to provide a Bearer token in authorization header and if token is not valid, you will get a 401 and if it is valid you will see the following response. This way middleware can be very useful for - authenticating user - attaching attributes to request like user id or email etc. - logging requests - error handling - and many more… That’s all about middlewares. I hope you like the blog and if you do then don’t forget to hit the clap icon and do follow me for more such blogs. Drink water. Keep smiling… ### Getting started with express.js in 2 min 2022-09-15 · https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min Express.js is a nodejs framework basically used to create a backend server for hosting APIs and can also be used for hosting files or serving them. In this blog, I will be telling you how to get started with express in a minimum amount of time and run your server and start hosting APIs. Without wasting any time, Let’s get started. **Installation** First of all, create a package.json file by running ```bash npm init -y ``` This will create a package.json file. Add an extra attribute of `“type”:”module”` Your package.json file will look something like this ![](https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min/1.png) Now let’s install expressjs ```bash npm install express ``` Let’s create and run our server using express installed. Before this, let’s install some more dependencies that will help us: ```bash npm install nodemon --save-dev //for running server in development npm install cors //for handling cors npm install body-parser //for taking input ``` Create a server.js file and write the following code in it: ![](https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min/2.png) Setup nodemon to start server.js file in development mode by adding scripts in package.json file like this: ```js "scripts": { "start":"node server.js", "dev":"nodemon server.js" } ``` package.json will look something like this: ![](https://dikshantraj.dev/blog/getting-started-with-express-js-in-2-min/3.png) Run `npm run dev` This will run the server again everytime you change anything in the code. Go to [http://localhost:3000/](http://localhost:3000/)hello, you will see the output as {“hello”:”world”}. Make as many routes you want now. That’s it. Enjoy making APIs and ship products in minimum time. I hope you like the blog and if you do, don’t forget to hit the clap icon and follow me for more such blogs. ### Setting up GraphQl with nodejs, sequelize, and postgres 2022-09-11 · https://dikshantraj.dev/blog/setting-up-graphql-with-nodejs-sequelize-and-postgres GraphQl is a powerful query language for writing APIs, where front end can ask for the data they need rather than backend telling them the queries, frontend decide itself what they need and just call for it. Maintaining documentation and all in REST is quite difficult as compared to GraphQl and also the point of flexibility plays a major role why one should choose GraphQl over REST. The front end can ask for more data as and when required while hitting GraphQl but the same is not the case for REST, whether the backend has to create completely new APIs or they have to edit the same API and there is always an overhead attached to both. Using sequelize is not necessary, you can use any ORM or can completely neglect using ORM and just write your own queries. We will be using Postgres as a DB but again we can also use MySql, it’s completely up to you. So let’s get started. The list of libraries we will be using throughout the tutorial are: ```sql express apollo-server-express cors sequelize sequelize-cli dotenv pg ``` Let’s get started by creating a GraphQl server using express. Create a server.js in the root directory of your project and write this set of code in it. ![](https://dikshantraj.dev/blog/setting-up-graphql-with-nodejs-sequelize-and-postgres/1.png) What’s in the file? - Created an express app. - Setup cors - Created new apolloserver passing on the typeDefs, resolvers, and context (will be explained in the rest part of the blog). - Started the apolloserver. - started the express application. **typeDefs:** These are the schemas of GraphQl. **resolvers:** These are the logic to fetch those schemas data. **context:** This is the common thing that we want to share with every resolver. Crete directory named graphQl and create three more directories inside it naming schemas, resolvers, and context. Inside the schemas directory create an index.js and write these set of code inside it: ![](https://dikshantraj.dev/blog/setting-up-graphql-with-nodejs-sequelize-and-postgres/2.png) Define the User and UserProfile schema we want to have fields in DB and expose to the front end. Inside the resolvers directory create an index.js and write these set of code inside it: ![](https://dikshantraj.dev/blog/setting-up-graphql-with-nodejs-sequelize-and-postgres/3.png) Ignore the User model file, we will be discussing it later. In the above file, we have written the resolvers for all the schema that we mentioned earlier while defining the schema. Inside the context directory create an index.js file and write these set of code inside it: ![](https://dikshantraj.dev/blog/setting-up-graphql-with-nodejs-sequelize-and-postgres/4.png) Fetch the user via any token or any header that you can receive from the req parameter passed to context and return the user. This user will be available to every resolver method as a third parameter. After all these, we have to create models, migrations, and seeders. For these, we will be using sequelize-cli. After installing sequelize-cli, configure the DB username, DB name, passwords, host, and all other required settings. Run these commands: ```bash npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string ``` User models and migrations will be created. ```bash npx sequelize-cli model:generate --name User --attributes bio:string,phone:number ``` UserProfile model and migrations will be created. Write your desired code in the migrations and models. ```bash npx sequelize-cli db:migrate ``` This will create tables with the field mentioned in the migrations file. Run the server file with node server.js and go to [http://localhost:3000/graphql](http://localhost:4000/graphql) Run this query and check the result. ![](https://dikshantraj.dev/blog/setting-up-graphql-with-nodejs-sequelize-and-postgres/5.png) If you like the blog, hit that clap icon and if you have any doubt or wants the complete code with tests written, post a comment below. ### React hooks in 1 min 2022-07-21 · https://dikshantraj.dev/blog/react-hooks-in-1-min ![](https://dikshantraj.dev/blog/react-hooks-in-1-min/1.png) I will be explaining majorly used react hooks in brief in this blog post. So without any delay, let’s get started: **UseState:** ```js const [name, setName] = useState(""); ``` Returns a stateful value and a function to update that value. Contains initial value as a parameter to it. ```js Updating state -> setName(“Dk”) ``` **UseEffect:** ```js useEffect( () => { const data = fetch(...); return () => { cancelRequest(); }; }, [dependency], ); ``` Provide lifecycle methods in react and used for controlling side effects like fetching data, subscribing, listening to state changes, updating DOM etc. Takes a function as parameter and runs on every render. Dependency array is used to tell when should it re run. Leave it empty if you want to run something once. returns a function that runs on unmounting of component generally used to cancel side effects. **useContext:** ```js const value = useContext(context); ``` Used to escape from prop drilling. Accepts a context object created from React.createContext returns value of the context passed from the parent. **useReducer:** ```js const [state, dispatch] = useReducer(reducer, initialArg); ``` used to manage state more effectively in larger projects or where code becomes large. Accepts a reducer of type `(state, action) => newState`, and returns the current state paired with a `dispatch` method. **useRef:** ```js const ref = useRef(null) ``` Basically used to hold a reference of DOM element. parameter -> initial value for reference. initially ref.current is null and is set like this. ```html ``` **useMemo:** ```js const memoizedValue = useMemo(function); ``` returns a memoized value. parameter -> function that can also have dependency like useEffect. memoized i.e cached the value passed to it … can be any complex function or a complete function. fetched the value from cache until variable specified in dependency array changes. **useLayoutEffect:** ```js useLayoutEffect(() => { console.log(count) }, [count]) ``` have same signature of useEffect. runs synchronously after all DOM mutations. used for DOM changes. ### Setup Private Blockchain using Geth 2022-06-30 · https://dikshantraj.dev/blog/setup-private-blockchain-using-geth ![](https://dikshantraj.dev/blog/setup-private-blockchain-using-geth/1.png) Blockchain is the future and no one can deny this fact. But in blockchain world, everything is public and there is no private world here but for some applications it become very difficult to hide sensitive data or data that they don’t want to be public at the same time they want to use the advantages of blockchain i.e. distributed and secure. In this case they can setup their private blockchain with some trusted nodes in few steps. Setting up a private blockchain also won’t cost much. You just need 2–3 normal CPUs. Let’s start building our own blockchain. **Geth** (Go Ethereum) is an open source library(go client) for ethereum. We will use it. Without any further delay let’s get started. We will be creating total 6 nodes on 2 server(3 nodes each). **Step 1** : Download geth from here: [Downloads | Go Ethereum](https://geth.ethereum.org/downloads/) **Step 2 **: Create directories in both server ```bash mkdir node1 mkdir node2 mkdir node3 ``` **Step 3** : Create accounts in each directory and note down the addresses. We will use them later. ```bash geth --datadir node1 account new geth --datadir node2 account new geth --datadir node3 account new ``` **Step 4 :** Create a password.txt file and save your account password so that we can use it easily. ```js vim password.txt ``` **Step 5 :** Create a genesis file to create first block in your blockchain known as genesis block. We will use puppeth for it, you can also create it manually like this: [Create a genesis file - Hyperledger Besu](https://besu.hyperledger.org/en/stable/HowTo/Configure/Genesis-File/) ```js puppeth ``` ![](https://dikshantraj.dev/blog/setup-private-blockchain-using-geth/2.png) ![](https://dikshantraj.dev/blog/setup-private-blockchain-using-geth/3.png) Follow these steps and a genesis file will be created. Provide all the account addresses for sealing and pre-funded that you created earlier. Copy this file in every server you want to create nodes and remember if anything is different, your blockchain peers will not sync with each other. **Step 6 :** Create genesis block in data directory you created earlier ```bash geth --datadir node1 init name.json geth --datadir node2 init name.json geth --datadir node3 init name.json ``` A new genesis block will be created. **Step 7 :** Start the nodes one by one and note their enode values to connect to different peers. ```bash geth --datadir node1 --networkid "networkid" --nodiscover console --nat=extip: --port 30301 geth --datadir node1 --networkid "networkid" --nodiscover console --nat=extip: --port 30303 geth --datadir node1 --networkid "networkid" --nodiscover console --nat=extip: --port 30305 ``` Type your networkid after — networkid flag , — nat flag is used to specify the ip address to connect to peers on different server. If not specified it will use 127.0.0.1 or localhost and you can add peers inside the server itself. **Step 8** : Now run every node one by one using some extra flags to create RPC and WebSocket servers also if you want. ```bash geth --datadir "node1" --nodiscover --port "30301" --ws --ws.origins "*" --ws.addr "ip-of-server" --ws.port "8550" --nat=extip:ip-of-server --http --http.addr "ip-of-server" --http.port "8545" --http.corsdomain "*" --http.api "personal,eth,net,web3,txpool,miner" --networkid "network-id" --miner.gasprice "0" --allow-insecure-unlock --unlock "address-inside-node1" --password password.txt --mine --bootnodes "enode-of-some-other-node" ``` This will create a RPC server i.e. RPC url will be -> ip:port specified with **http **flag and to receive events websocket server will be -> ip:port specified with** ws** flag. We will be starting our other nodes without exposing http and ws server. ```bash geth --datadir "node2" --nodiscover --port "30303" --nat=extip:ip-of-server --http.api "personal,eth,net,web3,txpool,miner" --networkid "network-id" --miner.gasprice "0" --allow-insecure-unlock --unlock "address-inside-node2" --password password.txt --mine --bootnodes "enode-of-some-other-node" geth --datadir "node3" --nodiscover --port "30305" --nat=extip:ip-of-server --http.api "personal,eth,net,web3,txpool,miner" --networkid "network-id" --miner.gasprice "0" --allow-insecure-unlock --unlock "address-inside-node2" --password password.txt --mine --bootnodes "enode-of-some-other-node" ``` **Step 9 :** After starting every node, connect peers with each other by accessing the console using this: ```js Travel to the node folder and run this: geth attach geth.ipc A js server will be started where you can see the blocknumber and everything else. We will use admin.addPeer() to connect to other peers and admin.peers to see all peers connected. admin.addPeer("enode-of-other-nodes") ``` **Step 10 :** Your blockchain will be up and running and you can see logs of block mining and blocks reaching to canonical chain. You can add the network to metamask and start doing transactions. I hope you liked the blog, don’t forget to hit that clap icon and if you get struck anywhere, leave a comment here I will try to help you……… ### Blockchain developer interview experience 2022-05-30 · https://dikshantraj.dev/blog/blockchain-developer-interview-experience ![](https://dikshantraj.dev/blog/blockchain-developer-interview-experience/1.jpeg) Let me give you a brief about me : I am a final year B.tech CSE student having experience of more than a year in the field of web development. In web3 specific, I have experience of just 3–4 months and have written few smart contracts and just know basics of blockchain. The role for which I was interviewing was Associate developer — Blockchain So without any delay, let me tell you the questions asked from me: **My past experience and the things I have developed? What is consensus algorithms?** [Consensus Mechanism (Cryptocurrency)](https://www.investopedia.com/terms/c/consensus-mechanism-cryptocurrency.asp) **Types of consensus algorithms?** [Proof of Work (PoW)](https://www.investopedia.com/terms/p/proof-work.asp) [Proof-of-Stake (PoS)](https://www.investopedia.com/terms/p/proof-stake-pos.asp) **What you know about NFTs and their marketplaces?** [Non-fungible tokens (NFT) | ethereum.org](https://ethereum.org/en/nft/) **Marketplaces : **An NFT marketplace is **a digital platform for buying and selling NFTs**. These platforms allow people to store and display their NFTs plus sell them to others for cryptocurrency or money. **How to create NFT?** [How to Write & Deploy an NFT (Part 1/3 of NFT Tutorial Series) | ethereum.org](https://ethereum.org/en/developers/tutorials/how-to-write-and-deploy-an-nft/) **What is IPFS?** [IPFS Powers the Distributed Web](https://ipfs.io/) **Video streaming in Blockchain?** [Theta Token](https://www.thetatoken.org/) **Do you know about Theta Blockchain?** [Theta Token](https://www.thetatoken.org/) Some more questions were asked from me but I didn’t remember the exact one. I have answered most of the questions but I don’t know what will be the reply from their side. I hope these will help you and if you want to read more such interview experiences, follow me and hit the clap icon below. ### Introduction to solidity 2022-05-03 · https://dikshantraj.dev/blog/introduction-to-solidity ![](https://dikshantraj.dev/blog/introduction-to-solidity/1.png) Solidity is nothing new, just the use case of it is something that came to existence a few years ago. Solidity is just a high level object oriented language that someone who is familiar with other object oriented language like C++, Java etc. will find very similar. **It would be a series of blogs and at the end, we will be deploying our ERC20, ERC721 and ERC1155 token on testnet**. The **learning** curve of solidity depends on two factors: - **Prior knowledge** of object oriented language like C++, Java, PHP etc. -> For those having prior knowledge, the curve is almost linear, there’s nothing new other than the syntax that is also very easy to learn and everything related to syntax can be found online. - **No Prior knowledge ->** Those having no knowledge of other OOPS language, I would suggest them to first learn any of the above mentioned language and then jump to solidity to experience a linear curve otherwise if you would directly jump on learning solidity, the curve would be very steep. **Use Cases** It is important to know the use cases of the thing you are planning to learn and if that doesn’t excite you, then you are not gonna enjoy your learning journey. - It’s one and only most popular use case is to write **smart contracts **and smart contracts in simple language are the code that runs on** blockchain**. If you don’t know about smart contract, please get a basic idea of it because in later tutorial we will be writing smart contracts throughout. **Setup** There’s nothing much to setup, you just need a browser and boom you can write your first smart contract now. We will be using remix for writing smart contracts. [Remix - Ethereum IDE](https://remix.ethereum.org/) **Data Types** - uint - int - string - bool - array - struct - address - bytes - contract - enums These are some majorly used data structure used in solidity **uint and int** are similar just the difference is that in int, you can have negative values but in uint, you can’t. **NOTE:** uint and int can be also written as uint256 and int256. We can also use uint8 uint16 uint24 ….. to save some gas. **Address** is a new type and it holds a 20 bytes value as ethereum address. **Contract** is just like a class. Let’s write our first contract on remix. **Hello World** ![](https://dikshantraj.dev/blog/introduction-to-solidity/2.png) **Line 1**: We have to mention the license, don’t focus on it just write the line as it is. **Line 3:** Mention the solidity version. **Line 5: C**ontract name just like class declaration in other languages **Line 6:** Declaring a string variable named hello and assigning value to it. The modifier of it is kept as public so that the compiler attaches a getter with it and we don’t have to manually create it. After writing this code, just press Ctr + s or go to the third icon from left bar and **compile **the code, if there is no error go to the fourth option and **deploy** your code. You will see something like this: ![](https://dikshantraj.dev/blog/introduction-to-solidity/3.png) You will see the value as specified in the smart contract. **Boom, you have successfully written your first smart contract and deployed it on blockchain**. That’s it for this blog, If you have any doubt please put it in the comment section and if you liked it, don’t forget to give a thumbs up to it. In next blog, we will be writing some basic level smart contracts. **Stay safe and keep learning.** ### Progressive Web App(PWA) 2022-01-12 · https://dikshantraj.dev/blog/progressive-web-app-pwa ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/1.png) A PWA or a progressive web application is simply a website that can be installed on any device i.e android, iphone, desktop etc. It is just a responsive website that can be easily installed on a single click with some great powers. **Advantages of a PWA:** - Small size (mostly in kbs) - Easy to install - Offline support - Not dependable on OS - Features of native application(mostly) - Push Notifications - No overhead of updation(updates itself in background) We can simply call PWA, a hybrid application/website that can be installed on any device or can even be submitted to play store(TWA). **Manifest.json:** It is a file that the browser parses and provide the application/pwa with certain name and also give some icon to your application after it is installed and also it have some advanced features like whether the app should be running standalone or with that url bar on top, different size icons for different screens, shortcut actions etc. Just link the manifest file to the html file in the head tag like this: ```html ``` Your manifest file looks something like this: ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/2.png) You can add more to your manifest file, just have a look here: [Add a web app manifest](https://web.dev/add-manifest/) For icon generation, I have used this tool: [PWA Application Icon Generator Free Online Tool](https://tools.crawlink.com/tools/pwa-icon-generator/) **Service Workers:** The heart of a PWA is it’s service worker that enables it to provide app like functionality and keep track of everything from the manifest file to the background services, updation, catching, fetching and everything. A service worker is just a js file that can be easily created and you just need to create some functions/methods to make it work. I’ll be explaining them in the later part. ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/3.png) **Lifecycles of a Service Worker:** - Registering - Installing - Activating - Updating If we update anything in the sw.js file, then the service worker will be installed again and it will become active only when all it’s instances are closed in order to not create any interruption in the user’s work. **Registering a SW:** Registering a sw is as simple as just writing 4 lines of code in your main js file. The code looks something like this: ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/4.png) _service worker registration_ **Installing a SW:** Installing a service worker is also as simple as registering it. Write this code in the sw.js file and the code looks something like this: ```js self.addEventListener('install',(evt)=>{ console.log("sw installed",evt) }) ``` **Activating a SW:** Activating a swrvice worker to listen to events and everything is also quite simple like just adding one more event listener like this: ```js self.addEventListener('activate',(evt)=>{ console.log("sw activated",evt) }) ``` **OFFLINE SUPPORT** PWA provides you the power of making your app work offline or show some other content while offline. All of these is possible due to caching. Caching is basically storing the assets on the browser storage and whenever the connection goes off or app becomes offline, fetching the files from the cache. This can be understood by looking at a simple diagram: ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/5.png) **CACHING:** Caching is a strategy to store the assets i.e. HTML, CSS, js, images and other files on the user’s browser storage. We can cache our assets anywhere in he sw file but if we think logically, we should use the install event to cache our assets because that is something we don’t need to do every time. We can just cache resources once and we are good to go. The caching code looks something like this: ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/6.png) **Fetching Files from cache:** We have successfully cached the resources, so our next step would be to get those resources from the cache directly rather than using user’s net again and again. So to do that, we just need to add one more event listener i.e. fetch event and check if the requested resource is in the cache or not and if it is in the cache fetch it from the cache directly before performing network call. The fetching looks something like this: ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/7.png) Now, it causes an issue like when developing the app, there will be cases where you will be updating the files that you have saved in your cache, but you won’t be seeing any effect because the resources are fetched from the cache so we need to create a mechanism that deletes the previous cache and caches the assets again so this can be achieved by checking the cache version every time we refresh i.e. we can use the activate event of sw. **Deleting older versions of cache:** The code of checking the cache and deleting previous versions looks something like this: ![](https://dikshantraj.dev/blog/progressive-web-app-pwa/8.png) **Displaying the offline page from cache if network is not there:** Showing a fallback html page or any image is very simple. Just check in the fetch event whether it’s possible to fetch from network, if both is not possible then show the fallback page stored in the cache of browser. The code will look something like this: ```js self.addEventListener('fetch',(evt)=>{ evt.respondWith( caches.match(evt.request) .then((cacheResponse)=>{ return cacheResponse || fetch(evt.request) }) .catch(()=>{ return caches.open(cache_version).then((cache)=>{ return cache.match('/fallback.html') }) }) ) }) ``` Dynamic Caching and Notifications and other features are not in the scope of this blog, I will be including all of these in my next blog. The tutorial PWA can be installed from the link here: [Dikshant rajput's PWA](https://vainsunnyport.dikshantrajput.repl.co/) All the code related to this tutorial will be found here: [GitHub - dikshantrajput/pwa-medium-tutorial](https://github.com/dikshantrajput/pwa-medium-tutorial) If you guys like this blog, don’t forget to hit that clap icon and follow me for more such content over web technologies. Stay safe and happy :) ### Views in Laravel 2021-10-30 · https://dikshantraj.dev/blog/views-in-laravel ![](https://dikshantraj.dev/blog/views-in-laravel/1.png) Views as the name suggests “It is the part of your website that is visible to the user”. Laravel provides a very efficient way for handling the HTML part of our website. Views are one of the powerful and underrated part of Laravel. Views can help you to maintain the structure and readability of code by separating each and every part of your HTML. Views in Laravel have their separate place in the resources/views directory. All the views of your project is present in this directory. A simple view file looks something like this: ![](https://dikshantraj.dev/blog/views-in-laravel/2.png) _View file_ Laravel uses a templating engine for converting the view files into plane php file. The view files are stored with .blade extension before the php extension like this : ```php home.blade.php ``` **Rendering View** For showing the view file or returning the view file from controller, use the view() global helper function like this: ```php public function index(){ return view('home'); } ``` **Passing Data To View** There are multiple ways of passing data to the view file. Some of them are: - Using compact method ```php public function index(){ $data = [ 'name' => 'Dikshant', 'email' => 'dikshantraj2001@gmail.com', 'gender' => 'M' ]; 'status' => 'active'; return view('home',compact('data','status')); } ``` - Passing data in an array as second parameter to view() ```php public function index(){ $data = [ 'name' => 'Dikshant', 'email' => 'dikshantraj2001@gmail.com', 'gender' => 'M' ]; 'status' => 'active'; return view('home',['data' => $data,'status' => $status]); } ``` - with() method ```php public function index(){ $data = [ 'name' => 'Dikshant', 'email' => 'dikshantraj2001@gmail.com', 'gender' => 'M' ]; 'status' => 'active'; return view('home')->with('data',$data)->with('status',$status); } ``` **Useful Blade Directives** There are many blade directives that make our life quite easier. Some of them are: - **Echo data** To echo data in blade directly use this {{ }} ![](https://dikshantraj.dev/blog/views-in-laravel/3.png) _Echoing data_ - **Conditional statements** ![](https://dikshantraj.dev/blog/views-in-laravel/4.png) _Conditional statements_ - **Loops** There are multiple types of loops available in blade templating engine: ![](https://dikshantraj.dev/blog/views-in-laravel/5.png) _Types of loops_ - **Including and Extending** @include is used for including some other view in the file. You can even pass data directly as second parameter to this method. @extends is used to extend a layout or any other file. @yield is used for taking some data and place in other file. Generally used while extending. @section is used to provide value to the variable mentioned with @yield. @stack for stacking data one over the other . Generally used to dynamically add styles and scripts ![](https://dikshantraj.dev/blog/views-in-laravel/6.png) _layouts/app.blade.php file_ ![](https://dikshantraj.dev/blog/views-in-laravel/7.png) _home.blade.php_ - **Auth and Guest directives** Used to check if the user is logged or not ![](https://dikshantraj.dev/blog/views-in-laravel/8.png) _@auth template_ - **PHP** Sometimes there are situations where you want to use raw PHP in your code, you can easily do so by usng the @php directive ![](https://dikshantraj.dev/blog/views-in-laravel/9.png) _@php directive_ These are all the basic things one should know for easy and hurdle free development. There are more advanced features also but all these can help you start your journey. Each and every thing is mentioned in the Laravel official documentation here: [Views](https://laravel.com/docs/8.x/views#introduction) [Blade Templates](https://laravel.com/docs/8.x/blade) If you like this blog, please hit that clap icon and if you want to read more such blogs on Laravel basics, do follow me and check my previous blogs here: [Dikshant Rajput - Medium](https://dikshantraj2001.medium.com/) ### Image Upload in Laravel 2021-10-26 · https://dikshantraj.dev/blog/image-upload-in-laravel ![](https://dikshantraj.dev/blog/image-upload-in-laravel/1.png) Images are the vital part of a website that provides the look and feel for the whole website and as a back end framework, Laravel takes care of uploading image. If you wish to use core PHP, the length of the code is too much, but in laravel it’s just 4 to 5 lines that too for naming the file. So let’s begin… **HTML Part** For uploading images or other file, you need to create the input form for it. The code for it looks something like this: ```html
@csrf
``` **Route** In your web.php make route for uploading file like this: ```php Route::post('user/avatar/upload',[App\Http\Controllers\UserController::class,'storeAvatar']) ->name('user.avatar.upload'); ``` **Controller Logic** First of all, you need to check whether file exists on the request or not. This can be done using request()->hasFile() method like this: ```php if($request->hasFile('avatar')) ``` **Naming File Original Name:** For getting name of the file uploaded, you can use the getClientOriginalName() method on the file object: ```php $file = $request->file('avatar'); $fileOriginalName = $file->getClientOriginalName(); ``` **Original Extension:** For getting extension of the file uploaded, you can use the getClientOriginalExtension() method on the file object: ```php $fileOriginalExtension = $file->getClientOriginalExtension(); ``` **Create a unique name:** For creating name, you need to separate the original file name and it’s extension. This can be done using php pathinfo() method: ```php $fileNameWithoutExtension = pathinfo($fileOriginalName,PATHINFO_FILENAME); ``` You can create name in your way but just remember that don’t leave any special character or anything that can harm your system. For that use the Str::slug() method. I will be creating name using time() method: ```php $uniqueFileName = time() . '-' . Str::slug($fileNameWithoutExtension) . '.' . $fileOriginalExtension; ``` **Specifying Location** ```php $location = 'folder-name'; ``` **Specifying disk** There are multiple types of storage available in Laravel for you to store the files. Some of them are: - Public - Local - S3 If you want to add any other or use any other platform service mention the credentials in the “config/filesystems.php” file The most common method used for storing image is the public method which can be easily accessed. So we will be using public disk: ```php $disk = Storage::disk(‘public’); ``` **Putting/ Storing file** There are multiple easy of putting file but the easiest way is to use the storeAs() method available with the file object itself. The method looks something like this: ```php $file->storeAs($location,$uniqueFileName,'public'); ``` This will upload the file to the “storage/public/{$location}” with the fileName specified by you in the code. Another way is by using the disk::put() method like this: ```php $disk->put($path,file_get_contents($file)); ``` That’s it. Your file will be uploaded to the directory you specified. Whole code looks something like this: ![](https://dikshantraj.dev/blog/image-upload-in-laravel/2.png) **Accessing file in view** First of all create a link of your storage folder in the public folder by running this command: ```bash php artisan storage:link ``` To access file just append the ‘storage’ directory before the url like this: ```php asset('storage/' . auth()->user()->avatar) ``` The tag will be something like this: ![](https://dikshantraj.dev/blog/image-upload-in-laravel/3.png) You can find the code here: [GitHub - dikshantrajput/auth-medium at file_upload](https://github.com/dikshantrajput/auth-medium/tree/file_upload) If you have any doubt or are facing any issue, shoot a comment below. I will try to resolve as soon as possible and if you like the blog, hit that clap icon and do follow me for more such blogs. ### Alpine.js basic tutorial 2021-10-08 · https://dikshantraj.dev/blog/alpine-js-basic-tutorial ![](https://dikshantraj.dev/blog/alpine-js-basic-tutorial/1.png) > Alipne.js is a newly born, lightweight, simple and powerful javascript framework that makes most of the stuff of javascript inline. It is like jQuery but it’s lighter and simpler version. No need for long codes to do a simple task like hiding or showing something or creating advance functions like debouncing and throttling and handle dom events gracefully. There are basically 15 attributes, 6 properties and 2 methods as of now and it’s still evolving. If you want to know about all these attributes, properties and methods, do have a look at alpine.js documentation here: [Alpine.js](https://alpinejs.dev/) It’s very simple to do small tasks and takes minimal to no code . **Including alpine.js in your project using a cdn** No need of installing anything in your project directory, just include alpine.js cdn in your head tag and start working like this: ```html OR ``` **Attributes** - **x-data** The main attribute that you need to know to start working is “x-data” attribute. it is specified on the html element in which you need to keep track of some variables. This attribute creates an object in the local space of that html element in which it is specified and the properties specified in it is available in all the children of that html element. ```html

``` An object is created having the following properties: { open : false , content : ‘India’ } Now, we can use these properties anywhere in the html element i.e inside the div in which x-data is specified. ![](https://dikshantraj.dev/blog/alpine-js-basic-tutorial/2.png) - **x-show** It is also one of the most important of attribute that makes our work so easier. As it’s name suggests, it is used to hide or show a particular html element. It is used like this : ```html
``` The div will be shown only when open is set to be true. - **x-text** It is used to show the content of html using object property value like this: ```html

is same as

India

``` - **x-model** This attribute is used to bind the value of any input value to a object property and use it. ```html

``` - **x-ref** This attribute acts as an alternative to getElementById or any selector attribute that one used to access dom elements. You can use it like this: ```html
Hi, I am dikshant
``` $refs is a magical property that is used to access the refs made by you and you can do anything on it that you previously used to do after using selector to select the html element. - **x-on** This is the most important and most handy attribute available in alpine.js and it is used for applying event listeners on an html element. It works like this : ```html

Alpine Tutorial

``` You can even use shorthand for x-on:click i.e @click You can find more such examples in their official documentation that i have linked above. You will find some more examples along with working code here. Feel free to suggest changes or updating the repo here: [GitHub - dikshantrajput/alpine-demo](https://github.com/dikshantrajput/alpine-demo) I hop you will make your next project using this wonderful lightweight library. If you like the blog, don’t forget to hit that clap icon and if you want to read more such blogs, do follow me up. ### General Simple level interview programs 2021-10-06 · https://dikshantraj.dev/blog/general-simple-level-interview-programs In basic freshers level interview, generally the interviewer prefers to ask some simple school level programs for beginning the interview and making the candidate confident. So it is very important to have a look at some of the basic programs before hand and you should be able to write program based on these questions in given time slot. I will be telling some of these questions in this blog and I will keep updating the questions and adding more and more basic level interview questions. So lets begin… #### **1. Fibonacci series** It is the most loved question of interviewers and first of all you should be knowing what a fibonacci series is: It is basically series where numbers follow a pattern i.e number would be the sum of previous two numbers and 0 and 1 are the beginning of the series. So the series look something like this: ```js 0 1 1 2 3 5 8 13 21 ... ``` There are two approaches to solve this problem: - **Iterative** The basic idea of this approach is to keep track of two variables and generate the third variable by adding previous two variables and after one adding assigning first variable with second value and second variable with sum like this: ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/1.png) - **Recursive** The approach here is to recursively calling same function and adding previous two values like this: ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/2.png) #### **2. Factorial** Factorial of a number is the product of number with previous numbers upto 1. ```js e.g 5! = 5 * 4 * 3 * 2 * 1 = 120 ``` Again there are two approaches for this one too i.e - **Iterative** ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/3.png) - **Recursive** ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/4.png) #### **3. Prime Numbers** A prime number is a number that is divisible by itself and by 1. ```js e.g 2,3,5,7,11,13 ... ``` ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/5.png) #### 4. Reverse a number A number can be reversed by the approach of dividing the number by 10 and taking its reminder: ```js 123 = 3 * (10 ^ 0) + 2 * (10 ^ 1) + 1 * (10 ^ 2) ``` ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/6.png) #### **4. Palindrome** A palindrome number is a number that is same after reversing the digits. ```js e.g 121 is a palindrome number 123 is not a palindrome number ``` Approach used to solve this is very simple: - Store the given number in a temporary variable - Reverse the number - Compare with given number ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/7.png) #### **6. Armstrong Number** Armstrong number is a number that is the sum of cube of digits of that number. ```js e.g 153 is a armstrong number as 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 ``` ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/8.png) #### **7. Swapping numbers** There are 4 ways of swapping a number: - By third variable and direct value - By third variable and referencing value - Without third variable using + and - - Without third variable using * and / ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/9.png) #### **8. Sum of digits** The approach is same as reversing a number and the only difference is that you have to just add the reminders like this: ```js e.g 153 = 1 + 5 + 3 = 8 ``` ![](https://dikshantraj.dev/blog/general-simple-level-interview-programs/10.png) All the cpp programs are added to github here : [GitHub - dikshantrajput/General-interview-programs: These are some basic school level programs that…](https://github.com/dikshantrajput/General-interview-programs) I will be keep on adding more questions in this blog post, so do follow me and if you like the blog, hit that clap icon and share it with your fiends. ### Accessors and Mutators in Laravel 2021-09-30 · https://dikshantraj.dev/blog/accessors-and-mutators-in-laravel ![](https://dikshantraj.dev/blog/accessors-and-mutators-in-laravel/1.png) Accessors and Mutators are basically used to reduce the length of the code and supports the DRY (do not repeat yourself) principles. **Accessors** As the name suggests, it is used while accessing something and here something is the attributes (columns in the database) of a model. > Accessor in laravel transforms an Eloquent attribute value that is been accessed. To create an accessor, there is a method named get{AttributeName}Attribute which returns the expected thing that you want when you access the attribute. e.g. If in your database, there is a field of first_name, second_name and you want to get the full name, you can create a accessor in the model like this: ```php public function getFullNameAttribute(){ return $this->first_name . ' ' . $this->last_name; } ``` You can access the “full_name ” attribute anywhere in your project like this: ```php $user = User::find(1); $name = $user->full_name; ``` Remember, the get{AttributeName}Attribute method should always be written like this in the “studly” case. **Mutators** As the name suggests, they are used to mutate something i.e. they are used to change the attribute before saving to the database. > Mutator in laravel transforms Eloquent attribute value when it is being set. To create a mutator, there is a method available in the model named set{AttributeName}Attribute. Whenever the field is being set anywhere it will come through this function and then go to the database. e.g. If you want to save the capitalize name of user in the database, rather than applying the logic in controller you can create a mutator like this: ```php public function setNameAttribute($value){ $this->attributes['name'] = strtoupper($value); } ``` This function will be called whenever you interact with the attribute. ```php $user = User::find(1); $user->name = "abc"; ``` The name “ABC” will be saved in the database. ![](https://dikshantraj.dev/blog/accessors-and-mutators-in-laravel/2.png) _example of accessor and mutator_ If you want to read more about accessor and mutator , do have a look here: [Eloquent: Mutators & Casting](https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor) You will find all the code related to accessor and mutator here: [GitHub - dikshantrajput/auth-medium at accessor_mutator](https://github.com/dikshantrajput/auth-medium/tree/accessor_mutator) If you like the blog, please hit that clap icon and if you want to read more such blogs, do follow me up. ### HTTP status codes 2021-09-26 · https://dikshantraj.dev/blog/http-status-codes ![](https://dikshantraj.dev/blog/http-status-codes/1.png) HTTP status codes specifies whether the request that you send to the server or on the browser is successful or there is any error or any redirection taking place. For creating an api, the developer should have knowledge about these http status codes and also in general, one should be aware of the most important status codes that we encounter in our daily developer life. Basically, these codes are divided into 5 classes: - 100–199 : Informational responses - 200–299 : Successful responses - 300–399 : Redirect responses - 400–499 : Client errors - 500–599 : Server errors As a developer, one should be knowing about the second, third, fourth and fifth classes codes. ![](https://dikshantraj.dev/blog/http-status-codes/2.png) **SUCCESSFUL RESPONSES (200–299)** - **200** : This is one of the most used and useful code. This tells us whether the request have been successful or not. - **201 :** This signifies that the request have been succeeded and a new resource have been created. - **204 :** This signifies that no content have to be sent back if the request is succeeded. **REDIRECT RESPONSES (300–399)** - **301, 308 :** This specifies that the url you are looking for have been moved to somewhere else permanently or a permanent redirect. - **302, 307 :** This specifies that the url you are looking for have been moved to somewhere else _temporarily or a temporary redirect_. **CLIENT ERRORS (400–499)** - **400 :** Bad request or the server is not able to understand the syntax of the request. - **401 : Unauthorized.** The user which is trying to access certain page or resource is not logged in. - **403 : **The user which is trying to access certain page or resource does not have required permissions and is **forbidden.** - **404 :** The page or the content which a user is trying to access is not found on the server. - **405 :** The method through which a user is trying to make the http request is not allowed. e.g not allowing PUT request on a url. - **408 :** The request gets timed out. - **415 :** Unsupported media types. - **429 :** The rate of request exceeds the limit i.e too many requests at a time. **SERVER ERRORS (500–599)** - **500 :** Internal server error. The server is not able to handle the request. - **502 :** Bad Gateway. - **503 :** Service unavailable. - **507 :** Insufficient storage. These all are some of the important http status codes. There are many other codes also but those are not that important but if you want to read about every status code, do have a look here: [HTTP response status codes - HTTP | MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) If you like the blog, hit that clap icon and if you want to read more such blogs on essential things you need to know as a developer, follow me up. ### Routing in laravel 2021-09-21 · https://dikshantraj.dev/blog/routing-in-laravel ![](https://dikshantraj.dev/blog/routing-in-laravel/1.png) Routing is one of the first step you would have to take care of while building any project. Routing is basically making the connection of controller with uri or view with uri. URI stands for uniform resource identifier and it is the path which you see on the top of your browser or the url of your website. If you don’t know the basics of laravel, I have written a blog on that also, do have a look at it here: [Getting started with laravel](https://dikshantraj.dev/blog/getting-started-with-laravel) **Routing File** All the routings of your website have to be registred in one of the file in directory of “routes”. By defaults, all the routings are mapped with the “web.php” file. I will be telling you how to make separate routes files for different sections of your project later in the blog. If you want to directly show a view file without creating any controller file, you can do it like this or if you want to pass some data to the view file pass in the callback function. But it is not advisable to do this as it breaks the “mvc” pattern rules. ```php Route::view('xyz','abc.index'); Route::get('xyz',function(){ return view('abc.index'); }) ``` There are several ways of binding a controller method to the route. - (Latest) Route::get(‘xyz’, [Controller::class, “index”]); - Route::get(‘/xyz’, ‘Controller@index’); **METHODS AVAILABLE** - GET - POST - PUT - PATCH - DELETE - OPTIONS **Route Parameters** There are situations where you want to pass id or any slug to the url with which you can identify the item selected. In that case, you will have to pass the parameter so for passing that you have to register the route with parameter. Register the route like this: ```php Route::get('xyz/{id}',[Controller::class,index]); ``` For optional parameter where you are not sure whether you will pass or not use this: ```php Route::get('xyz/{id?}',[Controller::class,index]); ``` To get the value of parameter in the route callback function, you can do like this: ```php Route::get('xyz/{id}',function($id){ return view('abc.index',compact('id')); }); ``` To get the value of parameter in the controller method, you can do like this: ```php public function index($id){ return view('abc.index',compact('id')); } ``` You can pass as many parameters as you want, those parameters will be injected in the order they are : ```php Route::get('xyz/{id}/{name}',[Controller::class,index]); ``` **Redirect route** If you want to redirect from one route to another route, you can use this: ```php Route::redirect('/abc','/xyz'); ``` **Middleware on route** If you want to apply middleware on a route, you can do it like this: ```php Route::get('abc', function(){ // do something })->middleware('auth'); ``` **Route Grouping** If you want to apply middlewares on multiple routes or you want to apply some common settings to the route like naming of route or route common uri, you can do it using route groups like this: ```php Route::group(['prefix'=>'abc','middleware' => ['auth','web'], 'as' =>'abc.'], function(){ Route::get('xyz/{id}',[Controller::class,index])->name('index'); Route::get('xyz',[Controller::class,store])->name('store'); }) ``` **Handling routing of different sections** Suppose you have three different parts of your project/website i.e - Student - Teacher - Admin You can create separate routing files in route directory and can register them in the “RouteServiceProvider” file found in the App\Providers directory. I’ll be telling you how to separate “admin” routes and other file which is automatically present is the“ web.php” file. Create a file named “admin.php” in the routes directory. Now go to the “RouteServiceProvider” file and you will find a boot method and you have to register your route within $this->routes() method like this: ![](https://dikshantraj.dev/blog/routing-in-laravel/2.png) You can find all the code here: [GitHub - dikshantrajput/auth-medium at routing](https://github.com/dikshantrajput/auth-medium/tree/routing) If you like the blog, do share it and hit the clap icon and if you want to learn more about laravel basics follow me. ### Observers in Laravel 2021-09-13 · https://dikshantraj.dev/blog/observers-in-laravel ![](https://dikshantraj.dev/blog/observers-in-laravel/1.png) Observers are used in the case where you want to make a model to listen to multiple events at the same time and you just have to register observer once rather than events that needs to be registered everytime you create an event. Observers as the name suggests is used to observe the application. There are many use cases of creating observers like if you want to do any fix operation on creating of that model instance or updating, deleting or restoring of a particular model instance, you don’t need to call events separately or write code in your controller everytime. You just have to create an observer and it will do the required actions in the backend. ![](https://dikshantraj.dev/blog/observers-in-laravel/2.png) Events provided by observers by default are :- - Retrieving - Creating - Updating - Deleting - Restoring - Force Deleting - Saving **Creating an observer** ```bash php artisan make:observer UserObserver --model=User ``` This will create an UserObserver class file in the App\Observers directory with some default methods **Registering the observer** You can register the observer in EventServiceProvider file like this: ```php public function boot(){ User::observe(UserObserver::class); } ``` This will register the observer throughout the application itself. The methods are called in this order: - Saving - Creating - Created - Saved Saving method is called on every event while dealing with model and at last of every event saved method is called. **Muting the events** If you want to mute the events for a particular model instance like suppose you have to create a user from admin panel and you don’t want to perform any event then you can use this to save: ```php $user = User::withoutEvents(function(){ User::where('id',1)->delete(); }); ``` If you want to change a property of a model like a user name and don’t want to call any event like updating or saving event then use this: ```php $user->name = 'ABC'; $user->saveQuietly(); ``` All the code for the above tutorial can be found here: [GitHub - dikshantrajput/auth-medium at observers](https://github.com/dikshantrajput/auth-medium/tree/observers) If you like the blog, don’t forget to hit the clap icon and if you want to read more such blogs, do follow me up. ### Interview Experience at Unthinkable(Software Developer) 2021-08-31 · https://dikshantraj.dev/blog/interview-experience-at-unthinkable-software-developer ![](https://dikshantraj.dev/blog/interview-experience-at-unthinkable-software-developer/1.jpeg) Unthinkable is a service based company established in 2019 . It was an on-campus placement drive and the whole process was completed within a week. The process includes of 5 rounds. Each candidate clearing the round goes to the next round. There was no aptitude or verbal test, the hiring was completely based on one’s coding skills. **Round 1** The first round was a machine coding round on hackerearth platform on 24th of August. In this round, there were 3 coding questions and time given was 1 hr. The questions were quite difficult as I was giving my first coding round ever and also the difficulty level of questions were MEDIUM. The first question was to convert the sorted linked list to Binary tree and print the preorder traversal. The second question was to find out the kth character from string formed by concatenation of substrings of word in ascending order. The third question was to find the minimum number of operations required to make the matrix beautiful. I was able to pass all the test cases of first question and have attempted second question but due to limitation of time, I couldn’t submit the code. Next day the results were out and I was selected for the second round that was conducted on 26th of August. **Round 2** The second round was also again a machine coding round with time bound of 45 min. Total number of questions were two and the difficulty level of this round was EASY. The first question was to find the number of triangles existing in an array and the approach was to use the info that in a triangle, sum of two sides should be greater than third. The second question was to delete the duplicate node in a sorted singly linked list. I was able to pass one test case out of two of first question and 4 test cases out of 5 of second question. Again next day, the results were out and I was selected for interview round that was conducted on 28th of August. **Round 3** The third round was a technical interview round and this round goes for almost one and half hour. The interviewer was quite calmed and he explained everything very nicely and politely. The questions asked during this round were based mainly on concepts and understanding of OOPS, algorithms, sql queries, dbms etc. The interviewer also asked 2 coding questions and he just wanted me to write the logic(function) on a google docs sheet. The first question was to find the number closest to a given number in an array of sorted elements. I used the approach of binary search and successfully wrote the function and explained to the interviewer. The second question was to find the frequencies of characters in a string. I successfully explained the approach and wrote the code for it on sheet. Then, he further gave me 3 questions to write sql queries and I was able to write 1 query out of three. There were a lot of questions on static keyword, abstraction, polymorphism and its types, inheritance, abstract classes, interfaces, insertion sort, selection sort and some other short questions. I was able to answer them easily. At the end, the interviewer asked me an aptitude which I was unable to answer. After one hour, I got a call and was selected for the next round that was conducted on the same day. **Round 4** The fourth round was also a technical interview round but this time the interviewer was a senior developer and this round was basically based on my development skills and I show him my multiple projects which I have done during my multiple internships and he also asked some concepts about PHP, JavaScript and other languages that I have mentioned in my resume. This round proceed for almost an hour. [Dikshant Rajput Portfolio](https://dikshantrajput.github.io/portfolio/) I have mentioned all my projects above and if you want to see my resume, you can contact me over any platform. He also asks 2 coding questions that I have to again explain the approach and write code on the sheet. The first coding question was to find whether two strings are anagrams of each other or not. The second question was on water juggling problem. He also asks some theoretical questions and I was able to answer almost each one of them. After half an hour, I again got a call and was selected for the final hr round. **Round 5** This round was the hr round and there were some basic questions on introduction, why you would like to join and some more simple questions. Luckily I cleared my last round too and landed up with an offer :) The interview was of basic level and no HARD questions or problems were asked but the quantity of questions and duration of test was quite high but overall I loved the experience. If you like the blog, hit that clap icon and if you want to read more about technologies and different languages, do follow me. ### Basic Algorithms (Searching and Sorting) — DSA 2021-08-26 · https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/1.jpeg) #### **SEARCHING Linear Search:** Let x = element to be found Let arr[] = search space(array in which x is to be found) Basic Approach:- Compare all the elements of arr[] one by one with x and if found , return it’s index and if the element is not found and the search space is exhausted, we return -1; ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/2.png) _linear search_ We can improve this if we take two pointers:- one at beginning and other at end and in one traversal we compare the left and right element simultaneously. ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/3.png) **Binary Search:** In this, the basic approach is to reduce the search space to half and compare the elements. - Find middle element from the given search space. - Compare x with the middle element, if same return middle index. - If x is less than arr[mid], element would be found in left half i.e from (0 to mid-1). - If x is greater than arr[mid], element would be found in right half i.e from (mid+1 to high). - If the search space is finished, return -1 ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/4.png) _binary search_ #### **SORTING Bubble Sort:** The basic approach of this sort is to compare the adjacent elements and if element at left is greater than element at right, then swap them. As you can observe that after one pass, the maximum element will be at last. Consider: [10, 2, 5, 3] Compare 10 and 2, 10 > 2, swap => [2, 10, 5, 3] Compare 10 and 5, 10 > 5, swap => [2, 5, 10, 3] Compare 10 and 3, 10> 3, swap => [2, 5, 3, 10] Now we know 10 is at it’s sorted position so we will compare the rest elements and the array will become sorted. => [2, 3, 5, 10] ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/5.png) _bubble sort_ A boolean variable “swapping” is taken to check if everything is sorted, then no need to make more comparisons. **Insertion Sort:** The basic idea behind this is to, insert the element at it’s correct position one by one. - Choose the second element and store it in a temp variable. - Compare it with the left elements until you found a smaller element. - Shift the element to right - Place the element stored in temp variable after the smaller element found. Consider [8, 4, 5, 10] temp = 4, compare 4 with left element i.e 8, 8>4, shift 8 to right => [ ,8, 5, 10] As there are no element left in the list, place temp at the first position => [4, 8, 5, 10] Now temp = 5, 8 > 5, shift 8 => [4, , 8, 10] 4>5, place 5 at this position =>[4, 5, 8, 10] Now temp = 10, 8<10 No need to do anything. The array is sorted. ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/6.png) _Insertion sort_ Note: Don’t swap elements, we need to shift bigger elements to right so that the element chosen is at the correct position. **Selection Sort:** The basic idea behind it is to find the minimum element of the list and swap it with the first unsorted element. - Select minimum element from the initial array and place it at the beginning of the array. - The first element is sorted, so now select minimum from unsorted part and place it at the beginning or unsorted part. Consider [4, 1, 9, 6] min = 1 swap it with the first element of array => [1, 4, 9, 6] min = 4 swap it with second element of array => [1, 4, 9, 6] min = 6 swap it with third element of array => [1, 4, 6, 9] The array will be sorted. ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/7.png) _Selection sort_ **Quick Sort(Divide and Conquer algorithm):** The basic approach behind quick sort is to select an element say “pivot” and place it at the correct position and partition the array in left part of pivot and right part and apply the same process. - Select first element as “pivot”. - Take two pointers and keep one at beginning(left) and other at end(right). - Move left pointer to right until a greater element(greater than pivot) is found. - Move right pointer to left until a smaller element(smaller than pivot) is found. - Swap left and right pointer element. - Repeat until left pointer< right pointer. - Swap the right pointer element and pivot element. - The pivot will be at it’s sorted position. - Partition the array and make it two sub arrays one that have element from start to pivot-1 and other that have elements from pivot+1 to end. - Apply same process. The array will be sorted. Consider [9, 5, 1, 10, 15, 2] pivot = 9 left = 1, right = 5 see from left 5<9 move forward left =2 1<9 move forward left = 3 10 > 9 stop left = 3 see from right 2 < 9 stop right = 5 swap 3rd and 5th index element => [9, 5, 1, 2, 15, 10] see again from left 15 > 9 stop left = 4 see from right 15 > 9 move backward right = 3 2<9 stop right = 3 as left > right swap right i.e. 3rd and pivot element =>[2, 5, 1, 9, 15, 10] You will observe that 9 is at it’s sorted position make 2 sub arrays => [2, 5, 1] and [15, 10] ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/8.png) _Quick Sort_ **Merge Sort:** The basic idea behind this sort is to divide the array into smaller sub arrays(arrays which can’t be divided further), then merge those sub arrays while sorting them with each other. It is also a divide and conquer algorithm. ![](https://dikshantraj.dev/blog/basic-algorithms-searching-and-sorting-dsa/9.png) _Merge Sort_ The scanned copy of all the notes related to these algorithms are available here: [GitHub - dikshantrajput/algorithms-notes](https://github.com/dikshantrajput/algorithms-notes) If you like the blog, don’t forget to hit the clap icon and follow me for more such blogs. I will be explaining the complexities of each and every algorithms in my next blog. ### Validation in Laravel 2021-08-22 · https://dikshantraj.dev/blog/validation-in-laravel ![](https://dikshantraj.dev/blog/validation-in-laravel/1.png) Validation is one of the most important part of any backend service. Protecting your forms from unwanted responses that can be potentially used to hack your system or create any mishappening. Whenever taking data from users through forms or any other medium, one should be very careful. Each and every response should be checked before going on to the servers or databases. ![](https://dikshantraj.dev/blog/validation-in-laravel/2.png) Laravel provides very efficient, organised and an easy way for validating responses or requests. It can even be used for checking uniqueness, correct form of data and other stuff. It’s very easy in Laravel to validate http request with use of **validate** method of the Request class. Laravel includes a wide variety of convenient validation rules that you may apply to inputs. It provides a very simple way to show error messages directly to the blade file. There are various ways to validate requests in Laravel. Some of most commonly used methods are: **Validate method:** Syntax: The validate method accepts max of 2 parameters, first one is the array of rules and second one is the array of messages. ```php validate($rules,$messages); public function store(Request $request){ $request->validate( [ 'email' => ['required','email','unique:users'], 'name' => ['required','max:40'] ],[ 'name.required' => 'Please enter your name', 'name.max' => 'Name should not exceed 40 characters', ]); } ``` The rules can be written like this also: ```php 'email' => 'required|email|unique:users' ``` As you can see there are multiple rules applied on a single ‘email’ field. If you want Laravel to stop on the first rule, you can add ‘bail’ to the rules like this: ```php 'email' => 'bail|required|email|unique:users' ``` If you want to apply validation on nested object like you have an array of input variable and you want to apply validation on elements in the array, you can do like this: ```php 'book.name' => 'required' ``` **Validator facade** Laravel provides a facade if you don’t want to apply validation using validate method. There are some extra functionality provided by the facade like redirecting the user to some other page if the validation fails. You can implement validation using facade like this: **Syntax:** Validator facade have a method named ‘make’ that is used to implement validation. It accepts 3 parameters. First one is the fields on which the validation is to be applied, Second one is the rules and third one is the custom messages to show. Each parameter is an array. ```php Validator::make($fields,$rules,$message) use Illuminate\Support\Facades\Validator; public function store(Request $request){ $validator = Validator::make( [ 'email' => $request->email, 'name'=>$request->name ], [ 'email' => ['required','email','unique:users'], 'name' => ['required','max:40'] ],[ 'name.required' => 'Please enter your name', 'name.max' => 'Name should not exceed 40 characters', ]); } ``` Laravel automatically redirects back to the route from which the request is initiated with the error messages. If you want to redirect to somewhere else, you can use the ‘fails’ method to check if the validation is failed . ```php if($validator->fails()){ return redirect()->route('abc') ->withInputs($request->all()) ->withErrors($validator); } ``` If you want to check if validation passes, there is a method for it too: ```php if($validator->passes()){ // } ``` To get validated fields, you can use the validated method or safe method. Additionally, you can even get only the fields you wan to use or can exclude some fields like these: ```php $validator->validated(); //array of validated fields $validator->safe()->all(); $validator->safe()->except(['password']); $validator->safe()->only(['email','name']); ``` If you want to make the collection of safe fields, you can do it like this: ```php $validator->safe()->collect(); ``` If you want to stop validator to run after the first failure, you can use “stopOnFirstFailure” method chained with “fails” method available with Validator facade like this: ```php if ($validator->stopOnFirstFailure()->fails()) { // ... } ``` **FormRequests** Syntax: ```php public function store(UserRequest $request){ // } ``` An efficient way of creating validation and validating http request inputs is by using FormRequests that can be easily created by composer command: ```bash php artisan make:request UserRequest ``` The form requests have rules method for making rules and messages method for making custom messages like this: ```php //for stoping on first failure protected $stopOnFirstFailure = true; public function rules() { return [ 'email' => 'required|email|unique:users', 'name' => 'required', ]; } public function messages() { return [ 'email.required' => 'Please enter email', 'name.required' => 'Please enter name', ]; } ``` All the available validation methods are listed here: [Validation](https://laravel.com/docs/8.x/validation#available-validation-rules) I hope you like the blog and if you do, then don’t forget to hit that clap icon and if you want to read more such blogs, do follow me. ### Middlewares in Laravel 2021-08-14 · https://dikshantraj.dev/blog/middlewares-in-laravel ![](https://dikshantraj.dev/blog/middlewares-in-laravel/1.png) In my previous blogs, I have told about the different aspects of authenticating and verifying users. Have a look on them here [Roles Authentication in Laravel](https://dikshantraj.dev/blog/roles-authentication-in-laravel) In this blog, I will be telling about middlewares in Laravel that comes in very handy while dealing with tasks that we want to do before forwarding Http requests and after forwarding Http requests. ![](https://dikshantraj.dev/blog/middlewares-in-laravel/2.png) Middlewares are used for many tasks and you can use them to perform tasks like: - Authenticating users - Validating incoming requests - Change the default language - Checking roles - Checking permissions - Adding headers to http requests - Logging requests Laravel itself uses a middleware that verifies the user of your application is authenticated or not. If the user is not authenticated, the middleware will redirect the user to your application’s login screen. To create a middleware, use this command ```bash php artisan make:middleware CheckAgeMiddleware ``` In this example, we will be checking the age of the user when he tries to access a particular route and will forbid his access if he/she is a minor. For this purpose, we will be taking the dob of the user at the time of registration and calculate age in the middleware and provide access if the age is greater than 18. Let’s start… #### **Creating Middleware** After running the command, a **CheckAgeMiddleware **file will be created in **app\Http\Middleware** folder. A middleware file generally consists of handle method with the following definition: ```php public function handle(Request $request, Closure $next) { //task return $next($request); } ``` The $next($request) is used to proceed the request further. There are two ways of performing actions on the requests . One is before the http request and other way is after the http request. The above method shows task to be done before the request have passed. To perform task after the request, you can do something like this: ```php public function handle(Request $request, Closure $next) { $response = $next($request); //task return $response; } ``` We have to just calculate the age of the user and restrict him from going further so we will use the first way like this: ```php public function handle(Request $request, Closure $next) { abort_if(Carbon::parse(auth()->user()->dob)->age < 18, 403 , 'Age Restricted Page'); return $next($request); } ``` The above handle method will first calculate the age and if it is less than 18, it will abort the request and show the forbidden(403) page with custom message. #### **Registering the middelware** We have to tell Laravel that this is the middleware and we have to use it so we have to register it in the **Kernel.php **file in the** app\Http** folder like this: ```php In the route middleware method, add this line 'age.check' => CheckAgeMiddleware::class ``` #### **Applying middleware on the route** In **routes/web.php** file, register the route and apply middleware on it like this: ```php Route::get('user/ageRestrictedPage',[App\Http\Controllers\UserController::class,'ageRestrictedPage'])->name('age.restricted.page')->middleware('age.check'); ``` Now you can use this route anywhere and whenever a user will move on the route, application will check his/her age and if it is less than 18, it will show something like this: ![](https://dikshantraj.dev/blog/middlewares-in-laravel/3.png) This is how you can create your middleware and restrict users or log them or can perform any task. All the references are taken from here: [Middleware](https://laravel.com/docs/8.x/middleware) You will find the code here: [GitHub - dikshantrajput/auth-medium at middleware](https://github.com/dikshantrajput/auth-medium/tree/middleware) I hope you like this and if you do, don’t forget to hit that clap icon and follow me for more such blogs. ### Ajax Requests in Laravel 2021-07-20 · https://dikshantraj.dev/blog/ajax-requests-in-laravel ![](https://dikshantraj.dev/blog/ajax-requests-in-laravel/1.png) Ajax or Asynchronous JavaScript and XML is one of the most beautiful part of webpages to create a request to the backend server from Laravel or PHP based application as it potentially stops the loading of page unnecessarily for a small task like “Liking a post” or “Commenting on a post” and also it saves a lot of resources and a lot of HTTP requests are not being called that a webpage made on every page load. It’s not that difficult task to make an ajax call using a library like jQuery, Axios, fetch api etc or even you can use vanilla javascript for making an Ajax or XMLHttpRequest. In this blog I will be telling about how to make an ajax request from your laravel application using jQuery. There are other libraries available out there, you can use any one. In my previous blogs, I have told about authentication, multi-auth, relationships and many more topics about Laravel. Don’t forget to check them out . [Roles Authentication in Laravel](https://dikshantraj.dev/blog/roles-authentication-in-laravel) **jQuery Ajax Request** It’s very simple to make a basic ajax request without any overhead. If you want to know about all the methods available in jQuery for making an ajax request, visit this : [jQuery.ajax()](https://api.jquery.com/jquery.ajax/) Let’s start with making a basic request for fetching data of a user. First of all, we have to add jQuery cdn or we can include the whole package, In this blog, I will be using a CDN like this: ```html ``` Add this in the layouts file that you used to include in your blade file in the end of your body section Making the request from the blade file : ```html
``` In the above code, fetchData() is a function that is used to send the ajax request with the help of $.ajax() function available with jQuery library We have to make a route before everything in the routes/web.php file like this : ```php Route::group(['middleware'=>'auth'],function(){ Route::get('user/data', [App\Http\Controllers\UserController::class,'getData'])- >name('user.data'); }); ``` The UserController getData() method looks something like this: ```php public function getData(Request $request){ $user_id = $request->id; $user = User::find($user_id)->first(['name','email','mobile']); // $user = auth()->user(); return view('users.data',compact('user')); } ``` In the above method, we have two option to fetch the user. One is by using the auth() facade and the other way is by sending the id as a get parameter and then fetching the user from that id. I have mentioned both the method above. We are returning the users.data view blade file that contains the appropriate html inside it and it look something like this: ```html
Name Email Mobile
{{ $user->name }} {{ $user->email }} {{ $user->mobile }}
``` One more thing that I want to focus on here is while using POST method you have to send the csrf token as every request in Laravel is secured by csrf token so we can make a post request and send the csrf token like this: ```php //change the type to "POST" in $.ajax({}) method and in web.php file $.ajaxSetup({ headers : { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content') } }); ``` Thats it… You can now send any amount of data or request and fetch data without need of reloading the page. ![](https://dikshantraj.dev/blog/ajax-requests-in-laravel/2.png) Thanks for reading the blog. I hope you have liked the blog and if you do…..please hit that clap icon and if you want to read more such blogs…..do follow me. All the code of this blog is uploaded to github here: [dikshantrajput/auth-medium](https://github.com/dikshantrajput/auth-medium/tree/ajax) ### Roles Authentication in Laravel 2021-07-10 · https://dikshantraj.dev/blog/roles-authentication-in-laravel ![](https://dikshantraj.dev/blog/roles-authentication-in-laravel/1.png) Authentication is the most important part of any application and the first basic thing that separates your privileged users from a non privileged user. In my previous blogs, I have covered these topics “**Laravel Authentication**(Theory & Practical Implementation)”, “**Verify Users**”, etc. Today, I will be writing about roles in Laravel and how can you differ your users and have separate access for them. If you haven’t read my previous blogs, I would recommend you to first read them because I will be taking the code from these blogs further and will not going to cover the basics again. So, let’s start… [Laravel Authentication (Practical Implementation)](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation) I will be creating three access areas or three types of roles i.e **user role**, **admin role** and **super admin role**. ![](https://dikshantraj.dev/blog/roles-authentication-in-laravel/2.jpeg) #### **Database Structure** First of all we will require a table to store the three roles and have a connection between roles and users table that will be having many-to-many relationship. [Relationships in Laravel](https://dikshantraj.dev/blog/relationships-in-laravel) ```bash php artisan make:migration create_roles_table //Roles migration file public function up() { Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('slug'); $table->string('desc'); $table->timestamps(); }); } ``` This will create a **roles** table with columns id, name, slug, desc where the column names are self explanatory. Then run, ```bash php artisan make:migration create_role_user_table //Role User Pivot table migration file public function up() { Schema::create('role_user', function (Blueprint $table) { $table->id(); $table->foreignId('role_id')->constrained()->onUpdate('cascade')->onDelete('cascade'); $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); }); } ``` This will create a **role_user pivot** table with column id, role_id, user_id for defining which user have which roles. Now run the migrations ```bash php artisan migrate ``` #### **Models** Create models for role and role_user table. Run ```bash php artisan make:model Role php artisan make:model RoleUser ``` **Role** Model will look something like this with fillable array. ```php class Role extends Model { use HasFactory; protected $fillable = [ 'name', 'slug', 'desc' ]; } ``` **RoleUser** Model will look something like this with fillable array. ```php class RoleUser extends Model { use HasFactory; protected $table = 'role_user'; protected $fillable = [ 'role_id', 'user_id' ]; } ``` #### **Seeders** We have to make three roles for which we have to seed some data or create some records in roles table, you can create record manually in db or make seeders. ```bash php artisan make:seeder RolesSeedeer public function run() { Role::insert([ [ 'name'=>'Super Admin Role', 'slug'=>'SUPER_ADMIN', 'desc'=>'Access to admin section', ], [ 'name'=>'Admin Role', 'slug'=>'ADMIN', 'desc'=>'Access to admin section', ], [ 'name'=>'User Role', 'slug'=>'USER', 'desc'=>'User role with access to user section', ], ]); } ``` Now run, ```bash php artisan db:seed --class=RolesSeeder ``` This will create some entry for roles table with roles — User role, admin role and super admin role. We also have to create users entries in db along with role_user table entries. ```bash php artisan make:seeder UsersSeeder public function run() { User::insert([ [ 'name'=>'User 1', 'email'=>'user1@gmail.com', 'password'=>Hash::make('aaaaaaaa'), 'email_verified_at'=>now(), 'mobile'=>'1111111111' ], [ 'name'=>'User 2', 'email'=>'user2@gmail.com', 'password'=>Hash::make('bbbbbbbb'), 'email_verified_at'=>now(), 'mobile'=>'1111111111' ], [ 'name'=>'User 3', 'email'=>'user3@gmail.com', 'password'=>Hash::make('cccccccc'), 'email_verified_at'=>now(), 'mobile'=>'1111111111' ], ]); } php artisan make:seeder RoleUserSeeder public function run() { RoleUser::insert([ [ 'role_id'=>1, 'user_id'=>1 ], [ 'role_id'=>2, 'user_id'=>2 ], [ 'role_id'=>3, 'user_id'=>3 ] ]); } ``` Now seed them one by one in the db ```bash php artisan db:seed --class=UsersSeeder php artisan db:seed --class=RoleUserSeeder ``` Now everything is ready, we just need to restrict the non-privileged user from privileged section i.e admin panel and for this we will be creating middlewares and protecting our routes. #### **Relationship** In User model, we have to define roles relation like this: ```php public function roles(){ return $this->belongsToMany(Role::class); } ``` Now, I will be creating some functions in the same model for checking roles of the user by passing parameters for roles slug like this : ```php public function hasRole($role){ return $this->roles->where('slug',$role)->count() > 0; } public function hasAnyRole($roles){ foreach($roles as $role){ if($this->hasRole($role)){ return true; } } return false; } ``` The functions are self explanatory. #### **Middleware** We will be needing a middleware to check the requests and if the user is allowed to goo further or not. If the user doesn’t have required permission, we will be showing forbidden page. ```bash php artisan make:middleware RoleMiddleware public function handle(Request $request, Closure $next, ...$roles) { if(!auth()->user()->hasAnyRole($roles)){ abort(403); } return $next($request); } ``` Now register the middleware in the App\Http\Kernel.php file in “**routeMiddleware**” method like this : ```php 'role' => App\Http\Middleware\RoleMiddleware::class, ``` #### **Routes** Just a last step, we need to create route and protect them using middlewares like this : ```php Route::group(['middleware'=>'role:ADMIN,SUPER_ADMIN'],function(){ Route::get('/admin/dashboard',function(){ return '

Admin Panel

'; }); }); ``` Now, if any user that doesn’t have permission of ADMIN or SUPER_ADMIN can’t visit the admin/dashboard. ![](https://dikshantraj.dev/blog/roles-authentication-in-laravel/3.png) You can create multiple views and areas for different type of users. All the code related to this blog is in this repository : [dikshantrajput/auth-medium](https://github.com/dikshantrajput/auth-medium/tree/role_authentication) I hope you like this blog and if you do, please hit that clap icon and if you have any issue or any suggestion please feel free to comment. Follow me for more such blogs. ### Relationships in Laravel 2021-07-01 · https://dikshantraj.dev/blog/relationships-in-laravel ![](https://dikshantraj.dev/blog/relationships-in-laravel/1.png) Relationship in Laravel are the most beautiful and most scariest part at the same time. Beautiful because you don’t have to write long long queries to seek data between related entities as in traditional PHP. Scariest because it can lead to (n+1) optimisation problem which can really slow down your website by a huge factor. First of all, thank you for your great response on my previous blog on **Optimising Laravel Mails.** If you haven’t read it yet, I would recommend to have a look here: [Optimising Laravel Mails](https://dikshantraj.dev/blog/optimising-laravel-mails) If relationships(in Laravel) are created and worked properly, you will definitely start to **love** Laravel and stick to it. It is one of the part which takes some experience to know them and use them properly. I also got struck at them in my beginning and started **hating **Laravel but now when i know about them, I would not say that I know the whole deep concept, but yes, I have some basic knowledge about them and can query the database using** Eloquent Relationship **that saves a lot of time. Let’s start…… > Relationship in Laravel are same as in real life **easy to create** but **difficult to work on**. **What is relationship ?** Relationship is nothing but just a function or you can call it a method that help connecting models(db table) together that are related to each other. e.g. A user table can be related to a profile table or you can say user table and profile table have relationship between them. To be precise - **User has a Profile **or P**rofile belongs to a User**. They have **one to one** relation with each other. **Types** Some common and most used types of relationships are : 1. One To One 2. One To Many 3. Many To many There are more but let’s discuss about these three in this blog. #### **One To One Relationship** As the name suggests, it’s the relationship of one model to the other model. e.g A User model has one Profile. ![](https://dikshantraj.dev/blog/relationships-in-laravel/2.png) _One to one relationship_ **Syntax:** ```php class User{ public function profile(){ return $this->hasOne(Profile::class); OR return $this->hasone('App\Models\Profile'); } } ``` This code will build a relationship of user with profile model. Now you can access the profile of a user like this: ```php $profile = User::find(1)->profile; ``` The beauty of Eloquent is that it determines the foreign id on the table itself and if you have some other column, then you can provide it as a second argument to the hasOne function like this : ```php return $this->hasOne(Profile::class, 'foreign_key'); ``` This function will search for profile on the basis of user’s table primary key i.e id. If you want to connect it with some other column, then you can also specify it like this: ```php return $this->hasOne(Profile::class,'foreign_key','local_key'); ``` So this will look something like this, ```php return $this->hasOne(Profile::class,'profile_id','id'); ``` **Inverse of One to One** Now one thing will come into your mind is that how to fetch the user if you have profile with you. So for that purpose you have to specify the reverse of relationship like this: ```php class Profile{ public function user(){ return $this->belongsTo(User::class); } } ``` This function will let you access the user from profile like this : ```php Profile::find(1)->user; ``` All the other rules of foreign and local key apply to this also. ```php return $this->belongsTo(User::class, 'foreign_key', 'local_key'); ``` **That’s it**… You have successfully created a **one to one relationship** between user and profile table/model. #### **One To Many Relationship** As the name suggests, one model is connected to more than one models i.e parent having multiple children or in more simple terms, one row of parent table having relationship with more than one or one row of child table. It seems to be little bit confusing but trust me it’s very simple. Let me give an example. e.g A User can have multiple Orders. ![](https://dikshantraj.dev/blog/relationships-in-laravel/3.png) _One to Many relationship_ **Syntax :** ```php class User{ public function orders(){ return $this->hasMany(Order::class); OR return $this->hasMany('App\Models\Order'); } } ``` This will create a relationship between User and Order model where a user can have a single or multiple orders. You can fetch the orders of a user like this : ```php $orders = User::find(1)->orders; foreach($orders as $order){ // } ``` Like the hasOne() method, you may also override the foreign and local keys by passing additional arguments to the hasMany() method like this : ```php return $this->hasMany(Order::class,'foreign_key','local_key'); ``` **Inverse of One to Many** If you want to get the user detail from the order, you can do something like this : ```php class Order{ public function user(){ return $this->belongsTo(User::class); } } ``` You can access user from order like so : ```php $user = Order::find(1)->user; ``` All the other rules of foreign and local key apply to this also. ```php return $this->belongsTo(User::class,'foreign_key','local_key'); ``` #### **Many To Many Relationship** As the name suggests, more than one model is connected to more than one models. It seems to be little bit more confusing than the hasOne and hasMany relations but trust me it’s also simple. Let me give an example. e.g A User can have multiple Roles and a Role can belong to many Users. Suppose there is a **user **who is having** admin as well as user role **and there can be **multiple admins and users.** In this case you have to use many to many relationship**.** ![](https://dikshantraj.dev/blog/relationships-in-laravel/4.png) _Many to Many relationship_ In these types of relationship you have to create an extra table that is known as _“pivot table”_. In this case the table will be names as **role_user**. Remember Laravel users some naming convention so the pivot table should be separated by an underscore and should be arranged **alphabetically**. The schema/structure of the pivot table will be this : ```php role_user ---> id user_id role_id ``` **Syntax :** ```php class User{ public function roles(){ return $this->belongsToMany(Role::class); } } ``` To access user Roles from user, you can do something like this : ```php $roles = User::find(1)->roles; foreach ($user->roles as $role) { // } ``` If you want to override the pivot table’s name, you can pass table name as a second argument like this : ```php return $this->belongsToMany(Role::class,'pivot_table_name'); ``` To customise the column name you can use the third argument as the table column from which you are creating relationship like “user_id” and fourth argument as the table column to which you are pointing like “role_id” in the pivot’s table .The syntax will look something like this : ```php belongsToMany(Role::class,'pivot_table','reference_from_column','reference_to_column'); ``` **Inverse of Many to Many** Now if you want to get the list of users from roles model, do the same as done on users models like this : ```php class Role{ public function users(){ return $this->belongsToMany(User::class); } } ``` You can access users in your code like this : ```php $users = Role::find(1)->users; foreach ($roles->users as $user) { // } ``` All the rules are same as above for table naming and column naming . **That’s it.**…. If you know about these **three relationship**, you can easily get advantage and use it in your code to make your queries a lot shorter. Play around the code and go through it several times and if you still found any issue, shoot it in the **comments **and If you like the blog, then please hit that **clap button **and follow me for more such blog. I will be posting my next blog on it’s** practical implementatio**n. So stay tuned… You can learn more about relationships here : [Eloquent: Relationships](https://laravel.com/docs/8.x/eloquent-relationships) ### Verify User in Laravel (send verification mail efficiently) 2021-06-23 · https://dikshantraj.dev/blog/verify-user-in-laravel-send-verification-mail-efficiently ![](https://dikshantraj.dev/blog/verify-user-in-laravel-send-verification-mail-efficiently/1.png) In my previous blog, I have discussed about the optimisation of Laravel mails using Queue. In this blog, I will be telling about how you can verify a user by sending him **verification mail** through Laravel default Auth. [Optimising Laravel Mails](https://dikshantraj.dev/blog/optimising-laravel-mails) So Laravel provides a beautiful and a simple way to send verification mail and it itself generates the signature and everything so you don’t need to implement it b yourself. So let’s get started…. Laravel by default saves a field in users table named email_verified_at which is filled only when the user verifies his/her mail. If this field is null that means the account is not verified and if it have some date that means the user’s account is verified. **User Model** You just need to implement an interface for enabling the email verification when a user signs up. The User class blueprint will looks like this : ```php class User extends Authenticatable implements MustVerifyEmail{ } ``` **Routes** You need to create 3 routes for verification purpose : 1. **Verification View** :- This route will be a get route and as the name suggests it is the view or the html that the user will see after registration or if he tries to access other parts of application. This route has to be named as “verification.notice”. It will look something like this : ```php Route::get('/email/verify',function(){ return view('email.verification-notice'); })->middleware('auth')->name('verification.notice'); ``` 2. **Verification Logic **:- This route will also be a get route and as the name suggests all the logic for making user verify from checking the payload signature from the url and updating the email_verified_at field in db. This route has to be named as “verification.verify” and it will look something like this : ```php Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) { $request->fulfill(); return redirect('/home'); })->middleware(['auth', 'signed'])->name('verification.verify'); ``` The callback function will validate the request and for that purpose a separate validation class is made by Laravel named EmailVerificationRequest. It will check for any error and if there is no error the fulfill() method will be called and the field in the db will be updated. 3. **Verification Mail Resend :-** If by-chance in any case the user misplaces the url or the email gets deleted you can give user a second option to verify their mail. This route has to be named as “verification.send” and it will look something like this : ```php Route::post('/email/verification-notification', function (Request $request) { $request->user()->sendEmailVerificationNotification(); return back()->with('message', 'Verification link sent!'); })->middleware(['auth', 'throttle:6,1'])->name('verification.send'); ``` This will resend the verification mail with new signature. Now whenever a user signs up (register) for your application a **mail** will be send automatically. ![](https://dikshantraj.dev/blog/verify-user-in-laravel-send-verification-mail-efficiently/2.png) _verification email example mail_ There’s an issue with this approach that your application will take a lot of time to send the mail so as I told in my previous blog that we can use queue to save time and the mail will be sent in background using queue worker. For this you have to create a job by using : ```bash php artisan make:job VerifyEmailJob ``` Now you have to overwrite the sendEmailVerificationNotification() method for dispatching the VerifyEmailJob with user forsending verification email like this : ```php public function sendEmailVerificationNotification(){ VerifyEmailJob::dispatch($this); } ``` Inside App/Jobs/VerifyEmailJob, create a private variable named user and initialize the user variable in __construct() method. ```php use App\Models\User; private $user; public function __construct(User $user) { $this->user = $user; } ``` In handle method, send the mail using Laravel default VerifyEmail notification. ```php use Illuminate\Auth\Notifications\VerifyEmail; public function handle() { $this->user->notify(new VerifyEmail); } ``` Now the email will be pushed to queue and will be placed in jobs db table. To execute them, run ```bash php artisan queue:work ``` Now the email will be sent in the background to the registered user and the execution time will be reduced and the efficiency of the application will improve and optimised. You can find all the code here : [dikshantrajput/auth-medium](https://github.com/dikshantrajput/auth-medium/tree/email_verification) Hope you like the blog and please hit that clap icon and follow me for more such Laravel basics blogs….. ### Optimising Laravel Mails 2021-06-19 · https://dikshantraj.dev/blog/optimising-laravel-mails ![](https://dikshantraj.dev/blog/optimising-laravel-mails/1.png) In my previous blog, I have discussed about basic functionality of sending mails to someone through your application. In this blog, I will be telling about some **optimisation** technique which can reduce the waiting time for the users. [Mails in Laravel](https://dikshantraj.dev/blog/mails-in-laravel) As you have seen that while sending mail from controller, It takes a lot of time to process. So Laravel have provided us with a option to queue the sending of mails i.e sending the mails through background just like a cron job if you have heard about it. It’s very easy to make any mail queueable. Let’s get started… First of all you need to create migrations for jobs and failed jobs . It can be done by running : ```bash php artisan queue:table ``` Now one simple way to make mails to run in queue is by just using queue method instead of send like this : ```php Mail::to($user->email) ->from('email-address') ->queue(new WelcomeMail($user)) ``` One more thing which I forgot to mention in my previous blog is that you can also easily add cc and bcc to your mails by just adding cc and bcc methods like this : ```php Mail::to($user->email) ->from('email-address') ->cc('email-address') ->bcc('email-address') ->queue(new WelcomeMail($user)) ``` After queuing the mail, If you will check jobs table in your db, you can find a job ready to be run. So for running the job just run : ```bash php artisan queue:work ``` This will make the job to run in background and the mail will be sent if everything goes well. If in any case the job fails, you can check the reason of failure by going to failed-jobs table. Laravel also provides a beautiful method to delay your mails for a certain amount of time. You just need to use the later method in place of queue method and later method accepts two parameter. One is the DateTime instance indicating when to send mail like next week, next hour or so and the second parameter is the mailable instance. ```php ->later(now()->nextWeeks(1), new WelcomeMail($user)); ``` So this will automatically send the mail after one week if the queue worker is running on your server. ![](https://dikshantraj.dev/blog/optimising-laravel-mails/2.jpeg) **Another way** One more way for making mails queueable is by using the ShouldQueue interface that is provided by Laravel queues. Just implement ShouldQueue interface to the mailable class like this : ```php use Illuminate\Contracts\Queue\ShouldQueue; class WelcomeMail extends Mailable implements ShouldQueue{ // } ``` By using this you need not to use queue() method with Mail facade, send() method will also work. So these were few simple tricks to optimise performance of your application for sending mails. Hope you like it and if you want in-depth explanation of queues and mailables, just hit the clap icon and I will be uploading more such simple content to make your life simple….. Follow me for more such blogs… ### Mails in Laravel 2021-06-18 · https://dikshantraj.dev/blog/mails-in-laravel ![](https://dikshantraj.dev/blog/mails-in-laravel/1.png) In my recent blogs, I have discussed about Laravel authentication and sending **mails** to the newly registered user is a must have functionality for every application. So today I will be telling about how to send mail from laravel. I will be telling about smtp driver but there are many drivers available in the market which can be used to send mails but most basic one is smtp. So let’s start !!! If you haven’t read my previous blog post about laravel authentication, I would recommend you to have a look at it first then continue with this one. [Laravel Authentication (Practical Implementation)](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation) ![](https://dikshantraj.dev/blog/mails-in-laravel/2.png) Sending mails in Laravel is like adding a cherry to the cake. It’s so simple to send a mail and if you follow all the steps you will be able to send your first mail from your application. **Configurations** First of all you need to configure mail account credentials in .env file or you can even do that in config/mail.php file but I will recommend you to do that in the .env file ![](https://dikshantraj.dev/blog/mails-in-laravel/3.png) _config for smtp mail_ **View File** Create a view file(html) that you want to send to the user that registers in your application. Create a folder of mails in your resources/views directory and inside that create a welcome.blade.php file For simplicity, I have just added the Welcome text along with mobile number of user. ```html

Welcome : {{ $user->mobile }}

``` **Logic** Now, you will be wondering how we can get the user mobile number to send in the mail. For that you need to create a mail php file that will contain the actual logic of mail and the data to be passed in the template. Just run ```bash php artisan make:mail WelcomeMail ``` A file will be created in App\Mail named WelcomeMail.php We need to pass the user details to the blade file so just create a public variable named user in this file like this : ```php public $user; ``` To set this variable, we will be using it’s constructor like so : ```php public function __construct($user){ $this->user = $user; } ``` One important thing : You can pass the variable to the blade file in two ways one by creating public variable and the public variable will be accessible directly in the view file and the other way is to create a protected or private variable and sending the user variable using the with method . I will show you both approaches. If you use the above method i.e creating a public variable then you don’t need to do anything just return the view file from the build method like this: ```php public function build() { return $this->view('mails.welcome'); } ``` If you don’t want to make variable public, you can pass it with the with method like : ```php return $this->with(['user'=>$this->user])->view('mails.welcome'); ``` This time the user variable is not an object, it’s an array so use $user[‘mobile‘] in blade file. Along with view , you can also specify with which email account you want to send the mail by chaining from method in return statement like this: ```php return $this->from('mail-id@gmail.com')->view('mails.welcome'); ``` If you don’t specify from method, laravel will automatically take the mail which you have specified in your .env file (MAIL_FROM_ADDRESS variable) **Sending Mail** You can send a mail from any controller within your application using the Mail facade like this: ```php Mail::to($user->email) ->send(new WelcomeMail($user)); ``` If you want to send it while a user registers to your application, you need to change the create method of App\Http\Controllers\Auth\RegisterController.php like this: ```php protected function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'mobile'=>$data['mobile'], ]); Mail::to($user->email) ->send(new WelcomeMail($user)); return $user; } ``` That’s it…An email will be sent to the user’s email address who signs up. I hop you liked the blog and if you , then please hit that clap icon and follow me for more such basic laravel blogs. **NOTE**: All the code is pushed in this repo under branch “mail_to_regstered_users” [dikshantrajput/auth-medium](https://github.com/dikshantrajput/auth-medium/tree/mail_to_regstered_users) ### JavaScript at ground level!!! 2021-06-06 · https://dikshantraj.dev/blog/javascript-at-ground-level ![](https://dikshantraj.dev/blog/javascript-at-ground-level/1.png) _Deep dive in JavaScript_ JavaScript is one of the most popular language out there in the industry. With emerging technology and birth of new languages, JavaScript is a language which you can blindfoldly rely on and it’s not going anywhere for minimum a decade. In this blog post, I am not going to tell anything about code or any library or any framework but pure JS working. How the browser interprets the code and execute it? Where the variables, functions are stored in memory? I will also not get very deep into it as it would take a day to type me all underlying principles. I would be giving just a wider picture so that everything can become crystal clear and you will surely love it. **ORIGIN** In September 1995, a Netscape programmer named Brandan Eich developed a new scripting language in just 10 days. It was originally named **Mocha**, but quickly became known as **LiveScript **and, later, **JavaScript**. **ECMAScript** It is a JavaScript standard meant to ensure the interoperability of web pages across different web browsers so that everyone have a single form and functionality remains constant across platforms. ![](https://dikshantraj.dev/blog/javascript-at-ground-level/2.jpeg) JavaScript is a **single-threaded synchronous** language… **Execution Context is basically a concept of environment that is setup before execution of any JS program.** There are two things inside this execution context : 1. Memory Area (Allocation area OR Variable Environment) 2. Code Area (Thread of execution) Before execution of any JS program, a global execution context is created. The execution of a JS program is done in 2 Phases. In first phase, memory is allocated to the variables and functions in the form of key value pair objects in the browser. In second phase, code is interpreted line by line and if there is any error, it is reported and the remaining execution of program is paused until the error is fixed. ![](https://dikshantraj.dev/blog/javascript-at-ground-level/3.png) _Global execution context_ Now I will be explaining everything with the help of a simple program. ```js var a = 10; var b = 20; function sum(num1 , num2){ return num1 + num2; } sum(a,b); ``` Before starting the execution of this program a global execution context will be created and it will look something like this: ![](https://dikshantraj.dev/blog/javascript-at-ground-level/4.png) First of all all the variables and function will be created in the phase one i.e memory allocation. It will make key value pairs of variables and functions . The variables are assigned a special value i.e “undefined”. Then the code will start to execute from the very first line and a and b will be assigned value 10 and 20 respectively. Then it will skip the function body and when it reaches the last line where we invoke the function sum(), a new execution context will be created all together for the function containing memory and code area. This is the real beauty of JS, At the time of invoking each functions, a completely new execution context will be created and it will look something like this : ![](https://dikshantraj.dev/blog/javascript-at-ground-level/5.png) _Sum fn execution context_ num1 and num2 i.e the parameters of the function are allocated memory and given a value of undefined. When the code is interpreted from the first line of the function , it will receive a and b i.e the arguments passed to function with value 10 and 20 as in global context their value is 10 and 20 respectively. sum(num1 , num2) → The value of num1 and num2 will be 10 and 20 in the memory area respectively. Then in the second line when it encountered the return statement it will calculate the sum i.e num1 + num2 and the control of the program will again come to global execution context and the value returned will be placed in place of sum(a,b) **NOTE :** Whenever a return statement is encountered the execution context created gets destroyed and control of the program is returned to global execution context. **Management of contexts(Call Stack)** You might be wondering that it is a cumbersome task to keep track of all the execution context and destroying them. So here again you will get to see the beauty of JavaScript. A **stack **is used to keep the record of all the execution contexts. It is called **call stack.** Whenever a program is created a global execution context is created and pushed to the call stack. Whenever a function is called and another execution context is created, it is pushed again to the same call stack and whenever it encounters a return statement, the context is popped out of the stack. ![](https://dikshantraj.dev/blog/javascript-at-ground-level/6.png) _Call Stack_ This is the basic functionality that runs behind the hood of every JS program. It’s hard to grasp at first but relax, you will understand it and whenever you will see a JS program your brain will start thinking of this functionality. Hope you will like it and If you want more such blog post do **follow **me and hit that** clap** button. ### Laravel Authentication (Practical Implementation) 2021-05-23 · https://dikshantraj.dev/blog/laravel-authentication-practical-implementation ![](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation/1.png) In previous blog, I have discussed about how to install Laravel bootstrap auth and in this blog, I will tell this with the help of code. If you have not seen my previous blog, do have a look on it here: [Laravel Authentication](https://dikshantraj.dev/blog/laravel-authentication) After installing auth scaffolding, you will get a new folder in **app\Http\Controllers **named** Auth** ![](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation/2.png) _Auth folder structure_ As you can see there are multiple Controllers files with logic for handling your users. The logic behind these files are self explanatory as their name. Try to register a user by going to /register url and you will notice that by default name, email, password and confirm password field. Whenever you register a user you will automatically login. The frontend(view) files for register, login, and some passwords related files are inside the **resources\views\auth** folder. In many conditions, you may also have to add some extra fields to the user . You can easily do it by going to your register.blade.php file and adding a new input as per your requirements. In this blog I will be adding a mobile number field. ```html
@error('mobile') {{ $message }} @enderror
``` After adding it your frontend will look like this ![](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation/3.png) Add the mobile field in your database by creating a migration by running ```bash php artisan make:migration add_mobile_field_to_users_table ``` A new migration file will be created in **database/migrations** folder Add this to **up** method of this file: ```php Schema::table('users', function (Blueprint $table) { $table->string('mobile',10)->nullable(); }); ``` Then run, ```bash php artisan migrate ``` Then add ‘mobile’ to the fillable array of **User** model ```php protected $fillable = [ 'name', 'email', 'password', 'mobile' ]; ``` Now you have to change the logic part i.e. controller file. Open RegisterController.php and edit the validator function. ```php 'mobile'=>['required','string','digits:10'] ``` Then edit the create method where the user is actually created, Add this line to User::create function ```php 'mobile'=>$data['mobile'] ``` Now go to your /register url and try to register the user with mobile number field filled ![](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation/4.png) After successfully registering you will be login to the application . To access this field go to the home.blade.php file and write this code anywhere in the file according to the view you want. ```php {{ __('Mobile : ') . auth()->user()->mobile }} ``` ![](https://dikshantraj.dev/blog/laravel-authentication-practical-implementation/5.png) Congratulations!!! You have successfully created a new field in db . Now you can add any field or can remove any field according to your requirement. You can find the above code on **github** here: [dikshantrajput/auth-medium](https://github.com/dikshantrajput/auth-medium/tree/final_code) Thank you for reading. If you like the post, please hit that clap icon and follow me for more blogs on Laravel basics….. ### Laravel Authentication 2021-05-20 · https://dikshantraj.dev/blog/laravel-authentication ![](https://dikshantraj.dev/blog/laravel-authentication/1.png) In today’s world, user security and privacy is the most important thing. Building a authentication system is not everyone’s cup of tea. But with Laravel, it’s not that hard . There are many types of authentication that you can apply while building a website with Laravel. You can either use Laravel default authentication or can use any third party library like sanctum, passport etc. Today I am going to tell something about Laravel’s default authentication There are different types of authentication that are introduced in different versions of laravel but Laravel Bootstrap UI authentication is the best and most simplest one that you can use in your next project. Best part is that there are no overhead while using this authentication. So let’s start… Run this composer command to install Bootstrap Auth in your fresh Laravel project. ```bash composer require laravel/ui php artisan ui bootstrap --auth ``` As you see we have given bootstrap — auth flag to the php artisan ui command which tells the artisan tool to install auth with bootstrap as default scaffolding. So If you are familiar with any other library like vue or react you can easily install using them also. But bootstrap is the most simple and loved library so I will be taking it as a starting point. After installing the dependency, you have to run ```bash npm install && npm run dev OR yarn install && yarn run dev ``` If you don’t want to use npm run dev you can even use npm run watch After running this, all the additional styling and javascript files will be installed in your node_modules folder. Your Bootstrap scaffolding is now ready and test it by running the server first with ```bash php artisan serve ``` Open the page in browser and go to {localhostURL}/register e.g. localhost:8000/register ![](https://dikshantraj.dev/blog/laravel-authentication/2.png) _Default register page_ Laravel by default have User Model created for you and the authentication now works hand on hand with User Model. If you want to add or remove any field you are free to do that. Now test your application by registering and logging with different users. Congratulations!!! You have successfully installed authentication in your laravel project. In next blog post I will be telling you how to twerk the default fields and how to made this authentication more project friendly. If you like this, please hit that clap icon and If you want more Laravel stuff, don’t forget to follow me. ### Building Your First Application with Laravel 2021-04-24 · https://dikshantraj.dev/blog/building-your-first-application-with-laravel ![](https://dikshantraj.dev/blog/building-your-first-application-with-laravel/1.png) In my previous post, I shared about the folder structure of Laravel. If you haven’t read it, I will suggest you to first read that and then carry on with this one. Link of my previous blog post: [https://dikshantraj2001.medium.com/getting-started-with-laravel-5c9191cee5d0](https://dikshantraj.dev/blog/laravel-application-folder-structure) We will be making a simple To Do App. I know that sounds little simple at first but believe me it’s like the **hello world program of our web world** and by making it you could gain a lot of confidence. Just give it a shot. NOTE: All the code is available on github here : [https://github.com/dikshantrajput/todo-laravel](https://github.com/dikshantrajput/todo-laravel) It would be good if you just not only stare at this blog post but also code along with me. Are you ready for making your first application? If Yes!! Hit that clap button and Let’s Begin….. First of all setup a new project along with database. You can name it as you wish . For simplicity I will name it to-do-app. If you haven’t read my first blog post I would recommend you to first read that. Link is given above. ```bash composer create-project laravel/laravel to-do-app ``` Open a terminal in your preferred directory and run above command. After the project is successfully installed, setup your .env file and initialise the DB_DATABASE variable with the name of db that you want to keep. If you don’t want to take more overhead just fork my repository and follow these steps: ```php Run composer install and then composer update Run npm install && npm run dev Run php artisan key:generate Run php artisan migrate --seed ``` P.S. You will get bootstrap and font awesome installed with the code .If you have any issue just shoot a comment. I will solve your queries As I told in my first blog post, Laravel is a framework build with php following **MVC** pattern. So, the model that we will be creating will be named as ToDo and remember table is named after models in migrations. (e.g if we named our model ToDo then we have to name our table to_dos *plurar*). So let’s first make migration for our db. Migration is like a schema for our to_dos table . ```php Run php artisan make:migration create_to_dos_table ``` In migration file, write this in up method ```php Schema::create('to_dos', function (Blueprint $table) { $table->id(); $table->string('created_by'); $table->string('todo_text'); $table->dateTime('end_at'); $table->timestamps(); }); ``` After this make ToDo model where our db logic will be placed ```bash php artisan make:model ToDo ``` In ToDo model add this code: ```php public $fillable = [ 'created_by', 'todo_text', 'end_at', ]; public function getCreatedDateAttribute(){ return Carbon::parse($this->created_at)->diffForHumans(); } public function getEndingDateAttribute(){ return Carbon::parse(now())->diffForHumans($this->end_at); } ``` In fillable array write the fields you want to create data with help of model. Bellow two functions are just used for view purpose to make created_at and end_at value more human readable. Then go to routes.php and define a route for todos. We will be making it a resourcefull controller . If you want to know more please read in documentation once and if you still need any help shoot that in the comment. Place this code in your web.php file ```php Route::resource('todos','ToDoController'); ``` Then create a controller file where all our actual logic will be placed . ```bash php artisan make:controller ToDoController --resource ``` Place this code in it ```php paginate(20); return view('index',compact('todos')); } public function create(): View { return view('create'); } public function store(ToDoRequest $request) { $data = $request->validated(); if(ToDo::create($data)){ return redirect()->route('todos.index')->with(['success-message'=>'ToDo created successfully']); }else{ return redirect()->route('todos.create')->with(['error-message'=>'Error creating a todo']); } } public function edit(ToDo $todo): View { return view('edit',compact('todo')); } public function update(ToDoRequest $request, ToDo $todo) { $data = $request->validated(); if($todo->update(['end_at'=>$data['end_at'],'todo_text'=>$data['todo_text']])){ return redirect()->route('todos.index')->with(['success-message'=>'ToDo updated successfully']); }else{ return redirect()->route('todos.create')->with(['error-message'=>'Error updating todo']); } } public function destroy(ToDo $todo) { if($todo->delete()){ return redirect()->route('todos.index')->with(['success-message'=>'ToDo deleted successfully']); }else{ return redirect()->route('todos.create')->with(['error-message'=>'Error deleting todo']); } } } ``` Only the view part is left now. I know this is a long blog but hold on with me for a bunch of lines of code more. Go to resources directory and in views directory create all the views file related to create todo, edit and some basic file like a layout file for basic html structure. You will find all these codes in my github repo. Now run ```bash php artisan serve ``` Open localhost:8000 in your browser and you will see something like this ![](https://dikshantraj.dev/blog/building-your-first-application-with-laravel/2.png) _Route /todos_ If you want to add a todo click on Add a ToDo button and you will see something like this ![](https://dikshantraj.dev/blog/building-your-first-application-with-laravel/3.png) _Route /todos/create_ After creating a todo you will be redirected to todos homepage. Then you can edit it or delete it. So, this was it for today’s blog. I hope you would like it. If you find any issue just shoot out it in comments and if you like it hit that clap button. ### Laravel Application folder structure 2021-04-22 · https://dikshantraj.dev/blog/laravel-application-folder-structure ![](https://dikshantraj.dev/blog/laravel-application-folder-structure/1.png) In my previous post, I shared about how to setup Laravel in your system and running the server. If you haven’t read it, I will suggest you to first read that and then carry on with this one. Link of my previous blog post: [https://dikshantraj2001.medium.com/getting-started-with-laravel-5c9191cee5d0](https://dikshantraj.dev/blog/getting-started-with-laravel) It’s very important to know what all you get from the framework that you are going to learn before starting real coding. You should know what all you are getting and how it’s going to make your life easy. So let’s start….. ![](https://dikshantraj.dev/blog/laravel-application-folder-structure/2.png) _Folder structure of laravel application_ APP Directory: It contains the core code and functionality of your application is defined here. BOOTSTRAP Directory: It contains the `app.php` file which bootstraps the framework. CONFIG Directory: It contains all the configuration files for your app. DATABASE Directory: It contains all your files related to database manipulation like migrations, seedings and model factories. PUBLIC Directory: It contains the index.php file and all the other required secondary resources like images, js files, css files etc. RESOURCES Directory: It contains the view files i.e all your html related stuff is in this directory. ROUTES Directory: It contains the routing for your application. STORAGE Directory: It contains the log files, session files, compiled blade templates, caches and other files required to run an application. The `storage/app/public` directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at `public/storage` which points to this directory. You may create the link using the `php artisan storage:link` Artisan command. TEST Directory: It contains all the files related to automated tests for your application. VENDOR Directory: It contains all the composer dependencies files. **WORKING OF A TYPICAL LARAVEL APPLICATION** DISCLAIMER: These all are just fancy words. Don’t get scared by them!!! :) **index.php** First of all I will tell you about the entry point of a laravel application i.e. `**public/index.php**` file. All requests are directed to this file by your web server. There’s not that much code in this file. It is just the starting point for your application. The `index.php` file loads the Composer generated autoloader definition, and then retrieves an instance of the Laravel application from `bootstrap/app.php`. The first action taken by Laravel itself is to create an instance of the application /service container. **HTTP / console kernel** Then the request goes to the HTTP or console **kernel** file depending on the type of request. All the actions that we want to do on the request before actually accessing is done here. Typically, these classes handle internal Laravel configuration that you do not need to worry about. Middlewares and everything is defined here. Don’t be scare with all these names, you will become familiar soon. **Service Providers** One of the most important kernel bootstrapping actions is loading the service providers for your application. All of the service providers for the application are configured in the `config/app.php` configuration file's `providers` array. All the third party libraries are registered here. **Routing** Then comes the routing part. All the routings configurations are in `App\Providers\RouteServiceProvider` file. All the routes from routes folder are loaded . **Last step** Once the route or controller method returns a response, the response will travel back outward through the route’s middleware, giving the application a chance to modify or examine the outgoing response. Finally, once the response travels back through the middleware, the HTTP kernel’s `handle` method returns the response object and the `index.php` file calls the `send` method on the returned response. The `send` method sends the response content to the user's web browser. ![](https://dikshantraj.dev/blog/laravel-application-folder-structure/3.jpeg) _Laravel Life Cycle_ NOTE: For better understanding go to official Laravel documentation, you will find everything there. ALL THE BEST !!! ### Getting started with laravel 2021-04-18 · https://dikshantraj.dev/blog/getting-started-with-laravel This post is for those who are willing to start learning Laravel and I will tell you how to setup environment for efficient and effective learning and creating applications with Laravel. ![](https://dikshantraj.dev/blog/getting-started-with-laravel/1.png) So first of all what is **Laravel **? Laravel is a web application framework with elegant syntax build over core php following the concepts of **MVC** (Model, View, Controller). For those who don’t know about MVC. It is a design strategy (pattern) that separates the application logic(Controller), frontend logic(View) and database logic(Model). ![MVC diagram](https://dikshantraj.dev/blog/getting-started-with-laravel/2.png) _Basic level diagram of MVC_ **Why to use Laravel ?** Before diving deep into Laravel lets understand why do we need Laravel when it is doing the stuff which can be done in core php. So the answer is really simple. As I told earlier it is a framework that means it gives us a pattern of how to create the application. Also it have many predefined functions that can make your life easier and save you from hell lot of overwork that we used to do in core php. So, those who are still hesitating to leave core php. It’s time for stop hesitating and getting started with it !!! Enough of theory, let’s deep dive into it and see how to install Laravel on windows and setup the environment. As there are many ways to install Laravel . I will tell you the most basic way of installing it. Considering you already worked on php and have php and any virtual server(wampp,xampp etc) installed on your system. Personally I would recommend xampp for all the beginners. First of all you need to install composer . You will find it here. [Composer](https://getcomposer.org/download/) After installing composer just open your terminal and for directly creating a project type ```bash composer create-project laravel/laravel name-of-app ``` Or if you want to first install laravel run this in your terminal ```bash composer global require laravel/installer ``` Then run ```php laravel new name-of-app ``` That’s it… Congratulations you have successfully created a new fresh Laravel project. After installing just cd into your app directory and type ```bash php artisan serve ``` Type localhost:port-number(you can get url and port number from your terminal) into your browser and that’s it you will see Laravel appplication running on your browser. Don’t forget to run your virtual server first (xampp or wampp). Now let’s setup database for our application: Create a database on your db manager (like phpmyadmin) Navigate to the .env file in your laravel app and change the DB_DATABASE variable value with the db name you just created DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db_name DB_USERNAME=root DB_PASSWORD= Change the variables as per your requirements. That’s it… You have successfully configured your first Laravel app. HAPPY CODING !!! If you like the blog, please hit that clap icon and comment if you have any issue or want any other blog on Laravel. Also do follow me and contact me if you need any guidance on your Laravel journey. **NOTE**: As of now the current version of Laravel is 8.1 and Laravel team introduces a new version in every 6 months. I would strongly recommend everyone to read their documentation atleast once. Everything which i told here is there in Laravel documentation.