<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ibrahim Amasha on Medium]]></title>
        <description><![CDATA[Stories by Ibrahim Amasha on Medium]]></description>
        <link>https://medium.com/@ibrahimamasha7?source=rss-6ef57e6406c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6lUREJUINPKP6bSk</url>
            <title>Stories by Ibrahim Amasha on Medium</title>
            <link>https://medium.com/@ibrahimamasha7?source=rss-6ef57e6406c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:01:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibrahimamasha7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mid-Level Backend Laravel Interview Q&A : part 2]]></title>
            <link>https://medium.com/@ibrahimamasha7/mid-level-backend-laravel-interview-q-a-part-2-1f62ca627126?source=rss-6ef57e6406c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f62ca627126</guid>
            <dc:creator><![CDATA[Ibrahim Amasha]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 06:56:36 GMT</pubDate>
            <atom:updated>2026-06-23T06:56:36.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>Q1: What is Late Static Binding in PHP?</h3><p>Late Static Binding is a mechanism that allows static method calls to be resolved at runtime based on the class that invoked the method, rather than the class where the method is defined. It enables polymorphic behavior in static contexts.</p><h3>Q2: What is the difference between self:: and static::?</h3><p>self:: is resolved at compile time and always refers to the class where the method is defined, while static:: is resolved at runtime and refers to the class that called the method, enabling late binding behavior.</p><h3>Q3: Why does Laravel rely on Late Static Binding?</h3><p>Laravel uses Late Static Binding to allow models and query builders to behave correctly when inherited. It ensures that methods like where() or factory() return instances of the correct child class instead of the parent class.</p><h3>Q4: What problem does Late Static Binding solve?</h3><p>It solves the issue of static methods not respecting inheritance properly. Without LSB, parent class static methods would always refer to the parent class, breaking polymorphic behavior in inherited classes.</p><h3>Q5: When should you use static:: instead of self::?</h3><p>You should use static:: when you expect methods or properties to be overridden in child classes and want the behavior to adapt dynamically based on the calling class. Use self:: when behavior should remain fixed.</p><p>request lifecycle :</p><p>public/index.php → Kernel → Middleware → Controller → Response</p><p>index.php , bootstrap/app , kernel resolving , Registering and Booting Service Providers , Then global middleware runs, route matching + route middleware , controller execution , response generation , middleware cleanup</p><h3>1. All requests enter through public/index.php</h3><p>Laravel follows the Front Controller pattern, meaning every request is routed through a single entry point:</p><pre>public/index.php</pre><p>This file is responsible for two main things:</p><p><strong>1. Loading Composer’s autoloader</strong></p><p>This allows PHP to automatically locate and load classes whenever they are needed, instead of requiring manual includes throughout the application.</p><p><strong>2. Bootstrapping the Laravel application</strong></p><p>It loads the application instance from:</p><pre>bootstrap/app.php</pre><p>This creates the Laravel Application object.</p><p>The Application object extends Laravel’s service container capabilities and is responsible for:</p><ul><li>Dependency Injection</li><li>Service Resolution</li><li>Binding interfaces to implementations</li><li>Managing the application’s registered services</li></ul><p>At this stage, Laravel exists as an application instance but hasn’t processed the request yet.</p><blockquote><em>After creating the application instance, Laravel asks the Service Container to create the HTTP Kernel object (laravel resolves the kernel object). The Kernel is responsible for handling the incoming request. Once created, Laravel passes the request to the Kernel, which starts bootstrapping the framework, loading service providers, running middleware, and eventually dispatching the request to the correct route.</em></blockquote><p>The Kernel prepares Laravel by loading:</p><ul><li>Environment variables</li><li>Configuration files</li><li>Exception handling</li><li>Logging</li><li>Facades</li></ul><p>Now Laravel has everything needed to operate correctly.</p><h3>-Register and Boot Service Providers</h3><p>Laravel loads all service providers.</p><p>Their job is to register services, bindings, event listeners, routes, and other framework components.</p><p>At this point, Laravel knows how to resolve dependencies when needed.</p><h3>- Request + Global Middleware</h3><p>Laravel converts the raw HTTP request into a structured Request object.</p><p>Then global middleware runs, such as:</p><ul><li>Maintenance mode checks</li><li>Input cleaning</li><li>CORS / proxy handling</li></ul><p>This ensures every request is safe and standardized before routing.</p><h3>-Route Matching + Route Middleware</h3><p>Laravel matches the request to a route based on URL + HTTP method.</p><p>Once matched, it runs route-specific middleware like:</p><ul><li>Authentication</li><li>Authorization</li><li>Rate limiting</li></ul><p>At this point Laravel knows <em>exactly</em> how to handle the request and who is allowed to proceed.</p><h3>- Controller Execution (Business Logic)</h3><p>Laravel resolves the controller and injects all dependencies from the service container.</p><p>Then the controller executes the actual business logic:</p><ul><li>Database queries</li><li>Services</li><li>External APIs</li><li>Application rules</li></ul><p>This is the core of your application.</p><h3>- Response Creation + Middleware Cleanup</h3><p>The controller returns a response (JSON, HTML, redirect, etc.).</p><p>Laravel then allows middleware to modify the response:</p><ul><li>Add headers</li><li>Store session data</li><li>Attach cookies</li></ul><p>After that, the response is returned to the client.</p><h3>(20) Explain Request Lifecycle in Laravel ?</h3><ul><li>The entry point for all requests to a Laravel application is the <strong>public/index.php</strong> file</li><li>All requests are directed to this file by your <strong>web server</strong> (Apache / Nginx) configuration</li><li>The index.php file loads the Composer generated <strong>autoloader </strong>definition</li><li>Then retrieves an instance of the Laravel application from <strong>bootstrap/app.php</strong></li><li>Next, the incoming request is sent to either the <strong>HTTP kernel</strong> or the <strong>console kernel</strong>, depending on the type of request that is entering the application</li><li>The<strong> HTTP kernel</strong> extends the <em>Illuminate\Foundation\Http\Kernel</em> class, which defines an <strong>array of bootstrappers</strong> that will be run before the request is executed. These bootstrappers configure <strong>error handling</strong>, <strong>configure logging</strong>, detect the <strong>application environment</strong></li><li>The <strong>HTTP kernel</strong> also defines a list of <strong>HTTP middleware</strong> that all requests must pass through before being handled by the application</li><li>Next step of the kernel is to load <strong>service providers</strong> as part of the bootstrapping action. Providers that are needed for the application are placed in <strong>config/app.php</strong> configuration file</li><li>Once the application has been bootstrapped and all service providers have been registered, the Request will be handed off to the router for dispatching. <strong>The router will dispatch the request to a route or controller.</strong></li></ul><h3>Q1: What is the difference between PHP errors and exceptions?</h3><p>Errors are system-level issues generated by the PHP engine, such as warnings or fatal errors, while exceptions are object-oriented constructs used by developers to handle application-level error conditions in a controlled way.</p><h3>Q2: Why are exceptions preferred over traditional error handling?</h3><p>Exceptions provide structured, controllable error flow using try/catch blocks, better debugging through stack traces, and cleaner separation between business logic and error handling compared to traditional PHP error mechanisms.</p><h3>Q3: What happens if an exception is not caught?</h3><p>If an exception is not caught, it will bubble up the call stack and eventually cause a fatal error, terminating script execution unless a global exception handler is defined.</p><h3>Q4: How does PHP 7+ improve error handling?</h3><p>PHP 7+ converts many traditional errors into exceptions or throwable objects, such as TypeError and ParseError, allowing developers to handle them using try/catch blocks consistently.</p><h3>Q5: How does Laravel handle errors internally?</h3><p>Laravel converts most errors into exceptions and manages them through a centralized exception handler (Handler.php), which allows consistent logging, reporting, and response formatting.</p><h3>Q1: What is the Model Context Protocol (MCP)?</h3><p>MCP is an open protocol that standardizes how AI models interact with external tools, services, and data sources. It allows AI systems to discover and use capabilities without requiring custom integrations for every tool.</p><h3>Q2: What problem does MCP solve?</h3><p>MCP solves the integration problem between AI models and external systems. Instead of building custom connectors for every application, developers expose capabilities through a standard protocol that any MCP-compatible AI can use.</p><h3>Q3: How does MCP differ from a traditional API?</h3><p>Traditional APIs are designed for developers and require explicit integration code. MCP adds standardized tool discovery, structured inputs and outputs, and AI-friendly interaction patterns so models can dynamically understand and use available tools.</p><h3>Q4: Why is Laravel a good fit for MCP servers?</h3><p>Laravel already contains business logic, authorization rules, validation, and service layers. Exposing these capabilities through MCP allows AI systems to safely interact with the application without direct database access.</p><h3>Q5: Why should AI interact with Laravel services instead of the database directly?</h3><p>Because Laravel services enforce business rules, validation, permissions, and transactional consistency. Direct database access bypasses these protections and can lead to security or data integrity issues.</p><h3>Q6: How would you explain MCP in one sentence during an interview?</h3><blockquote><em>MCP is a standardized protocol that allows AI models to discover and securely interact with external tools and applications, similar to how HTTP standardized communication between browsers and web servers.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f62ca627126" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mid-Level Backend Laravel Interview Q&A]]></title>
            <link>https://medium.com/@ibrahimamasha7/mid-level-backend-laravel-interview-q-a-2fe636a982d1?source=rss-6ef57e6406c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe636a982d1</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Ibrahim Amasha]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 23:09:11 GMT</pubDate>
            <atom:updated>2026-06-22T16:36:39.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqP9TS-Om5WNe8Fy0Kknmg.png" /></figure><h3>Index</h3><ol><li>Rate Limiting &amp; Brute-Force Protection (Q1–Q6)</li><li>Jobs, Queues &amp; Scheduling (Q1–Q16)</li><li>Events &amp; Listeners (Q1–Q5)</li><li>Eloquent ORM (Q1–Q5)</li><li>APIs, Webhooks &amp; Idempotency (Q1–Q10)</li><li>Databases — SQL vs NoSQL &amp; Data Types (Q1–Q9)</li><li>Database Internals — Indexing, Isolation &amp; Concurrency (Q1–Q18)</li><li>Database Performance &amp; Optimization (Q1–Q11)</li><li>System Design — Scaling, Partitioning &amp; Sharding (Q1–Q11)</li><li>System Design — Multi-Tenancy (Q1–Q6)</li></ol><h3>Section 1: Rate Limiting &amp; Brute-Force Protection</h3><p><strong>Q1: What is the difference between rate limiting and brute-force protection?</strong> Rate limiting is a general mechanism applied to any type of request to control traffic volume, while brute-force protection is specifically focused on authentication endpoints to prevent password guessing attacks. In practice:<br>Rate limiting → API protection , <br>Brute-force protection → login security layer</p><p><strong>Q2: How does Laravel implement rate limiting under the hood?</strong> <br>Laravel uses a cache-driven system where each request increments a counter stored against a unique key (like IP + route). If the counter exceeds the allowed threshold within a time window, Laravel blocks further requests and returns a 429 response. <br>Redis is commonly used in production for accuracy and performance.</p><p><strong>Q3: Why is brute-force protection necessary if we already have rate limiting?</strong> <br>Because attackers often target login endpoints specifically. General rate limiting might allow enough attempts to guess passwords over time, but brute-force protection adds stricter limits , temporary lockouts and progressive delays , This makes password guessing practically infeasible.</p><p><strong>Q4: How can rate limiting be customized in Laravel?</strong> Laravel allows customization using: RateLimiter::for() method custom keys (IP, user ID, API token) dynamic limits (e.g., premium users get higher limits)</p><p>Example idea: Free users: 60 req/min Paid users: 600 req/min</p><p><strong>Q5: What happens when a rate limit is exceeded?</strong> Laravel immediately: stops processing the request returns HTTP 429 Too Many Requests includes retry-after headers so the client knows when to retry</p><p><strong>Q6: Should we use IP or User ID for rate limiting?</strong> It depends on the stage of the request. For unauthenticated traffic, IP-based limiting is necessary because there is no user identity. After authentication, user-based limiting becomes more reliable since it ensures fairness per account. Most production systems use a hybrid approach combining both.</p><h3>Section 2: Jobs, Queues &amp; Scheduling</h3><p><strong>Q1: What is the difference between a Job and a Queue?</strong> A Job is the actual unit of work that defines what should be executed, while a Queue is the system that stores and manages those jobs until a worker processes them. In simple terms: <br>Job = task <br>Queue = waiting system for tasks</p><p><strong>Q2: Why do we use queues instead of executing jobs directly?</strong> Because executing heavy tasks inside the HTTP request slows down the response. Queues move that work to the background, improving response time , scalability , reliability under load .</p><p><strong>Q3: What happens after dispatching a job in Laravel?</strong> When a job is dispatched, Laravel serializes it and pushes it into the configured queue driver (like Redis or database). A queue worker later pulls the job from the queue and executes its handle() method.</p><p><strong>Q4: What is a queue worker?</strong> A queue worker is a long-running process that continuously listens to the queue and processes jobs as they arrive. Without workers, jobs remain in the queue and are never executed.</p><p><strong>Q5: Can jobs exist without queues?</strong> No, jobs always need a queue system to be executed asynchronously. However, Laravel allows synchronous execution using the sync driver, where jobs run immediately instead of being queued once we dispatch it.</p><p><strong>Q6: What happens if a job fails?</strong> Laravel can: retry the job automatically (based on retry settings) move it to a failed jobs table allow manual retry or logging for debugging</p><p><strong>Q7: What is Cron?</strong> Cron is a Linux system service that runs scheduled commands at fixed time intervals. It does not know anything about Laravel or PHP — it only executes OS-level commands based on time rules.</p><p><strong>Q8: What is a Cron Job?</strong> A Cron Job is a single scheduled entry inside Cron. Example:</p><pre>php artisan schedule:run</pre><ul><li>It defines what command runs and when it runs inside the Cron system.</li></ul><p><strong>Q9: What is Laravel Scheduler?</strong> The Laravel Scheduler is a feature that lets you define all scheduled tasks in PHP instead of writing multiple cron jobs. It is triggered by a single cron job:</p><pre>php artisan schedule:run</pre><ul><li>Then Laravel decides internally what should run at that moment.</li></ul><p><strong>Q10: Why is schedule:run executed every minute?</strong> Because Linux Cron only supports minute-level precision.</p><p>So Laravel uses:</p><p>Cron → runs every minute , Scheduler → checks all due tasks each time</p><p>This gives Laravel the finest possible scheduling resolution using Cron.</p><p><strong>Q11: Can Laravel run tasks faster than 1 minute (e.g. every 10 seconds)?</strong> Yes, but not directly via Cron. Laravel simulates sub-minute scheduling by keeping schedule:run active during the minute and executing multiple cycles internally. For more advanced setups, you can use: php artisan schedule:work which runs continuously instead of relying on Cron.</p><p><strong>Q12: What is a Queue in Laravel?</strong> A Queue is a storage system (Redis, database, SQS) that holds jobs waiting to be processed. It acts like a waiting line where tasks are stored until a worker picks them up.</p><p><strong>Q13: What is a Queue Worker?</strong> A Queue Worker is a long-running PHP process started by: php artisan queue:work</p><p>It continuously listens to the queue, pulls jobs, and executes them.</p><p><strong>Q14: What is the difference between Queue and Queue Worker?</strong> Queue → stores jobs (data waiting to be processed) Worker → processes those jobs (execution engine)</p><p><strong>Q15: What does “queue worker is a running process” mean?</strong> It means queue:work starts a persistent PHP CLI process that: stays alive loops continuously checks the queue repeatedly executes jobs when available</p><p>So the worker is literally that running process.</p><p><strong>Q16: Why do we need Supervisor with queue workers?</strong> Because queue workers stop if the process crashes or the terminal closes. Supervisor ensures: workers stay alive , workers restart if they fail , multiple workers can be managed efficiently .</p><h3>Section 3: Events &amp; Listeners</h3><p><strong>Q1: What is the difference between events and listeners?</strong> An event represents something that has happened in the system, while a listener is responsible for reacting to that event and executing the corresponding logic. Events describe the “what happened,” and listeners define “what to do next.”</p><p><strong>Q2: Why do we use events and listeners in Laravel?</strong> They are used to decouple business logic and improve maintainability. Instead of writing multiple actions inside a single controller or service, you can trigger an event and let multiple listeners handle different responsibilities independently.</p><p><strong>Q3: How does Laravel handle events internally?</strong> When an event is dispatched using the event() helper, Laravel looks up all registered listeners in the EventServiceProvider and executes them. These listeners can run synchronously or be pushed to a queue if they implement ShouldQueue.</p><p><strong>Q4: Can listeners run asynchronously?</strong> Yes. If a listener implements ShouldQueue, Laravel will dispatch it to the queue system, and a queue worker will process it in the background instead of running it during the request lifecycle.</p><p><strong>Q5: What are the benefits of using events over direct method calls?</strong> Events reduce coupling between components, make the system more scalable, and allow new features to be added without modifying existing logic. This leads to cleaner and more maintainable architecture.</p><h3>Section 4: Eloquent ORM</h3><p><strong>Q1: How does Eloquent ORM work internally?</strong> Eloquent translates PHP method calls into SQL queries using the Query Builder. It builds the query lazily, executes it only when needed, and then hydrates the raw database results into PHP model objects.</p><p><strong>Q2: What happens when you call a model method like User::where()?</strong> The static call is intercepted by PHP magic methods and resolved into an Eloquent Builder instance. This builder accumulates query constraints until execution methods like get() or first() are called.</p><p><strong>Q3: What is hydration in Eloquent?</strong> Hydration is the process of converting raw database rows into fully functional Eloquent model instances, allowing developers to interact with data using object-oriented syntax instead of arrays.</p><p><strong>Q4: How does Eloquent handle relationships internally?</strong> Relationships are resolved through additional queries or eager loading. Lazy loading triggers a query when the relationship is accessed, while eager loading fetches all related data in advance using optimized queries.</p><p><strong>Q5: Why is Eloquent considered slower than raw SQL?</strong> Eloquent introduces abstraction layers such as query building, hydration, and model instantiation, which add overhead compared to direct SQL queries that return raw results.</p><h3>Section 5: APIs, Webhooks &amp; Idempotency</h3><p><strong>Q1: What is a webhook?</strong> A webhook is an HTTP callback mechanism where external services send real-time data to your application when a specific event occurs, eliminating the need for continuous polling.</p><p><strong>Q2: Why are webhooks preferred over polling?</strong> Because webhooks are event-driven and push data only when needed, making them more efficient, real-time, and less resource-consuming compared to constantly checking for updates via polling.</p><p><strong>Q3: How does a webhook work in a typical system?</strong> The external service stores your webhook URL and sends an HTTP POST request to it whenever an event occurs. Your backend receives the payload, validates it, and processes it accordingly.</p><p><strong>Q4: What are the main security concerns with webhooks?</strong> The main risk is fake or malicious requests. To prevent this, you must verify the webhook signature using a shared secret, ensuring the request genuinely comes from the external provider.</p><p><strong>Q5: Why should webhook processing be asynchronous?</strong> Because webhook requests must respond quickly. Heavy processing (like database updates or external API calls) should be moved to queue jobs to avoid timeouts and retries from the provider.</p><p><strong>Q6: What is idempotency in APIs?</strong> Idempotency means that making the same request multiple times results in the same system state as making it once. It ensures that retries or duplicate requests do not cause unintended side effects like duplicate payments or records.</p><p><strong>Q7: Why is idempotency important in distributed systems?</strong> Because distributed systems are unreliable by nature. Requests can be retried due to timeouts, network failures, or client-side issues. Without idempotency, these retries can lead to duplicate operations such as double payments or repeated data creation.</p><p><strong>Q8: How is idempotency implemented in real systems?</strong> It is commonly implemented using an idempotency key sent with each request. The server stores the result of the first request associated with that key and returns the same result for any repeated requests with the same key.</p><p><strong>Q9: Which HTTP methods are naturally idempotent?</strong> GET, PUT, and DELETE are idempotent because repeating them does not change the final state beyond the first execution. POST is typically not idempotent because it usually creates new resources on each call.</p><p><strong>Q10: Where is idempotency most critical in backend systems?</strong> It is most critical in payment processing, order creation, webhook handling, and any operation where duplicate execution can cause financial or data inconsistencies.</p><h3>Section 6: Databases — SQL vs NoSQL &amp; Data Types</h3><p><strong>Q1: What is the main difference between SQL and NoSQL databases?</strong> SQL databases are structured and use predefined schemas with tables and relationships, while NoSQL databases are flexible and store data in formats like documents, key-value pairs, or graphs without requiring a fixed schema.</p><p><strong>Q2: Why is SQL preferred for transactional systems?</strong> SQL databases provide strong consistency and support ACID transactions, making them ideal for systems where data accuracy and integrity are critical, such as banking or financial applications.</p><p><strong>Q3: Why do NoSQL databases scale better horizontally?</strong> NoSQL systems are designed to distribute data across multiple servers easily without complex joins or rigid schemas, allowing them to handle large-scale traffic and datasets more efficiently.</p><p><strong>Q4: Can SQL and NoSQL be used together?</strong> Yes. Many modern systems use both: SQL for structured transactional data and NoSQL for caching, logs, analytics, or flexible data storage.</p><p><strong>Q5: What is the trade-off between consistency and scalability?</strong> SQL prioritizes strong consistency, ensuring all users see the same data at the same time. NoSQL often prioritizes scalability and availability, sometimes allowing temporary inconsistencies to achieve higher performance.</p><p><strong>Q6: What is structured data?</strong> Data stored in a fixed schema like tables where every row follows the same format.</p><p><strong>Q7: What is semi-structured data?</strong> Data that has partial structure (like JSON) but no fixed schema like SQL tables.</p><p><strong>Q8: What is unstructured data?</strong> Data without any predefined format, such as images, videos, and free text.</p><p><strong>Q9: SQL vs NoSQL in scaling context?</strong> SQL databases usually scale vertically, meaning you increase the power of a single server (CPU, RAM, SSD). This works well because relational data needs strong consistency and joins, but it becomes expensive and has a limit (one machine can only get so big). NoSQL databases are designed to scale horizontally, meaning you add more servers (sharding/partitioning data across machines). This allows them to handle very large traffic and data volumes easily, but often with weaker consistency guarantees compared to SQL. In short: SQL → scale up (vertical), consistency-focused NoSQL → scale out (horizontal), scalability-focused</p><h3>Section 7: Database Internals — Indexing, Isolation &amp; Concurrency</h3><p><strong>Q1: What is a database index?</strong> A database index is a data structure that improves the speed of data retrieval operations by allowing the database to find rows quickly without scanning the entire table.</p><p><strong>Q2: How does indexing improve query performance?</strong> Indexing improves performance by reducing the number of rows the database must scan. Instead of performing a full table scan, the database uses structures like B-trees to directly locate the required data.</p><p><strong>Q3: What are the disadvantages of indexing?</strong> Indexes consume additional storage and slow down write operations such as INSERT, UPDATE, and DELETE because the index must also be updated whenever data changes.</p><p><strong>Q4: When should you avoid using indexes?</strong> You should avoid indexes on small tables, columns with low uniqueness, or in systems with heavy write operations where the overhead of maintaining indexes outweighs the performance benefits.</p><p><strong>Q5: What is a composite index?</strong> A composite index is an index created on multiple columns. It is useful when queries frequently filter or sort data using a combination of those columns.</p><p><strong>Q6: What is the purpose of transaction isolation levels?</strong> Transaction isolation levels control how concurrent transactions interact with each other. Their goal is to prevent data consistency issues while allowing multiple transactions to run at the same time. The higher the isolation level, the fewer consistency problems can occur, but concurrency and performance may decrease.</p><p><strong>Q7: What is a Dirty Read?</strong> A dirty read occurs when a transaction reads data that was modified by another transaction but has not yet been committed. Example: Transaction A updates balance from 1000 → 500 Transaction B reads 500 Transaction A rolls back</p><p>Now the balance is actually 1000, but Transaction B saw an invalid value.</p><p><strong>Q8: What is a Non-Repeatable Read?</strong> A non-repeatable read occurs when the same row is read twice within a transaction and returns different values because another transaction modified and committed the row between the two reads. Example: First read → balance = 1000 Another transaction updates balance to 500 and commits Second read → balance = 500</p><p>Same query, same transaction, different result.</p><p><strong>Q9: What is a Phantom Read?</strong> A phantom read occurs when the same query returns a different set of rows because another transaction inserted or deleted matching rows. Example: First query returns 10 pending orders Another transaction inserts a pending order Second query returns 11 pending orders</p><p>A new row “appeared” during the transaction.</p><p><strong>Q10: What are the database isolation levels and what problems do they solve?</strong> Read Uncommitted Lowest isolation level Allows Dirty Reads, Non-Repeatable Reads, and Phantom Reads</p><p>1-<strong>Read Committed</strong> : Prevents Dirty Reads , but still allows<strong> Non-Repeatable Reads</strong> and <strong>Phantom Reads</strong></p><p>2-<strong>Repeatable Read </strong>: Prevents <strong>Dirty Reads </strong>and<strong> Non-Repeatable Reads</strong> , but May allow<strong> Phantom Reads</strong> (depending on database implementation)</p><p><strong>Serializable : </strong>Highest isolation level , Prevents <strong>Dirty Reads</strong>,<strong> Non-Repeatable Reads</strong>, and <strong>Phantom Reads .</strong></p><p><strong>Q11: Which isolation level is typically used in production?</strong> Most applications use: Read Committed : Common in PostgreSQL , Good balance between consistency and performance .</p><p>Repeatable Read : Default in MySQL , as InnoDB engine Provides stronger consistency by preventing non-repeatable reads .</p><p>Serializable : Reserved for highly critical operations (financial systems, inventory management, etc.) because it provides maximum consistency but reduces concurrency.</p><p><strong>Q12: What is a race condition?</strong> A race condition occurs when multiple processes or transactions access and modify the same data concurrently, causing unpredictable or incorrect results because the final outcome depends on execution timing.</p><p><strong>Q13: What problems can race conditions cause in real systems?</strong> Race conditions can lead to duplicate payments, oversold inventory, inconsistent balances, duplicate order creation, and general data corruption when concurrent requests modify the same data.</p><p><strong>Q14: What is pessimistic locking?</strong> Pessimistic locking assumes conflicts are likely and locks the data before modification. Other transactions must wait until the current transaction finishes, ensuring only one transaction can modify the data at a time.</p><p><strong>Q15: What is optimistic locking?</strong> Optimistic locking assumes conflicts are uncommon. Instead of locking data, it checks whether the data changed before committing an update, typically using a version number or timestamp.</p><p><strong>Q16: What is an atomic operation and how does it help?</strong> An atomic operation is executed as a single indivisible action by the database. Operations like increment() and decrement() help avoid race conditions because the read-and-update process happens in one database operation.</p><p><strong>Q17: When should we use distributed locks?</strong> Distributed locks are needed when multiple application servers may process the same resource concurrently. They ensure that only one server can execute a critical operation at a time, even across a distributed system.</p><p><strong>Q18: How do idempotency and locking differ?</strong> Locking prevents multiple processes from executing the same critical section simultaneously, while idempotency ensures that repeated requests produce the same result. In payment systems, both are often used together for maximum safety.</p><h3>Section 8: Database Performance &amp; Optimization</h3><p><strong>Q1: What problem do read replicas solve?</strong> They reduce load on the primary database by offloading read queries to replica databases.</p><p><strong>Q2: What is a replica?</strong> A database that maintains a copy of the primary database through replication.</p><p><strong>Q3: Why are writes sent only to the primary?</strong> To maintain a single source of truth and avoid data consistency issues.</p><p><strong>Q4: What is replication lag?</strong> The delay between a write being committed on the primary and appearing on replicas.</p><p><strong>Q5: When are read replicas useful?</strong> In read-heavy systems where SELECT queries greatly outnumber writes, such as e-commerce sites, dashboards, news sites, and social media feeds.</p><p><strong>Q6: What is the first thing you should do when a database becomes slow?</strong> Start by identifying slow queries using profiling tools, query logs, or EXPLAIN. Optimization should be data-driven; you should understand the bottleneck before applying solutions.</p><p><strong>Q7: Why is indexing usually the most effective optimization?</strong> Because it allows the database to locate rows efficiently instead of scanning entire tables. A well-designed index can reduce query execution time from seconds to milliseconds.</p><p><strong>Q8: When should caching be used instead of querying the database?</strong> Caching should be used for frequently accessed data that changes infrequently, such as settings, product catalogs, permissions, or dashboard statistics. It reduces database load and improves response times.</p><p><strong>Q9: What is the difference between read replicas and sharding?</strong> Read replicas duplicate the same data across multiple servers to distribute read traffic, while sharding splits the data itself across different databases to distribute both storage and workload.</p><p><strong>Q10: When should partitioning or sharding be considered?</strong> Only after simpler optimizations such as indexing, query tuning, eager loading, and caching have been exhausted. They add significant complexity and are typically reserved for very large-scale systems.</p><p><strong>Q11: If an interviewer asks, “How would you optimize a slow Laravel application?”, what is a good answer?</strong> A structured answer is: Identify slow queries using logs and profiling. Add or improve indexes. Fix N+1 problems with eager loading. Reduce unnecessary queries and selected columns. Introduce caching where appropriate. Consider read replicas for heavy read traffic. Move heavy processing to queues. Use partitioning or sharding only if the scale requires it.</p><h3>Section 9: System Design — Scaling, Partitioning &amp; Sharding</h3><p><strong>Q1: What is the difference between horizontal and vertical scaling?</strong> Vertical scaling improves a system by upgrading the resources of a single machine, while horizontal scaling improves capacity by adding more machines to distribute the load.</p><p><strong>Q2: Why is horizontal scaling preferred in modern systems?</strong> Because it provides better fault tolerance and virtually unlimited scalability. If one server fails, others continue handling traffic, making the system more reliable and resilient.</p><p><strong>Q3: What are the limitations of vertical scaling?</strong> Vertical scaling is limited by hardware capacity. You can only upgrade a machine up to a certain point, and it also introduces a single point of failure since everything runs on one server.</p><p><strong>Q4: What is a load balancer in horizontal scaling?</strong> A load balancer distributes incoming traffic across multiple servers to ensure no single server is overloaded and to improve system reliability and performance.</p><p><strong>Q5: Can we combine both scaling approaches?</strong> Yes. Many systems start with vertical scaling and later adopt horizontal scaling as traffic grows, often using both together to optimize performance and cost.</p><p><strong>Q6: What is the difference between partitioning and sharding?</strong> Partitioning divides data into smaller logical segments inside a single database, while sharding distributes data across multiple databases or servers to scale horizontally. Example: Partitioning → one MySQL database splits orders table by date Sharding → users 1–1M in DB1, users 1M–2M in DB2</p><p><strong>Q7: Why do we use partitioning in databases?</strong> Partitioning improves query performance by reducing the amount of data scanned while keeping everything in one database system. Example: An orders table is partitioned by year: 2023 orders → Partition A 2024 orders → Partition B</p><p>So querying 2024 data doesn’t scan all historical data.</p><p><strong>Q8: What is the main purpose of sharding?</strong> Sharding is used to scale databases horizontally by distributing data across multiple servers. Example: A social app: Shard 1 → users with id 1–1M Shard 2 → users with id 1M–2M</p><p>A routing layer decides which shard to query.</p><p><strong>Q9: What are the types of partitioning and sharding?</strong> Partitioning types: Range partitioning Example: orders split by date (Jan–Jun, Jul–Dec)</p><p>Hash partitioning Example: user_id % 4 → decides partition</p><p>List partitioning Example: users grouped by country (Egypt, USA, UAE)</p><p>Sharding types: Horizontal sharding Example: users split by ID ranges across servers</p><p>Vertical sharding Example: DB1 → user accounts DB2 → payments data</p><p>Directory-based sharding Example: A lookup service says user 123 → shard 2</p><p><strong>Q10: What are the challenges of sharding?</strong> Sharding adds complexity in: Routing requests to correct shard Cross-shard queries Data consistency Rebalancing shards when scaling</p><p>Example: Fetching a user feed might require querying multiple shards if posts are distributed.</p><p><strong>Q11: Can partitioning and sharding be used together?</strong> Yes. They are often combined in large systems. Example: Sharding → users split across multiple databases Partitioning → each shard splits orders table by month internally</p><p>So: First level: routing decides shard Second level: database engine selects partition</p><h3>Section 10: System Design — Multi-Tenancy</h3><p><strong>Q1: What is multi-tenancy in SaaS architecture?</strong> Multi-tenancy is a software architecture where a single application instance serves multiple customers (tenants), while keeping each tenant’s data logically or physically isolated.</p><p><strong>Q2: What are the main types of multi-tenancy?</strong> There are three main types: Shared database with tenant_id (logical isolation) Separate schema per tenant Separate database per tenant (strong isolation)</p><p>Each approach balances cost, scalability, and isolation differently.</p><p><strong>Q3: How does subdomain-based multi-tenancy work?</strong> Each tenant is assigned a unique subdomain. The system uses middleware to extract the subdomain from the request, identify the tenant, and load the corresponding configuration or database before processing the request.</p><p><strong>Q4: What is the role of middleware in multi-tenancy?</strong> Middleware is responsible for resolving the tenant from the request (usually via subdomain or domain) and setting the tenant context before the request reaches controllers or services. It ensures all subsequent operations are tenant-aware.</p><p><strong>Q5: How do SaaS applications isolate tenant data?</strong> They isolate data using techniques like tenant_id filtering in shared databases, separate schemas, or completely separate databases. Middleware ensures the correct tenant context is applied during each request.</p><p><strong>Q6: What is the difference between logical and physical isolation?</strong> Logical isolation uses a shared database with tenant identifiers, while physical isolation uses separate databases per tenant. Physical isolation provides stronger security and scalability but comes with higher infrastructure cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe636a982d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Robust Backup and Restore System in Laravel]]></title>
            <link>https://medium.com/@ibrahimamasha7/building-a-robust-backup-and-restore-system-in-laravel-cafdface95a4?source=rss-6ef57e6406c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cafdface95a4</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[backup]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ibrahim Amasha]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 09:29:09 GMT</pubDate>
            <atom:updated>2024-11-23T09:29:09.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zWxSG0tDGgcONPOam03gw.png" /></figure><p>In today’s digital age, ensuring the safety and availability of data is crucial for any application. Backups serve as a safety net against accidental data loss, malicious attacks, or hardware failures. A reliable backup system is not just about preserving database records but also other essential files such as user-uploaded content. Here, we’ll explore the importance of having a backup and restore system, learn from a notable incident, and explain how we implemented a robust solution in a Laravel application.</p><h3>Why Backup Systems Are Crucial</h3><p>Imagine losing years of data because of a technical oversight or unforeseen incident. The infamous GitLab database incident of 2017 serves as a cautionary tale. During maintenance, GitLab accidentally deleted their production database, leading to significant downtime and data loss. Although GitLab had backups, multiple issues in their recovery strategy compounded the problem, making restoration efforts much harder. This incident underscores the importance of not just creating backups but ensuring they are easy to restore and properly tested.</p><p>A comprehensive backup system ensures:</p><ul><li><strong>Data Protection:</strong> Safeguards against accidental deletion, corruption, or attacks.</li><li><strong>Business Continuity:</strong> Minimizes downtime and enables quick recovery during crises.</li><li><strong>User Trust:</strong> Demonstrates a commitment to securing user data, building confidence in your platform.</li></ul><h3>Our Laravel Backup Solution</h3><p>To address the challenges of data loss, we developed a Laravel-based backup and restore system that handles both the <strong>database</strong> and critical <strong>files</strong> such as those in the public/uploads folder, where user-uploaded content typically resides. This approach is not limited to the database alone but extends to any other essential directory in your Laravel project.</p><p>Here’s how we implemented the solution using three main functions: createBackup, download, and restore.</p><h3>1. Creating Backups :</h3><p>In the createBackup function, we leveraged the popular <strong>Spatie Backup</strong> package to create database dumps efficiently. This package simplifies the process of backing up databases and can be extended to include file backups.</p><p><strong>Install the package</strong><br>Run the following command to install the Spatie Backup package via Composer:</p><pre>composer require spatie/laravel-backup</pre><p><strong>Publish the configuration file</strong><br>Use the command below to publish the package’s configuration file to config/backup.php:</p><pre>php artisan vendor:publish --provider=&quot;Spatie\Backup\BackupServiceProvider&quot;</pre><p><strong>Configure additional directories</strong><br>To include additional directories such as public/uploads in your backup, modify the config/backup.php file. Under the include section, add your target folder:</p><pre>    &#39;include&#39; =&gt; [<br>         (&#39;uploads&#39;), // which is at public/uploads <br>     ],</pre><p>Additionally, we created a Backup model and its corresponding database table to store metadata about each backup, including its file name and type. This allows us to manage and track backups from the application.</p><p>After generating the database dump using Spatie, we used PHP’s ZipArchive class to create a ZIP file. The ZIP file includes both the database dump and the contents of the public/uploads directory, ensuring a comprehensive backup of user data.</p><p>code overview:</p><pre>use Log;<br>use ZipArchive;<br>use App\Models\Backup;<br><br>public function createBackup()<br>{<br>    try {<br>        Log::info(&#39;starting the backup process&#39;);<br><br>        // run the backup command using Spatie<br>        Artisan::call(&#39;backup:run&#39;);<br>        $outputDb = Artisan::output();<br>        Log::info(&#39;database backup output: &#39; . $outputDb);<br><br>        // locate backup files<br>        $backupPath = storage_path(&#39;app/&#39; . config(&#39;app.name&#39;));<br>        $files = File::files($backupPath);<br><br>        if (!empty($files)) {<br>            // find the most recent backup file<br>            $mostRecentFile = collect($files)-&gt;sortByDesc(fn($file) =&gt; $file-&gt;getMTime())-&gt;first();<br><br>            // save metadata to the database<br>            Backup::create([&#39;file_path&#39; =&gt; $mostRecentFile-&gt;getFilename(), &#39;type&#39; =&gt; &#39;files&#39;]);<br><br>            // create a ZIP file<br>            $zipFileName = &#39;backup-&#39; . now()-&gt;format(&#39;Y-m-d-H-i-s&#39;) . &#39;.zip&#39;;<br>            $zipFilePath = storage_path(&quot;app/$zipFileName&quot;);<br>            $zip = new \ZipArchive;<br><br>            if ($zip-&gt;open($zipFilePath, \ZipArchive::CREATE) === true) {<br>                // add the uploads folder<br>                $zip-&gt;addFile($mostRecentFile-&gt;getRealPath(), &#39;uploads/&#39; . basename($mostRecentFile-&gt;getRealPath()));<br><br>                // add the database dump<br>                $dbBackupFile = $backupPath . &#39;/db-backup.sql&#39;;<br>                if (File::exists($dbBackupFile)) {<br>                    $zip-&gt;addFile($dbBackupFile, basename($dbBackupFile));<br>                }<br><br>                $zip-&gt;close();<br>                Log::info(&#39;ZIP file created: &#39; . $zipFilePath);<br><br>                return redirect()-&gt;back()-&gt;with(&#39;success&#39;, &#39;Backup created successfully.&#39;);<br>            }<br>        }<br><br>        Log::warning(&#39;no backup files found&#39;);<br>    } catch (\Exception $e) {<br>        Log::error(&#39;backup creation failed: &#39; . $e-&gt;getMessage());<br>    }<br>}</pre><h3>2.Downloading Backups :</h3><p>The download function allows administrators to download a previously created backup file directly from the server. This is especially useful for storing backups on external storage or transferring them to another environment.</p><p>The function retrieves the backup metadata from the database, constructs the file path, and ensures the file exists before offering it for download. If the file is missing, an error message is displayed to the user.</p><h4>Code Overview:</h4><pre>public function download($id)<br>{<br>    try {<br>        // fetch backup metadata<br>        $backup = Backup::findOrFail($id);<br><br>        // construct the full path to the backup file<br>        $backupPath = storage_path(&#39;app/&#39; . config(&#39;app.name&#39;) . &#39;/&#39; . $backup-&gt;file_path);<br><br>        // check if the file exists<br>        if (File::exists($backupPath)) {<br>            return response()-&gt;download($backupPath);<br>        }<br><br>        return redirect()-&gt;back()-&gt;with(&#39;error&#39;, &#39;Backup file not found.&#39;);<br>    } catch (\Exception $e) {<br>        Log::error(&#39;failed to download backup: &#39; . $e-&gt;getMessage());<br>        return redirect()-&gt;back()-&gt;with(&#39;error&#39;, &#39;An error occurred while trying to download the backup.&#39;);<br>    }<br>}</pre><h3>3. Restoring Backups :</h3><p>Unlike the backup process, which utilizes the Spatie package, the restore function was implemented natively without relying on external packages. This was done to have precise control over the restoration process, which includes extracting files and restoring the database dump.</p><p>The function retrieves the specified backup file from the Backup model. It then extracts its contents into a temporary directory, restoring both the database and the contents of the uploads folder.</p><p>code overview:</p><pre>public function restore($backupId)<br>{<br>    try {<br>        Log::info(&quot;starting restore process for backup ID: $backupId&quot;);<br><br>        // fetch backup metadata<br>        $backup = Backup::findOrFail($backupId);<br>        $backupPath = storage_path(&#39;app/&#39; . config(&#39;app.name&#39;));<br>        $backupFile = $backupPath . &#39;/&#39; . $backup-&gt;file_path;<br><br>        if (File::exists($backupFile)) {<br>            // extract the ZIP file<br>            $tempRestorePath = storage_path(&#39;app/restore-temp&#39;);<br>            File::ensureDirectoryExists($tempRestorePath);<br>            $zip = new \ZipArchive;<br><br>            if ($zip-&gt;open($backupFile) === true) {<br>                $zip-&gt;extractTo($tempRestorePath);<br>                $zip-&gt;close();<br><br>                // restore database<br>                $dbDumpFile = $tempRestorePath . &#39;/db-dumps/mysql-&#39; . env(&#39;DB_DATABASE&#39;) . &#39;.sql&#39;;<br>                if (File::exists($dbDumpFile)) {<br>                    $command = sprintf(<br>                        &#39;mysql -u%s -p%s %s &lt; %s&#39;,<br>                        env(&#39;DB_USERNAME&#39;),<br>                        env(&#39;DB_PASSWORD&#39;),<br>                        env(&#39;DB_DATABASE&#39;),<br>                        escapeshellarg($dbDumpFile)<br>                    );<br>                    exec($command);<br>                    Log::info(&quot;database restored successfully from $dbDumpFile&quot;);<br>                }<br><br>                // restore uploads folder<br>                $uploadsBackupPath = $tempRestorePath . &#39;/uploads&#39;;<br>                if (File::exists($uploadsBackupPath)) {<br>                    File::copyDirectory($uploadsBackupPath, public_path(&#39;uploads&#39;));<br>                    Log::info(&quot;uploads restored to: &quot; . public_path(&#39;uploads&#39;));<br>                }<br><br>                // clean up temporary files<br>                File::deleteDirectory($tempRestorePath);<br><br>                return redirect()-&gt;back()-&gt;with(&#39;success&#39;, &#39;Backup restored successfully.&#39;);<br>            }<br>        }<br>    } catch (\Exception $e) {<br>        Log::error(&#39;restore process failed: &#39; . $e-&gt;getMessage());<br>    }<br>}</pre><h3>Conclusion</h3><p>Implementing a reliable backup and restore system is crucial for safeguarding data and assets in a Laravel application. By combining Spatie Backup for creating backups and a custom restoration approach, we ensured flexibility and control over the process.</p><p>Additionally, this system can be tailored to meet your specific requirements, allowing you to schedule backups on a daily, weekly, or monthly basis. This adaptability ensures your application remains protected against potential data loss, regardless of your operational needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cafdface95a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating PDFs in Laravel: A Guide to Use TCPDF for Arabic Text]]></title>
            <link>https://medium.com/@ibrahimamasha7/generating-pdfs-in-laravel-a-guide-to-using-tcpdf-for-arabic-text-201c432bdf1a?source=rss-6ef57e6406c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/201c432bdf1a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tcpdf]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Ibrahim Amasha]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 23:47:26 GMT</pubDate>
            <atom:updated>2024-09-27T00:08:27.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Xaz0x_Y3AfTFwwLoGY1tw.png" /></figure><p>In web development, generating PDF documents is a frequent requirement, especially for reports, invoices, and documents that need to support multiple languages. For Laravel developers, there are many libraries to choose from, but when it comes to handling Arabic text, things get a bit tricky.</p><p>After testing several options , I found that TCPDF stands out as the best choice. Here is why :</p><ul><li><strong>Supports Arabic and RTL Languages:</strong> TCPDF stands out for its robust support of Arabic and other right-to-left languages, ensuring accurate text rendering.</li><li><strong>Custom Font Usage:</strong> Easily integrate any font you need into your PDF documents.</li><li><strong>Text and Image Insertion:</strong> Seamlessly insert both text and images into your PDFs.</li><li><strong>Bi-directional Text Handling:</strong> Effectively manages mixed text, supporting both Arabic and English, ensuring that your content displays correctly regardless of language.</li><li><strong>Customizable Layout:</strong> Override functions to customize headers and footers, giving you complete control over the document layout.</li></ul><p>In this tutorial, I’ll show you how to integrate TCPDF into your Laravel project, with a focus on supporting Arabic content. Let’s get started!</p><p>First , install TCPDF in your Laravel project :</p><pre>composer require tecnickcom/tcpdf</pre><p><strong>Create the View</strong> (resources/views/my-pdf.blade.php):</p><pre>&lt;!-- resources/views/my-pdf.blade.php --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Test PDF Report&lt;/title&gt;<br>    &lt;style&gt;<br>        .header {<br>            text-align: center;<br>            font-size: 24px;<br>            font-weight: bold;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    @php<br>        // Sample mixed text fetched from the database<br>        // Function to render text segments with appropriate direction<br>        function renderMixedText($text)<br>        {<br>            $segments = preg_split(&#39;/(\s*-\s*)/&#39;, $text); // Split by hyphen or other delimiter<br>            return collect($segments)<br>                -&gt;map(function ($segment) {<br>                    $trimmed = trim($segment);<br>                    if (preg_match(&#39;/[\x{0600}-\x{06FF}]/u&#39;, $trimmed)) {<br>                        return &quot;&lt;span dir=&#39;rtl&#39;&gt;$trimmed&lt;/span&gt;&quot;; // Arabic text<br>                    }<br>                    return &quot;&lt;span class=&#39;english-text&#39;&gt;$trimmed&lt;/span&gt;&quot;; // English text<br>                })<br>                -&gt;implode(&#39; &#39;); // Join segments back into a single string<br>        }<br>    @endphp<br>    &lt;div class=&quot;header&quot;&gt; pdf جديد &lt;/div&gt;<br>    &lt;div class=&quot;section&quot;&gt;<br>        &lt;div class=&quot;content&quot;&gt;<br>            @php<br>                $mixedText = &#39;مرحبا بكم في التقرير - This PDF Includes Mixed Arabic And English text&#39;;<br>            @endphp<br>            {!! renderMixedText($mixedText) !!}<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;image&quot;&gt;<br>        &lt;img src=&quot;{{ public_path(&#39;laravel.png&#39;) }}&quot; alt=&quot;Sample Image&quot;&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now create your controller :</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use TCPDF;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\View;<br><br><br>class MyPDF extends TCPDF<br>{<br>    private $isFirstPage = true;<br><br>    // Page header<br>    public function Header()<br>    {<br>    }<br><br>    // Page footer<br>    public function Footer()<br>    {<br>        // Set font for footer<br>        $this-&gt;SetFont(&#39;helvetica&#39;, &#39;&#39;, 10);<br><br>        // Set the image details<br>        $logoFileName = public_path(&#39;images/footer.jpg&#39;);<br>        $logoWidth = 220; // Width of the image in mm<br>        $logoHeight = 40; // Height of the image in mm<br><br>        // Create HTML for the footer logo<br>        $footer_logo_html = &#39;&lt;img src=&quot;&#39; . $logoFileName . &#39;&quot; width=&quot;&#39; . $logoWidth . &#39;mm&quot; height=&quot;&#39; . $logoHeight . &#39;mm&quot; /&gt;&#39;;<br><br>        // Calculate X position for the cell<br>        $pageWidth = $this-&gt;w;<br>        $imageX = ($pageWidth - $logoWidth) / 2; // Center horizontally<br><br>        // Set Y position to a fixed value from the bottom of the page<br>        $footerY = 10; // Distance from the bottom of the page (in mm)<br><br>        // Set Y position for the footer<br>        $this-&gt;SetY(-$footerY - $logoHeight + 12); // Adjust this to place the image at the bottom<br><br>        // Use writeHTMLCell to position the footer logo<br>        $this-&gt;writeHTMLCell($logoWidth, $logoHeight, $imageX, $this-&gt;GetY(), $footer_logo_html, 0, 1, false, true, &#39;L&#39;, false);<br><br>        // Set position for the page number<br>        $this-&gt;SetY(-$footerY); // Position for the page number just above the footer logo<br><br>        // Page number<br>        $this-&gt;Cell(0, 10,   $this-&gt;getAliasNumPage() . &#39;/&#39; . $this-&gt;getAliasNbPages(), 0, 0, &#39;C&#39;);<br>    }<br>}<br><br>class PdfController extends Controller<br>{<br><br>    public function generateStaticPDF()<br>    {<br>        // Create new PDF document using a custom TCPDF class to override header and footer<br>        $pdf = new class(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, &#39;UTF-8&#39;, false) extends \TCPDF<br>        {<br>            // Override Header method<br>            public function Header()<br>            {<br>                // Logo<br>                $image_file = public_path(&#39;images/sample-logo.png&#39;); // Your logo path<br>                $this-&gt;Image($image_file, 10, 10, 30, &#39;&#39;, &#39;PNG&#39;, &#39;&#39;, &#39;T&#39;, false, 300, &#39;&#39;, false, false, 0, false, false, false);<br><br>                // Set font for header<br>                $this-&gt;SetFont(&#39;helvetica&#39;, &#39;B&#39;, 12);<br><br>                // Title<br>                $this-&gt;Cell(0, 15, &#39;Test Report Header - Custom Header&#39;, 0, false, &#39;C&#39;, 0, &#39;&#39;, 0, false, &#39;M&#39;, &#39;M&#39;);<br>            }<br><br>            // Override Footer method<br>            public function Footer()<br>            {<br>                // Position at 15 mm from bottom<br>                $this-&gt;SetY(-15);<br><br>                // Set font for footer<br>                $this-&gt;SetFont(&#39;helvetica&#39;, &#39;I&#39;, 8);<br><br>                // Page number<br>                $this-&gt;Cell(0, 10, &#39;Page &#39; . $this-&gt;getAliasNumPage() . &#39; of &#39; . $this-&gt;getAliasNbPages(), 0, false, &#39;C&#39;, 0, &#39;&#39;, 0, false, &#39;T&#39;, &#39;M&#39;);<br>            }<br>        };<br><br>        // Set document information<br>        $pdf-&gt;SetCreator(PDF_CREATOR);<br>        $pdf-&gt;SetAuthor(&#39;Test Author&#39;);<br>        $pdf-&gt;SetTitle(&#39;Test PDF Report&#39;);<br>        $pdf-&gt;SetSubject(&#39;Test PDF with Mixed Content&#39;);<br>        $pdf-&gt;SetKeywords(&#39;TCPDF, PDF, test, report, tutorial&#39;);<br><br>        // Set margins<br>        $pdf-&gt;SetMargins(10, 30, 10); // Top margin is increased to allow space for the header<br>        $pdf-&gt;SetHeaderMargin(10); // Header margin<br>        $pdf-&gt;SetFooterMargin(15); // Footer margin<br><br>        // Set auto page breaks<br>        $pdf-&gt;SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);<br><br>        // Set image scale factor<br>        $pdf-&gt;setImageScale(PDF_IMAGE_SCALE_RATIO);<br><br>        // Set the font for Arabic content<br>        $pdf-&gt;SetFont(&#39;dejavusans&#39;, &#39;&#39;, 12);<br><br>        // Set RTL for Arabic content<br>        $pdf-&gt;setRTL(true);<br><br>        // Add a page<br>        $pdf-&gt;AddPage();<br><br>        // Render the Blade view to HTML<br>        $html = view(&#39;my-pdf&#39;)-&gt;render();<br><br>        // Output the HTML content into the PDF<br>        $pdf-&gt;writeHTML($html, true, false, true, false, &#39;&#39;);<br><br>        // Output the PDF for download<br>        $pdf-&gt;Output(&#39;test_report.pdf&#39;, &#39;D&#39;); // &#39;D&#39; means force download<br>    }<br>}</pre><p>Don’t forget to add your route :</p><pre>Route::get(&#39;/generate-pdf&#39;, [PdfController::class, &#39;generateStaticPDF&#39;]);</pre><p>now when you head to ‘generate-pdf ’ url in your browser , you will get this result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*7MdGmL3oScWzhs8is8PJug.png" /></figure><h3>Usage of the renderMixedText Function</h3><p>The renderMixedText function is designed to handle text that may contain both Arabic and English segments. It splits the input text by hyphens or other delimiters, determines the language of each segment, and applies appropriate formatting for display.</p><p><strong>When to Use:</strong></p><ul><li>If you’re dealing with static Arabic or English-only text, there’s no need to pass it to this function; you can display it directly.</li><li>However, if you’re unsure whether the text is mixed (e.g., when retrieving data from a database), using this function ensures that the text is rendered correctly. It will automatically detect the language and apply the appropriate text direction for optimal readability.</li></ul><p>By utilizing renderMixedText, you can confidently handle any text input, ensuring it displays perfectly in your application.</p><h3>Setting a Specific Arabic Font in Your Blade Template</h3><p>The last step remaining is to use a specific Arabic font throughout your Blade template. The fonts are stored in the following directory:</p><pre>vendor\tecnickcom\tcpdf\fonts</pre><p>To specify the font you want in your PDF, use the following line of code as we did in the controller :</p><pre>$pdf-&gt;SetFont(&#39;dejavusans&#39;, &#39;&#39;, 12);</pre><p>Note that the font name, &quot;dejavusans&quot;, must be included in the aforementioned folder.</p><p><strong>Here’s how to add your custom font:</strong></p><ol><li><strong>Download the Font:</strong> Find and download the desired font in TTF format from any source.</li></ol><p><strong>2- Use the TTF to TCPDF Converter:</strong> Visit the following website to convert your TTF file: <a href="https://fonts.palettize.me/">TTF to TCPDF Converter</a>. This tool will provide you with the necessary files to add to your fonts folder.</p><p><strong>3-Add the Font Name in Your Code:</strong> After adding the converted font files to the fonts directory, you can include the font name in your PDF generation code inside the controller.</p><p>By following these steps, you can ensure that your PDF documents display in the specific Arabic font of your choice.</p><ol><li><strong>Add the Font Name in Your Code:</strong> After adding the converted font files to the fonts directory, you can include the font name in your PDF generation code.</li></ol><p>By following these steps, you can ensure that your PDF documents display in the specific Arabic font of your choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=201c432bdf1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Follower/Followee Logic in Laravel]]></title>
            <link>https://medium.com/@ibrahimamasha7/understanding-follower-followee-logic-in-laravel-ce398b72dd10?source=rss-6ef57e6406c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce398b72dd10</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Ibrahim Amasha]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 01:28:57 GMT</pubDate>
            <atom:updated>2024-03-15T01:28:57.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xqoEHjCQ9qwyuppsDCyrw.png" /></figure><p>In social networking platforms and applications, users often engage in interactions where they can follow other users to receive updates or notifications about their activities. In Laravel, managing these follower-followee relationships involves understanding the underlying database structure, defining appropriate models and relationships, and implementing the necessary logic to facilitate user interactions.</p><h3>Understanding the Relationship:</h3><p>The relationship between users in this scenario is typically a one-to-many relationship, where the user can have multiple followers (the followers of the user) and the user can also follow many other users (the followees of the user ). This implies that a user can be associated with multiple followers and follow multiple other users.</p><h3>The Unusual Need for an Intermediate Table:</h3><p>In a typical one-to-many relationship, an intermediate table isn’t required. However, for followers and followees, a bidirectional relationship arises where users can follow and be followed by others. This complexity necessitates an intermediate table, such as “user_relationships,” to accurately represent these many-to-many connections between users.</p><p>The “user_relationships” table stores pairs of user IDs, indicating who follows whom. For instance, a row in this table might store the IDs of a user who follows another user. This structure allows for efficient tracking of followers and followees.</p><p>let’s take a look of the table structure :</p><pre>Schema::create(&#39;user_relationships&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;foreignId(&#39;follower_id&#39;)-&gt;constrained(&#39;users&#39;)-&gt;onDelete(&#39;cascade&#39;);<br>    $table-&gt;foreignId(&#39;followee_id&#39;)-&gt;constrained(&#39;users&#39;)-&gt;onDelete(&#39;cascade&#39;);<br><br>    // ensure that each user can follow another user only once<br>    $table-&gt;unique([&#39;follower_id&#39;, &#39;followee_id&#39;]);<br>    $table-&gt;timestamps();<br>});</pre><p>The unique([&#39;follower_id&#39;, &#39;followee_id&#39;]) constraint ensures that each user can follow another user only once. It prevents duplicate entries in the &quot;user_relationships&quot; table, where each row represents a follower-followee relationship.</p><h3>Implementing the Solution:</h3><p>Now that we’ve defined the structure of the “user_relationships” table, let’s dive into the implementation of models to interact with this table and manage follower-followee relationships.</p><h3>User Model:</h3><p>In the User model, we define methods to retrieve followers and followees using the “hasMany” relationship. These methods allow us to access the related records stored in the “user_relationships” table without needing a separate model for the intermediate table.</p><pre>class User extends Model<br>{<br>    // define relationship with UserRelationship model for followers<br><br>    public function followers()<br>    {<br>        return $this-&gt;hasMany(UserRelationship::class, &#39;followee_id&#39;);<br>    }<br><br>    // define relationship with UserRelationship model for followees<br><br>    public function followees()<br>    {<br>        return $this-&gt;hasMany(UserRelationship::class, &#39;follower_id&#39;);<br>    }<br>}</pre><p>In the User model, the followers() method returns a collection of records representing users who follow the current user, while the followees() method returns a collection of records representing users whom the current user follows.</p><h3>UserRelationship Model:</h3><p>In the UserRelationship model, we define methods to associate users with follower or followee records using the “belongsTo” relationship. These methods allow us to establish the connection between users and their followers or followees.</p><pre> class UserRelationship extends Model<br>{<br>     public function follower()<br>    {<br>        return $this-&gt;belongsTo(User::class, &#39;follower_id&#39;);<br>    }<br><br>     public function followee()<br>    {<br>        return $this-&gt;belongsTo(User::class, &#39;followee_id&#39;);<br>    }<br>}</pre><h3>API Controller:</h3><p>Now that we have our models and relationships defined, let’s implement an API controller to handle requests related to follower-followee interactions. We’ll focus on endpoints to retrieve followers and followees for a given user.</p><pre>namespace App\Http\Controllers\API;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\User;<br><br>class UserRelationshipController extends Controller<br>{<br>    // retrieve followers of a given user<br>    public function followers($userId)<br>    {<br>        $user = User::findOrFail($userId);<br>        $followers = $user-&gt;followers()-&gt;with(&#39;follower&#39;)-&gt;get();<br><br>        return response()-&gt;json($followers);<br>    }<br><br>    // retrieve followees of a given user<br>    public function followees($userId)<br>    {<br>        $user = User::findOrFail($userId);<br>        $followees = $user-&gt;followees()-&gt;with(&#39;followee&#39;)-&gt;get();<br><br>        return response()-&gt;json($followees);<br>    }<br>}</pre><h3>Routes:</h3><p>Don’t forget to define routes for these endpoints in your routes/api.php file:</p><pre>Route::get(&#39;users/{userId}/followers&#39;, &#39;API\UserRelationshipController@followers&#39;);<br>Route::get(&#39;users/{userId}/followees&#39;, &#39;API\UserRelationshipController@followees&#39;);</pre><h3>Conclusion :</h3><p>Now, users can effortlessly fetch details about their followers and followees via our API endpoints. Utilizing Laravel’s robust features, we’ve streamlined the process, ensuring efficient management of social network connections. This setup ensures smooth integration with frontend applications, enhancing the user experience in managing follower-followee interactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce398b72dd10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>