<?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 Kanishka Perera on Medium]]></title>
        <description><![CDATA[Stories by Kanishka Perera on Medium]]></description>
        <link>https://medium.com/@kanishkanuwanperera?source=rss-3b73ede655f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Rp3RIp6tACahkIXO</url>
            <title>Stories by Kanishka Perera on Medium</title>
            <link>https://medium.com/@kanishkanuwanperera?source=rss-3b73ede655f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:44:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kanishkanuwanperera/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[Understanding “fatal: refusing to merge unrelated histories” in Git-and How to Fix It]]></title>
            <link>https://medium.com/@kanishkanuwanperera/understanding-fatal-refusing-to-merge-unrelated-histories-in-git-and-how-to-fix-it-002b57d334b7?source=rss-3b73ede655f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/002b57d334b7</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kanishka Perera]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 15:18:03 GMT</pubDate>
            <atom:updated>2025-10-28T15:18:03.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m90-iO3I4dI6NAL--Xs6hg.png" /></figure><blockquote>If you’ve ever tried to push or pull from a remote Git repository and encountered this dreaded message:<br><strong><em>fatal: refusing to merge unrelated histories</em></strong></blockquote><p>you’re not alone. This error is surprisingly common-especially when working with Bitbucket, GitHub, or any shared project-and it usually confuses even experienced developers.</p><p>In this article, let’s break down why this happens, how Git thinks, and how to fix it safely without losing your work.</p><h3>The Problem: Unrelated Git Histories</h3><p>When you see this error, Git is essentially saying:</p><blockquote>“I don’t know how to combine these two repositories-they don’t share a common starting point.”</blockquote><p>In other words, your <strong>local repository</strong> and your <strong>remote repository</strong> have completely separate commit histories.</p><h3>Why Git Refuses to Merge Unrelated Histories</h3><p>Git is built around the concept of <strong>commit ancestry-</strong>every commit is linked to its parent commit(s). When you perform a<strong><em> merge</em></strong>, Git looks for a <strong>common ancestor</strong> commit between your local branch and the remote branch.</p><p>But if Git can’t find one, it refuses to merge. That’s when you see:</p><pre>fatal: refusing to merge unrelated histories</pre><h3>Common Real-World Scenarios That Cause This Error</h3><h4>1. <strong>Separate Initializations</strong></h4><p>You create a local repo like this:</p><pre>git init<br>git add .<br>git commit -m &quot;Initial commit&quot;</pre><p>Then you push it to a remote repo that <em>already has</em> files (like a <strong><em>README.md</em></strong> added via the Bitbucket or GitHub UI).</p><p>Now, your local and remote both have separate initial commits-no shared history.</p><h4>2. <strong>Adding Files Directly on the Remote</strong></h4><p>Sometimes you initialize your project locally and later someone adds a file directly on the remote (e.g., a .gitignore or license). Again, no common commit exists between your local and remote repos.</p><h4>3. <strong>Reinitializing a Cloned Repo</strong></h4><p>If you clone a repository, then accidentally run:</p><pre>git init</pre><p>again in the same folder, you’ve created a new history-Git now sees two unrelated repositories.</p><h4>4. <strong>Force Pushes or History Rewrites</strong></h4><p>When someone uses <strong><em>git push --force</em></strong> on the remote, it rewrites commit history. If your local repo still points to the old history, Git will treat the histories as unrelated.</p><h3>How to Fix It — Safely</h3><p>The easiest and most direct fix is to tell Git to <em>allow merging unrelated histories</em>.<br>Run:</p><pre>git pull origin main --allow-unrelated-histories</pre><blockquote>This command tells Git:<br>“Yes, I know these repositories have different roots, but please merge them anyway.”</blockquote><h4>Step-by-step:</h4><ol><li><strong>Pull with the flag:</strong></li></ol><pre>git pull origin main --allow-unrelated-histories</pre><p><strong>2. Resolve merge conflicts (if any):</strong></p><p>Git will merge both histories, but if files like <strong><em>README.md</em></strong> or <strong><em>.gitignore</em></strong> exist in both repos, you’ll need to manually edit and resolve them.</p><p><strong>3. Stage and commit the resolved files:</strong></p><pre>git add .<br>git commit -m &quot;Merge remote and local histories&quot;</pre><p><strong>4. Push your final changes:</strong></p><pre>git push origin main</pre><p>Now your local and remote repositories share a common history.</p><h3>How to Avoid This Error in the Future</h3><p>Here are some best practices to keep your Git workflow clean:</p><ol><li><strong>Always Clone, Don’t Init</strong></li></ol><p>Instead of <strong><em>git init</em></strong>, always start with:</p><pre>git clone &lt;repo-url&gt;</pre><p>This ensures your local repo inherits the remote’s commit history from the start.</p><p><strong>2. Push Early</strong></p><p>If you must create a repo locally first, push it to the remote immediately before others start contributing.</p><p><strong>3. Avoid Force Pushes</strong></p><p>Use <strong><em>git push — force</em></strong> sparingly-it rewrites history and can cause other developers’ local repos to become out of sync.</p><p><strong>4. Communicate With Your Team</strong></p><p>If someone initialized the repo differently or made changes directly on the remote, coordinate before pushing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=002b57d334b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting Laravel to Remote MySQL on Red Hat 9: Multi-Server Architecture]]></title>
            <link>https://medium.com/@kanishkanuwanperera/connecting-laravel-to-remote-mysql-on-red-hat-9-multi-server-architecture-9cb20ea03df0?source=rss-3b73ede655f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cb20ea03df0</guid>
            <category><![CDATA[mysql-database-server]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[multiserver]]></category>
            <category><![CDATA[app-server]]></category>
            <category><![CDATA[redhat-linux]]></category>
            <dc:creator><![CDATA[Kanishka Perera]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 17:51:00 GMT</pubDate>
            <atom:updated>2025-10-05T17:51:00.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlsccBJzOhHbAyTlA3d4RQ.png" /></figure><h3>When one server isn’t enough: Scaling your LAMP stack the right way</h3><p>It’s Monday morning. Your Laravel application has been humming along nicely on your single RHEL 9 server for months. Then your manager walks in with news: “We’re getting audited for SOC 2 compliance. The auditor says we need to separate our database layer for security. We have until Friday.”</p><p>Your heart sinks. You’ve heard horror stories about database migrations gone wrong. Downtime. Data loss. Angry users. But here’s the truth: splitting your database onto a separate server is not only doable — it’s actually straightforward when you know the right steps.</p><p>After setting up dozens of multi-server LAMP architectures for everything from startups to enterprise clients, I’ve learned that the key isn’t just making it work — it’s making it work <strong><em>securely</em></strong> and <strong><em>reliably</em></strong>.</p><p><strong>This is Part 2 of our Red Hat 9 LAMP Stack series.</strong> If you haven’t set up your basic LAMP stack yet, start with <a href="https://medium.com/@kanishkanuwanperera/installing-apache-php-8-2-mysql-phpmyadmin-on-red-hat-9-c931c2d26f82"><strong>Part 1: Installing Apache, PHP 8.2, MySQL &amp; phpMyAdmin on Red Hat 9</strong></a>.</p><h3>What You’ll Learn</h3><ul><li>Why and when to separate your database layer</li><li>Setting up MySQL for remote connections securely</li><li>Configuring Laravel to connect to a remote database</li><li>Troubleshooting connection issues (SELinux, firewall, permissions)</li><li>Security best practices for production environments</li></ul><h3>Part 1: Why Separate Your Database?</h3><h4>The Single-Server Problem</h4><p>When your application and database share a single server, you face several challenges:</p><p><strong>Performance bottlenecks:</strong> Your web server and database compete for the same CPU, RAM, and I/O resources. During traffic spikes, both suffer.</p><p><strong>Security risks:</strong> If an attacker compromises your web application, they immediately have access to your database on the same machine.</p><p><strong>Scaling limitations:</strong> You can’t independently scale your application layer and database layer. Want more web server capacity? You’re also paying for unused database resources.</p><p><strong>Compliance issues:</strong> Many security frameworks (SOC 2, PCI DSS, HIPAA) require or strongly recommend database isolation.</p><h4>The Multi-Server Solution</h4><p>By separating your architecture into:</p><ul><li><strong>Server A:</strong> Application server (Apache + PHP + Laravel)</li><li><strong>Server B:</strong> Database server (MySQL only)</li></ul><p>You gain:</p><p><strong>. Better performance:</strong> Each server has dedicated resources<br>. <strong>Enhanced security:</strong> Network-level isolation between layers<br>. <strong>Independent scaling:</strong> Scale web and database tiers separately<br>. <strong>Easier maintenance:</strong> Update one layer without touching the other<br>. <strong>Compliance ready:</strong> Meets most security framework requirements</p><h3>Part 2: Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxJc21HOYnB393u-DPEhIA.png" /></figure><h3>Network Requirements</h3><ul><li>Both servers must be able to communicate over TCP port 3306</li><li>Preferably on a private network (not exposed to the internet)</li><li>Firewall rules configured to allow MySQL traffic</li><li>SELinux properly configured to permit database connections</li></ul><h3>Part 3: Configuring Server B (Database Server)</h3><p>Let’s start with the database server. We need to configure MySQL to accept remote connections and create a user for Server A.</p><h4>Step 1: Configure MySQL to Listen on All Interfaces</h4><p>By default, MySQL only listens on localhost (127.0.0.1). We need to change this.</p><p>Edit the MySQL configuration file:</p><pre>sudo vi /etc/my.cnf</pre><p><strong>Alternative location</strong> (if the file doesn’t exist at <strong><em>/etc/my.cnf</em></strong>):</p><pre>sudo vi /etc/my.cnf.d/mysql-server.cnf</pre><p>Find the line that says:</p><pre>bind-address = 127.0.0.1<br><br># Change it to:<br>bind-address = 0.0.0.0</pre><p><strong>What does this mean?</strong></p><ul><li><em>127.0.0.1</em> : Only accept connections from localhost</li><li><em>0.0.0.0</em> : Accept connections from any IP address</li></ul><p><strong>Security consideration:</strong> For maximum security, you can specify Server A’s exact IP instead of <em>0.0.0.0</em> :</p><pre>bind-address = 192.168.1.10<br><br># This way, MySQL only accepts connections from your application server.</pre><h4>Step 2: Restart MySQL</h4><p>Apply the configuration changes:</p><pre>sudo systemctl restart mysqld</pre><p>Verify MySQL is running:</p><pre>sudo systemctl status mysqld</pre><h4>Step 3: Verify MySQL is Listening on All Interfaces</h4><p>Check which interfaces MySQL is listening on:</p><pre>sudo netstat -tulnp | grep 3306<br><br>#You should see output like:<br>tcp6  0  0 :::3306  :::*  LISTEN  12345/mysqld<br><br>#or<br>tcp  0  0 0.0.0.0:3306  0.0.0.0:*  LISTEN  12345/mysqld</pre><p><strong>If you see <em>127.0.0.1:3306</em></strong>, MySQL is still only listening locally. Double-check your configuration file and restart MySQL.</p><p><strong>Don’t have netstat?</strong> Install it:</p><pre>sudo dnf install net-tools -y</pre><h4>Step 4: Create a Remote MySQL User</h4><p>Now we need to create a MySQL user that can connect from Server A.</p><p>Log into MySQL as root:</p><pre>mysql -u root -p</pre><p>Enter your MySQL root password when prompted.</p><p>Create a database (if you don’t have one already):</p><pre>CREATE DATABASE laravel_production;</pre><p>Create a user with access from Server A’s IP:</p><pre>CREATE USER &#39;laravel_user&#39;@&#39;192.168.1.10&#39; IDENTIFIED BY &#39;your_strong_password_here&#39;;</pre><p>Grant privileges to this user:</p><pre>GRANT ALL PRIVILEGES ON laravel_production.* TO &#39;laravel_user&#39;@&#39;192.168.1.10&#39;;</pre><p>Flush privileges to apply changes:</p><pre>FLUSH PRIVILEGES;</pre><p>Exit MySQL:</p><pre>EXIT;</pre><p><strong>Important security notes:</strong></p><ul><li>Replace <strong><em>192.168.1.10</em></strong> with Server A&#39;s actual IP address</li><li>Replace <strong><em>your_strong_password_here</em></strong> with a strong password (16+ characters)</li><li>Generate a secure password: <strong><em>openssl rand -base64 24</em></strong></li><li>Never use <strong><em>‘user’@’%’</em></strong> (allows connections from anywhere) in production</li></ul><h4>Step 5: Open MySQL Port in Firewall</h4><p>Allow TCP traffic on port 3306:</p><pre>sudo firewall-cmd --permanent --add-port=3306/tcp<br>sudo firewall-cmd --reload</pre><p>Verify the rule was added:</p><pre>sudo firewall-cmd --list-ports</pre><p>You should see <strong><em>3306/tcp</em></strong> in the output.</p><p><strong>Security tip:</strong> For even better security, restrict to Server A’s IP only:</p><pre>sudo firewall-cmd --permanent --add-rich-rule=&#39;rule family=&quot;ipv4&quot; source address=&quot;192.168.1.10&quot; port protocol=&quot;tcp&quot; port=&quot;3306&quot; accept&#39;<br>sudo firewall-cmd --reload</pre><p>This way, only Server A can connect to MySQL.</p><h4>Step 6: Configure SELinux (Critical!)</h4><p>If SELinux is enabled (which it should be), it might block remote MySQL connections even with correct firewall rules.</p><p>Check if SELinux is enabled:</p><pre>sestatus</pre><p>If it shows <strong><em>SELinux status: enabled</em></strong> and <strong><em>Current mode: enforcing</em></strong> , configure it:</p><pre>sudo setsebool -P mysql_connect_any 1</pre><p><strong>What does this do?</strong> It tells SELinux to allow MySQL to accept network connections.</p><h3>Part 4: Configuring Server A (Application Server)</h3><p>Now let’s configure your Laravel application server to connect to the remote database.</p><h4>Step 7: Allow Outbound Connections (SELinux)</h4><p>On Server A, if SELinux is enabled, allow Apache/PHP to make network database connections:</p><pre>sudo setsebool -P httpd_can_network_connect_db 1</pre><p><strong>What does this do?</strong> By default, SELinux blocks web applications from making network connections to databases. This boolean explicitly allows it.</p><h4>Step 8: Test MySQL Connection from Server A</h4><p>Before changing your Laravel configuration, test that you can connect to MySQL from Server A:</p><pre>mysql -h 192.168.1.20 -u laravel_user -p</pre><p>Replace <strong><em>192.168.1.20</em></strong> with Server B&#39;s actual IP address.</p><p>Enter the password you created in Step 4.</p><p><strong>If the connection succeeds</strong>, you’ll see the <strong><em>mysql&gt;</em></strong> prompt. Type <strong><em>exit</em></strong> to quit.</p><p><strong>If the connection fails</strong>, check these common issues:</p><p><strong>Error: “Connection refused”</strong></p><ul><li>MySQL isn’t running on Server B: <strong><em>sudo systemctl status mysqld</em></strong></li><li>MySQL isn’t listening on 0.0.0.0: Check Step 3</li><li>Firewall is blocking: Check Step 5</li></ul><p><strong>Error: “Access denied”</strong></p><ul><li>Wrong username or password</li><li>User not created for Server A’s IP</li><li>Verify with: <strong><em>SELECT user, host FROM mysql.user WHERE user=’laravel_user’;</em></strong> on Server B</li></ul><p><strong>Error: “Connection timed out”</strong></p><ul><li>Network routing issue between servers</li><li>Firewall blocking at network level (not server firewall)</li><li>Check: <strong><em>ping 192.168.1.20</em></strong> from Server A</li></ul><h4>Step 9: Update Laravel .env File</h4><p>Once the connection test succeeds, update your Laravel configuration:</p><pre>sudo vi /var/www/html/.env</pre><p>Update the database configuration section:</p><pre>DB_CONNECTION=mysql<br>DB_HOST=192.168.1.20<br>DB_PORT=3306<br>DB_DATABASE=laravel_production<br>DB_USERNAME=laravel_user<br>DB_PASSWORD=your_strong_password_here</pre><p>Replace:</p><ul><li><strong><em>192.168.1.20</em></strong> with Server B&#39;s IP address</li><li><strong><em>laravel_production</em></strong> with your database name</li><li><strong><em>laravel_user</em></strong> with your MySQL username</li><li><strong><em>your_strong_password_here</em></strong> with the password from Step 4</li></ul><p><strong>Security reminder:</strong> The <strong><em>.env</em></strong> file should have restricted permissions:</p><pre>sudo chmod 600 /var/www/html/.env<br>sudo chown apache:apache /var/www/html/.env</pre><h4>Step 10: Test Laravel Database Connection</h4><p>Clear Laravel’s configuration cache:</p><pre>cd /var/www/html<br>php artisan config:clear<br>php artisan cache:clear</pre><p>Test the database connection with a migration:</p><pre>php artisan migrate</pre><p>If migrations run successfully, your remote connection is working!</p><p><strong>Alternative test</strong> (doesn’t require migrations):</p><pre>php artisan tinker</pre><p>Then in the tinker shell:</p><pre>DB::connection()-&gt;getPdo();</pre><p>If you see a PDO object returned, the connection works. Type <strong><em>exit</em></strong> to quit tinker.</p><h4>Step 11: Restart Apache</h4><p>Restart Apache to ensure all changes take effect:</p><pre>sudo systemctl restart httpd</pre><h4>Step 12: Test Your Application</h4><p>Open your browser and test your Laravel application:</p><pre>http://192.168.1.10</pre><p>Try actions that require database access:</p><ul><li>User registration</li><li>Login</li><li>Viewing data from the database</li><li>Creating new records</li></ul><p>If everything works, congratulations! Your multi-server architecture is live.</p><h3>Part 5: Setting Laravel’s Public Directory as DocumentRoot</h3><p>For security and proper routing, your Apache DocumentRoot should point to Laravel’s <strong><em>public</em></strong> folder.</p><h4>Step 13: Create Apache Virtual Host Configuration</h4><p>Create a new Apache configuration file:</p><pre>sudo vi /etc/httpd/conf.d/laravel.conf</pre><p>Add the following configuration:</p><pre>&lt;VirtualHost *:80&gt;<br>    ServerName your-domain.com<br>    DocumentRoot /var/www/html/public<br><br>    &lt;Directory /var/www/html/public&gt;<br>        AllowOverride All<br>        Require all granted<br>    &lt;/Directory&gt;<br><br>    ErrorLog /var/log/httpd/laravel_error.log<br>    CustomLog /var/log/httpd/laravel_access.log combined<br>&lt;/VirtualHost&gt;</pre><p>Replace<strong><em> your-domain.com</em></strong> with your actual domain (or use the server IP for testing).</p><p><strong>What does <em>AllowOverride All</em></strong> <strong>do?</strong> It tells Apache to respect Laravel&#39;s <strong><em>.htaccess</em></strong> file in the public directory, which handles URL routing.</p><h4>Step 14: Restart Apache</h4><p>Apply the configuration:</p><pre>sudo systemctl restart httpd</pre><p><strong>Tip:</strong> To save and exit in vi, press <strong><em>Esc</em></strong> , type <strong><em>:wq</em></strong> , then press <strong><em>Enter</em></strong>.</p><h4>Step 15: Verify Configuration</h4><p>Check Apache syntax:</p><pre>sudo apachectl configtest</pre><p>You should see <strong><em>Syntax OK</em></strong> .</p><p>Test your application at:</p><pre>http://your-domain.com<br><br>#or<br>http://192.168.1.10</pre><h3>Part 6: Common Issues and Solutions</h3><h4>Issue 1: Routes Don’t Work (404 Errors)</h4><p><strong>Symptom:</strong> Homepage loads fine, but <strong><em>/about</em></strong> , <strong><em>/login</em></strong> , or other routes return 404.</p><p><strong>Cause:</strong> Apache isn’t processing Laravel’s <strong><em>.htaccess</em></strong> file.</p><p><strong>Solution:</strong></p><p>Make sure your Apache configuration has <strong><em>AllowOverride All</em></strong> (see Step 13).</p><p>Edit the main Apache config if needed:</p><pre>sudo vi /etc/httpd/conf/httpd.conf</pre><p>Find the Directory section and ensure:</p><pre>&lt;Directory &quot;/var/www/html/public&quot;&gt;<br>    AllowOverride All<br>    Require all granted<br>&lt;/Directory&gt;</pre><p><strong>Enable mod_rewrite</strong> (usually enabled by default on RHEL):</p><pre>sudo dnf install mod_rewrite -y<br>sudo systemctl restart httpd</pre><h4>Issue 2: Permission Denied Errors</h4><p><strong>Symptom:</strong> Laravel can’t write to <strong><em>storage</em></strong> or <strong><em>bootstrap/cache</em></strong> directories.</p><p><strong>Solution:</strong></p><p>Set proper permissions (run on Server A):</p><pre>sudo chown -R root:apache /var/www/html/storage /var/www/html/bootstrap/cache<br><br># Directories<br>sudo find /var/www/html/storage /var/www/html/bootstrap/cache -type d -exec chmod 2775 {} \;<br><br># Files<br>sudo find /var/www/html/storage /var/www/html/bootstrap/cache -type f -exec chmod 664 {} \;</pre><p><strong>Configure SELinux</strong> to allow Apache to write to these directories:</p><pre>sudo chcon -R -t httpd_sys_rw_content_t /var/www/html/storage /var/www/html/bootstrap/cache</pre><h4>Issue 3: Database Connection Intermittently Fails</h4><p><strong>Symptom:</strong> Application works sometimes, but randomly shows database connection errors.</p><p><strong>Possible causes:</strong></p><p><strong>1. Connection timeout settings</strong></p><p>Edit Laravel’s <strong><em>config/database.php</em></strong> and adjust timeout:</p><pre>&#39;mysql&#39; =&gt; [<br>    // ... other settings<br>    &#39;options&#39; =&gt; [<br>        PDO::ATTR_TIMEOUT =&gt; 5,<br>        PDO::ATTR_PERSISTENT =&gt; true,<br>    ],<br>],</pre><p><strong>2. MySQL max connections limit</strong></p><p>On Server B, check current connections:</p><pre>SHOW VARIABLES LIKE &#39;max_connections&#39;;<br>SHOW STATUS LIKE &#39;Threads_connected&#39;;</pre><p>Increase if needed in <strong><em>/etc/my.cnf</em></strong> :</p><pre>[mysqld]<br>max_connections = 200</pre><p>Restart MySQL:</p><pre>sudo systemctl restart mysqld</pre><p><strong>3. Network instability</strong></p><p>Test network latency:</p><pre>ping -c 100 192.168.1.20</pre><p>If you see packet loss or high latency, investigate network issues.</p><h3>Troubleshooting Checklist</h3><p>When things go wrong, work through this checklist systematically:</p><h4>Server B (Database Server)</h4><ul><li>MySQL is running: <strong><em>sudo systemctl status mysqld</em></strong></li><li>MySQL is listening on 0.0.0.0: <strong><em>sudo netstat -tulnp | grep 3306</em></strong></li><li>Firewall allows port 3306: <strong><em>sudo firewall-cmd — list-ports</em></strong></li><li>User exists with correct host: <strong><em>SELECT user, host FROM mysql.user;</em></strong></li><li>User has proper grants: <strong><em>SHOW GRANTS</em></strong> <br>FOR <strong><em>‘laravel_user’@’192.168.1.10&#39;;</em></strong></li><li>SELinux allows MySQL connections: <strong><em>getsebool mysql_connect_any</em></strong></li></ul><h4>Server A (Application Server)</h4><ul><li>Can ping Server B: <strong><em>ping 192.168.1.20</em></strong></li><li>Can connect to MySQL: <strong><em>mysql -h 192.168.1.20 -u laravel_user -p</em></strong></li><li><strong><em>.env</em></strong> has correct credentials</li><li>SELinux allows network DB connections: <strong><em>getsebool</em></strong> <strong><em>httpd_can_network_connect_db</em></strong></li><li>Apache can read <strong><em>.env</em></strong> : <strong><em>ls -l /var/www/html/.env</em></strong></li><li>Laravel cache is cleared: <strong><em>php artisan config:clear</em></strong></li></ul><h4>Network Level</h4><ul><li>No intermediate firewall blocking port 3306</li><li>Servers are on same network or properly routed</li><li>DNS resolution works (if using hostnames)</li><li>SSL/TLS certificates valid (if using encrypted connection)</li></ul><h3>Conclusion: You’re Production-Ready</h3><p>Congratulations! You’ve successfully set up a multi-server LAMP architecture on Red Hat 9. You now have:</p><p><strong>. Separated application and database layers</strong> for better security and performance<br> . <strong>Properly configured MySQL</strong> for remote access<br> . <strong>Laravel application</strong> connecting to a remote database<br> . <strong>Troubleshooting skills</strong> for common RHEL-specific issues<br> . <strong>Production-ready configuration</strong> for multi-server setup</p><p>This architecture forms the foundation for scaling your application. You can now add more application servers, implement load balancing, and scale each tier independently based on demand.</p><h3>What’s Next?</h3><p>Ready to take your infrastructure further?</p><p><strong>Recommended next steps:</strong></p><ol><li><strong>Set up SSL/TLS certificates</strong> with Let’s Encrypt for HTTPS</li><li><strong>Implement automated backups</strong> for your database</li><li><strong>Add monitoring and alerting</strong> with tools like Prometheus or New Relic</li><li><strong>Configure advanced security</strong> including MySQL SSL/TLS and IP whitelisting</li><li><strong>Optimize performance</strong> with query caching and connection pooling</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cb20ea03df0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Apache, PHP 8.2, MySQL & phpMyAdmin on Red Hat 9]]></title>
            <link>https://medium.com/@kanishkanuwanperera/installing-apache-php-8-2-mysql-phpmyadmin-on-red-hat-9-c931c2d26f82?source=rss-3b73ede655f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c931c2d26f82</guid>
            <category><![CDATA[php-8]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[redhat-linux]]></category>
            <category><![CDATA[phpmyadmin]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Kanishka Perera]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 18:09:06 GMT</pubDate>
            <atom:updated>2025-10-04T18:09:06.603Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The foundation every PHP developer needs on RHEL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKRjr4rK__y0FQRCw5PgDA.png" /></figure><p>It’s 2 AM. Your client needs their Laravel application deployed by morning. You SSH into the fresh Red Hat 9 server, ready to install a basic LAMP stack. “This should take 20 minutes,” you think.</p><p>Three hours later, you’re still battling PHP version conflicts, MySQL permission errors, and wondering why Apache isn’t loading your PHP files. RHEL isn’t Ubuntu. The security is tighter, the repos are different, and SELinux has opinions about everything.</p><p>I’ve created this guide to get you from fresh server to fully functional LAMP stack in under an hour — with no surprises.</p><h4>What You’ll Learn</h4><ul><li>Installing Apache HTTP Server and configuring it properly</li><li>Upgrading from PHP 8.0 to PHP 8.2 (the right way)</li><li>Setting up and securing MySQL Server</li><li>Installing phpMyAdmin for easy database management</li><li>Fixing file permissions for PHP applications</li><li>Troubleshooting common RHEL-specific issues</li></ul><blockquote><strong>Time investment:</strong> 45 minutes<br><strong>Difficulty:</strong> Beginner to Intermediate<br><strong>Prerequisites:</strong> Root or sudo access to a Red Hat 9 server</blockquote><h3>Part 1: System Preparation</h3><h4>Step 1: Update Your System (Never Skip This)</h4><p>Before installing any software, update your system to ensure you have the latest security patches:</p><pre>sudo dnf update -y<br>sudo dnf upgrade -y</pre><p><strong>Why this matters: </strong>Installing software on an outdated system is like building a house on a cracked foundation. Security vulnerabilities matter, especially in production environments.</p><p>This process might take 5–10 minutes depending on your server and available updates. Grab some coffee.</p><h3>Part 2: Apache HTTP Server</h3><h4>Step 2: Install Apache</h4><p>Apache is the web server that will handle HTTP requests and serve your PHP applications:</p><pre>sudo dnf install httpd -y</pre><h4>Step 3: Start and Enable Apache</h4><p>Start the service immediately and configure it to start automatically on boot:</p><pre>sudo systemctl enable --now httpd<br></pre><p>What does <strong><em>— now</em></strong> do? It’s a shortcut that combines <strong><em>enable</em></strong> (start on boot) and <strong><em>start</em></strong> (start immediately) into one command.</p><h4>Step 4: Verify Apache is Running</h4><p>Check the service status:</p><pre>sudo systemctl status httpd<br><br># If it’s not running, start it:<br>sudo systemctl start httpd</pre><p>You should see <strong><em>active (running)</em></strong> in green text.</p><h4>Step 5: Configure Firewall</h4><p>Open port 80 (HTTP) in your firewall:</p><pre>sudo firewall-cmd --permanent --add-service=http<br>sudo firewall-cmd --reload</pre><p><strong>Quick test:</strong> Open your browser and visit <a href="http://your_server_ip/"><strong><em>http://your_server_ip</em></strong></a>. You should see the Red Hat Enterprise Linux Test Page. If you do, Apache is working!</p><p><strong>Can’t see the test page?</strong> Check these:</p><ul><li>Is your server IP correct?</li><li>Is the firewall blocking the connection?</li><li>Is Apache actually running? (<strong><em>sudo systemctl status httpd</em></strong>)</li></ul><h3>Part 3: PHP 8.2 Installation</h3><h4>The PHP Version Challenge</h4><p>RHEL 9 ships with PHP 8.0 by default. While that’s perfectly stable, most modern frameworks (Laravel 10+, Symfony 6+) require PHP 8.1 or higher. Here’s how to get PHP 8.2 running.</p><h4>Step 6: Enable Additional Repositories</h4><p>First, we need to enable the CodeReady Builder repository (required for EPEL dependencies):</p><pre>sudo subscription-manager repos --enable codeready-builder-for-rhel-9-$(arch)-rpms</pre><blockquote>If you don’t have a Red Hat subscription, this might not work.</blockquote><p><strong>Don’t have a Red Hat subscription? </strong>No problem. Install EPEL manually:</p><pre>sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm -y</pre><h3>Step 7: Verify EPEL Repository</h3><p>Check that EPEL was added successfully:</p><pre>sudo dnf repolist</pre><blockquote>You should see <strong>epel</strong> or <strong>epel-release</strong> in the list.</blockquote><h4>Step 8: Install Remi Repository</h4><p>The Remi repository provides newer PHP versions for RHEL:</p><pre>sudo dnf install https://rpms.remirepo.net/enterprise/remi-release-9.rpm -y</pre><h4>Step 9: Switch to PHP 8.2</h4><p>Reset the default PHP module and enable PHP 8.2 from Remi:</p><pre>sudo dnf module reset php -y<br>sudo dnf module enable php:remi-8.2 -y</pre><p><strong>What’s a “module” in dnf?</strong> Think of it as a version selector. RHEL can have multiple PHP versions available, and modules let you choose which one to use.</p><h4>Step 10: Install PHP and Essential Extensions</h4><p>Now install PHP with the most commonly needed extensions:</p><pre>sudo dnf install php php-cli php-common php-mysqlnd php-curl php-gd php-mbstring php-xml php-zip php-intl -y</pre><p><strong>What each extension does:</strong></p><ul><li><strong><em>php-cli:</em></strong><em> </em>Run PHP from command line (required for Composer, Artisan)</li><li><strong><em>php-common:</em></strong> Core PHP functionality</li><li><strong><em>php-mysqlnd:</em></strong> MySQL database connectivity</li><li><strong><em>php-curl:</em></strong> Make HTTP requests (APIs, webhooks, etc.)</li><li><strong><em>php-gd:</em></strong> Image manipulation and generation</li><li><strong><em>php-mbstring: </em></strong>Handle multi-byte strings (essential for international text)</li><li><strong><em>php-xml:</em></strong> XML processing (required by most frameworks)</li><li><strong><em>php-zip:</em></strong> Create and extract ZIP archives</li><li><strong><em>php-intl:</em></strong> Internationalization functions</li></ul><h4>Step 11: Restart Apache</h4><p>Restart Apache to load the PHP module:</p><pre>sudo systemctl restart httpd</pre><h4>Step 12: Verify PHP Installation</h4><p>Check the PHP version:</p><pre>php -v</pre><p>You should see something like:<br><em>PHP 8.2.x (cli) (built: …)</em></p><p><strong>Troubleshooting:</strong> If <strong><em>php -v </em></strong>doesn&#39;t work or shows the wrong version, try reinstalling PHP CLI:</p><pre>sudo dnf install php-cli -y</pre><h4>Step 13: Test PHP in Apache</h4><p>Create a PHP info file to verify Apache can process PHP:</p><pre>echo &quot;&lt;?php phpinfo(); ?&gt;&quot; | sudo tee /var/www/html/info.php</pre><p>Visit <a href="http://your_server_ip/info.php"><strong><em>http://your_server_ip/info.php</em></strong></a> in your browser. You should see a detailed PHP configuration page showing version 8.2.x.</p><p><strong>Security reminder:</strong> Delete this file after testing, as it exposes sensitive server information:</p><pre>sudo rm /var/www/html/info.php</pre><h3>Part 4: MySQL Database Server</h3><h4>Step 14: Install MySQL Server</h4><p>Install MySQL from the default RHEL repository:</p><pre>sudo dnf install -y mysql-server</pre><h4>Step 15: Start and Enable MySQL</h4><p>Start MySQL and configure it to run on boot:</p><pre>sudo systemctl start mysqld<br>sudo systemctl enable mysqld</pre><h4>Step 16: Check MySQL Status</h4><p>Verify MySQL is running:</p><pre>sudo systemctl status mysqld</pre><h4>Step 17: Find Your Temporary Root Password</h4><p>When MySQL is first installed, it generates a temporary root password. Find it in the log file:</p><pre>sudo grep &#39;temporary password&#39; /var/log/mysqld.log</pre><p>Copy this password—you’ll need it in the next step.</p><p><strong>Note:</strong> If the command returns nothing, it means MySQL didn’t generate a temporary password. You might be able to log in without one initially.</p><h4>Step 18: Secure Your MySQL Installation</h4><p>Run the MySQL security script:</p><pre>sudo mysql_secure_installation</pre><p>The script will guide you through several prompts:</p><p>1. <strong>Enter current root password:</strong> Use the temporary password from Step 17</p><p>2. <strong>Set new root password:</strong> Create a strong password (16–32 characters recommended)</p><p>· Generate a secure password: <strong><em>openssl rand -base64 24</em></strong></p><p>3. <strong>Remove anonymous users?</strong> Type <strong>Y</strong> (Yes)</p><p>4. <strong>Disallow root login remotely?</strong> Type <strong>Y</strong> (Yes)</p><p>5. <strong>Remove test database?</strong> Type <strong>Y</strong> (Yes)</p><p>6. <strong>Reload privilege tables now?</strong> Type <strong>Y</strong> (Yes)</p><p><strong>Why secure MySQL?</strong> Default installations are vulnerable to:</p><ul><li>Anonymous user access</li><li>Remote root logins</li><li>Test databases with weak security</li></ul><p>This script hardens your database against common attack vectors.</p><h4>Step 19: Open MySQL Port (Optional)</h4><p>Only do this if you need remote MySQL access:</p><pre>sudo firewall-cmd --permanent --add-port=3306/tcp<br>sudo firewall-cmd --reload</pre><h4>Step 20: Restart MySQL</h4><p>Apply all configuration changes:</p><pre>sudo systemctl restart mysqld</pre><h4>Step 21: Test MySQL Connection</h4><p>Log into MySQL to verify everything works:</p><pre>mysql -u root -p<br><br># Enter your new root password. If you see the mysql&gt; prompt, you&#39;re in! Type exit to quit.</pre><h3>Part 5: phpMyAdmin Installation</h3><p>phpMyAdmin provides a web-based interface for managing MySQL databases.<br>Unfortunately, phpMyAdmin is not in the default RHEL AppStream repository. You can install it by:</p><ul><li>Downloading the latest phpMyAdmin manually, or</li><li>Using the EPEL repository (Extra Packages for Enterprise Linux)</li></ul><h3>Option A: Install via EPEL Repository (Recommended)</h3><p>This is the easiest method and gets you a stable version:</p><pre># First, enable EPEL repo:<br>sudo dnf install -y epel-release<br>sudo dnf update -y<br><br># Then install phpMyAdmin:<br>sudo dnf install -y phpmyadmin</pre><p>After installation, phpMyAdmin will be accessible at: <a href="http://your_server_ip/phpmyadmin"><strong><em>http://your_server_ip/phpmyadmin</em></strong></a></p><h3>Option B: Manual Installation (Latest Version)</h3><p>If you want the newest features or EPEL doesn’t work:</p><p><strong>Step 1: Download the latest phpMyAdmin:</strong></p><pre>cd /var/www/html<br>sudo wget https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.tar.gz</pre><p><strong>Step 2: Extract the archive:</strong></p><pre>sudo tar xzf phpMyAdmin-latest-all-languages.tar.gz<br>sudo mv phpMyAdmin-*-all-languages phpmyadmin<br>sudo rm phpMyAdmin-latest-all-languages.tar.gz</pre><p><strong>Step 3: Create a temp directory for sessions:</strong></p><pre>sudo mkdir /var/www/html/phpmyadmin/tmp</pre><p><strong>Step 4: Set proper permissions:</strong></p><pre>sudo chown -R apache:apache /var/www/html/phpmyadmin # To upload SQL files, both root and Apache permissions will be required at a later stage.<br>sudo chmod 777 /var/www/html/phpmyadmin/tmp</pre><p><strong>Why these permissions?</strong> phpMyAdmin needs to write session data to the <strong><em>tmp</em></strong> directory. The <strong><em>apache</em></strong> user needs ownership, and <strong><em>777</em></strong> allows full read/write access.</p><h4>Step 22: Test phpMyAdmin</h4><p>Open your browser and navigate to:<br><a href="http://your_server_ip/phpmyadmin"><strong><em>http://your_server_ip/phpmyadmin</em></strong></a></p><p>You should see the phpMyAdmin login page. Log in with:</p><ul><li><strong>Username:</strong> <em>root</em></li><li><strong>Password:</strong> Your MySQL root password</li></ul><p><strong>Can’t access phpMyAdmin?</strong> Check these:</p><ul><li>Is Apache running? (<strong><em>sudo systemctl status httpd</em></strong>)</li><li>Is the firewall allowing HTTP? (<strong><em>sudo firewall-cmd — list-services</em></strong>)</li><li>Is the directory path correct? (<strong><em>ls -la /var/www/html/</em></strong>)</li></ul><h3>Part 6: File Permissions for PHP Applications</h3><p>This is where most developers hit a wall. You deploy your application, but uploads fail, logs can’t be written, and permission errors are everywhere. Here’s the proper fix.</p><p><strong>The Problem<br></strong>By default, <strong><em>/var/www/html</em></strong> is owned by <strong><em>root:root</em></strong> with restrictive permissions. When you try to:</p><ul><li>Upload files via SFTP</li><li>Have your PHP app write to storage directories</li><li>Generate logs or cache files</li></ul><p>You get: <strong>Permission Denied</strong></p><h4>The Solution: Group-Based Permissions</h4><h4>Step 23: Identify Your Username</h4><p>Find out your Linux username:</p><pre>whoami</pre><p>Let’s say it returns <strong><em>systemadmin</em></strong>.</p><h4>Step 24: Add Your User to Apache Group</h4><p>Add your user to the <strong><em>apache</em></strong> group so you share permissions with the web server:</p><pre>sudo usermod -aG apache systemadmin</pre><p>Replace <strong><em>systemadmin</em></strong> with your actual username.</p><p><strong>Critical:</strong> You must log out and log back in (or close and reopen your SFTP client) for this group change to take effect.</p><h4>Step 25: Change Group Ownership</h4><p>Make the <strong><em>apache</em></strong> group the owner of the web directory:</p><pre>sudo chown -R root:apache /var/www/html</pre><p>This keeps <strong><em>root</em></strong> as the owner but gives the <strong><em>apache</em></strong> group access.</p><h4>Step 26: Set Directory Permissions</h4><p>Set proper permissions for directories:</p><pre>sudo find /var/www/html -type d -exec chmod 2775 {} \;</pre><p><strong>What’s 2775?</strong></p><ul><li><strong>2</strong>: setgid bit (new files inherit the group)</li><li><strong>7</strong>: Owner has read, write, execute</li><li><strong>7</strong>: Group has read, write, execute</li><li><strong>5</strong>: Others have read and execute</li></ul><h4>Step 27: Set File Permissions</h4><p>Set proper permissions for files:</p><pre>sudo find /var/www/html -type f -exec chmod 664 {} \;</pre><p><strong>What’s 664?</strong></p><ul><li><strong>6</strong>: Owner has read and write</li><li><strong>6</strong>: Group has read and write</li><li><strong>4</strong>: Others have read only</li></ul><p>Check the permissions:</p><pre>ls -ld /var/www/html</pre><p>You should see:</p><pre>drwxrwsr-x. 3 root apache 24 May 21 08:59 /var/www/html</pre><p>The <em>s</em> in <em>rws</em> indicates the setgid bit is set.</p><h3>Part 7: Laravel-Specific Permissions</h3><p>If you’re deploying a Laravel application, two directories need special attention: <strong><em>storage</em></strong> and <strong><em>bootstrap/cache</em></strong>.</p><h4>Step 29: Set Laravel Directory Permissions</h4><pre>sudo chown -R root:apache /var/www/html/storage /var/www/html/bootstrap/cache</pre><h4>Step 30: Set Laravel Directory and File Permissions</h4><p>For directories:</p><pre>sudo find /var/www/html/storage /var/www/html/bootstrap/cache -type d -exec chmod 2775 {} \;</pre><p>For files:</p><pre>sudo find /var/www/html/storage /var/www/html/bootstrap/cache -type f -exec chmod 664 {} \;</pre><h4>Step 31: Configure SELinux (If Enabled)</h4><p>If SELinux is enabled on your system (it should be in production), you need to explicitly tell it that Apache can write to these directories:</p><pre>sudo chcon -R -t httpd_sys_rw_content_t /var/www/html/storage /var/www/html/bootstrap/cache</pre><p><strong>What is SELinux?</strong> Security-Enhanced Linux adds an extra security layer beyond traditional Unix permissions. It’s enabled by default on RHEL and provides mandatory access controls.</p><p><strong>Make SELinux permissions permanent: (optional)</strong></p><pre>sudo semanage fcontext -a -t httpd_sys_rw_content_t &quot;/var/www/html/storage(/.*)?&quot;<br>sudo semanage fcontext -a -t httpd_sys_rw_content_t &quot;/var/www/html/bootstrap/cache(/.*)?&quot;<br>sudo restorecon -Rv /var/www/html/storage /var/www/html/bootstrap/cache</pre><p><strong>Don’t have semanage?</strong> Install it:</p><pre>sudo dnf install policycoreutils-python-utils -y</pre><h3>Common Issues and Quick Fixes</h3><h4>Issue 1: “Permission Denied” When Uploading Files</h4><p><strong>Symptoms:</strong></p><ul><li>Can’t upload files via SFTP</li><li>Can’t create directories</li><li><strong><em>mkdir(): Permission denied</em></strong> errors</li></ul><p><strong>Solution:</strong></p><ol><li>Make sure you added your user to the <strong><em>apache</em></strong> group (Step 24)</li><li>Log out and back in for group changes to take effect</li><li>Verify directory permissions are <strong><em>2775</em></strong> (Step 26)</li><li>Verify file permissions are <strong><em>664</em></strong> (Step 27)</li></ol><h4>Issue 2: Can’t Access phpMyAdmin</h4><p><strong>Symptoms:</strong></p><ul><li><strong><em>404 Not Found</em></strong> when accessing phpMyAdmin</li><li><strong><em>403 Forbidden</em></strong> error</li></ul><p><strong>Solution:</strong></p><p>Check if phpMyAdmin directory exists:</p><pre>ls -la /var/www/html/phpmyadmin</pre><p>If using EPEL installation, check the default config:</p><pre>sudo vi /etc/httpd/conf.d/phpMyAdmin.conf</pre><p>Make sure it allows access from your IP. By default, it might be restricted to localhost only.</p><h4>Issue 3: MySQL Connection Refused</h4><p><strong>Symptoms:</strong></p><ul><li><em>ERROR 2002 (HY000): Can’t connect to MySQL server</em></li><li>Applications can’t connect to database</li></ul><p><strong>Solution:</strong></p><ol><li>Check if MySQL is running:</li></ol><pre>sudo systemctl status mysqld</pre><p>2. If not running, start it:</p><pre>sudo systemctl start mysqld</pre><p>3. Check if it’s listening:</p><pre>sudo netstat -tulnp | grep 3306</pre><p>You should see MySQL listening on port 3306.</p><h3>Bonus: Moving Files on RHEL</h3><p>Here are some useful commands for managing files on your server:</p><h4>Move All Files (Including Hidden Files)</h4><pre>shopt -s dotglob<br>mv /path/to/source/* /path/to/dest/<br>shopt -u dotglob</pre><p><strong>Why <em>dotglob?</em></strong> By default, the <strong>*</strong> wildcard doesn&#39;t match hidden files (those starting with <strong>.</strong> ). The <strong><em>dotglob</em></strong> option includes them.</p><h4>Alternative: Using Brace Expansion</h4><pre>mv /path/to/source/{*,.*} /path/to/dest/ 2&gt;/dev/null</pre><p>The <strong><em>2&gt;/dev/null</em></strong> suppresses error messages from trying to move ‘.’ and ‘..’ directories.</p><h4>Move Single File or Folder</h4><pre># Single file<br>mv /path/to/source/somefile.txt /path/to/dest/<br><br># Single folder<br>mv /path/to/source/somedir/ /path/to/dest/</pre><h4>Move Multiple Specific Items</h4><pre>mv file1.jpg file2.png somedir/ /path/to/dest/</pre><h3>Security Checklist</h3><p>Before considering your server production-ready, verify:</p><ul><li><strong>System is updated:</strong> All packages are current</li><li><strong>Firewall is configured:</strong> Only necessary ports (80, 443) are open</li><li><strong>MySQL root password is strong:</strong> 16+ characters, random</li><li><strong>Remote MySQL root login is disabled:</strong> Security script completed</li><li><strong>phpMyAdmin access is restricted:</strong> IP whitelist or HTTP authentication</li><li><strong>SELinux is enabled:</strong> Don’t disable it; configure it properly</li><li><strong>File permissions are correct:</strong> No <strong><em>777</em></strong> permissions except where documented</li><li><strong>PHP errors are hidden:</strong> <strong><em>display_errors = Off</em></strong> in production</li><li><strong>SSL certificate installed:</strong> Use Let’s Encrypt for free HTTPS</li><li><strong>Regular backups configured:</strong> Database and file backups automated</li></ul><h3>What You’ve Accomplished</h3><p>Congratulations! You now have a fully functional LAMP stack on Red Hat 9. You’ve successfully:</p><p>✅ Installed and configured Apache HTTP Server<br> ✅ Upgraded to PHP 8.2 with essential extensions<br> ✅ Set up and secured MySQL Server<br> ✅ Installed phpMyAdmin for database management<br> ✅ Configured proper file permissions for PHP applications<br> ✅ Learned RHEL-specific security considerations</p><p>Your server is now ready to host PHP applications, from simple websites to complex frameworks like Laravel, Symfony, or WordPress.</p><h3>What’s Next?</h3><p>Ready to take your server to the next level? Check out these follow-up guides:</p><ol><li><strong>Remote MySQL Connections:</strong> Connect your application server to a separate database server</li><li><strong>SSL Certificate Setup:</strong> Secure your site with free Let’s Encrypt certificates</li><li><strong>Production Optimization:</strong> PHP-FPM, OPcache, and performance tuning</li><li><strong>Automated Backups:</strong> Set up database and file backups with cron jobs</li><li><strong>Monitoring Setup:</strong> Use Nagios, Prometheus, or New Relic</li></ol><p><strong>Questions?</strong> Drop them in the comments below. I read and respond to every one.</p><p><strong>Found this helpful?</strong> Share it with your team and bookmark it for your next server setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c931c2d26f82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a Complete LAMP Stack on Ubuntu: A Developer’s Journey]]></title>
            <link>https://medium.com/@kanishkanuwanperera/setting-up-a-complete-lamp-stack-on-ubuntu-a-developers-journey-402527ff79aa?source=rss-3b73ede655f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/402527ff79aa</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Kanishka Perera]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 08:56:33 GMT</pubDate>
            <atom:updated>2025-09-28T08:56:33.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ4TmzAOa5YHUaH7LI-Atw.png" /></figure><p>A comprehensive guide to installing Linux, Apache, MySQL, and PHP for web development</p><h3><strong>Introduction</strong></h3><p>As a developer diving into server-side web development, one of the first hurdles you’ll encounter is setting up a proper development environment. The LAMP stack—Linux, Apache, MySQL, and PHP—remains one of the most popular and reliable combinations for hosting dynamic websites and web applications.<br>Recently, I went through the process of setting up a LAMP stack on Ubuntu, and I want to share the insights, challenges, and best practices I discovered along the way. This guide will walk you through each step while explaining the reasoning behind important decisions.</p><p><strong>What Is a LAMP Stack?</strong></p><p><strong><em>Linux:</em></strong><em> The operating system (Ubuntu in our case)<br></em><strong><em>Apache:</em></strong><em> The web server that handles HTTP requests<br></em><strong><em>MySQL:</em></strong><em> The database management system for storing application data<br></em><strong><em>PHP:</em></strong><em> The server-side scripting language for dynamic content</em></p><blockquote>This combination has powered millions of websites and remains relevant due to its stability, flexibility, and extensive community support.</blockquote><h3>Prerequisites and System Preparation</h3><p>Before diving into the installation, it’s crucial to start with a clean, updated system. This ensures compatibility and reduces potential conflicts:</p><pre>sudo apt update<br>sudo apt upgrade</pre><p>These commands update your package lists and upgrade existing packages to their latest versions. While this might seem like a minor step, it can save hours of debugging later.</p><h3>Step 1: Installing and Configuring Apache</h3><p>Apache serves as the backbone of your web server, handling incoming HTTP requests and serving web pages to users.</p><p><strong>Installation</strong></p><pre>sudo apt install apache2</pre><p><strong>Start Apache Server</strong></p><pre>sudo systemctl enable apache2<br>sudo systemctl start apache2</pre><p><strong>Firewall Configuration</strong></p><p>One aspect that many tutorials gloss over is proper firewall configuration. Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP traffic. Ubuntu’s default firewall configuration tool is called Uncomplicated Firewall (UFW). Ubuntu’s UFW (Uncomplicated Firewall) provides different Apache profiles:</p><blockquote><strong>Apache:</strong> Opens only port 80 (HTTP)<br><strong>Apache Full:</strong> Opens ports 80 and 443 (HTTP and HTTPS)<br><strong>Apache Secure: </strong>Opens only port 443 (HTTPS)</blockquote><pre># To list all currently available UFW application profiles<br>sudo ufw app list</pre><p><em>For initial setup, start with the basic </em><strong><em>Apache</em></strong><em> profile:</em></p><pre>sudo ufw allow in &quot;Apache&quot;<br><br># Verify the change with:<br>sudo ufw status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*3XWx5HV-DFoF93badP_e5A.png" /></figure><p><strong><em>Pro tip:</em></strong><em> You can test your Apache installation immediately by visiting </em><a href="http://your_server_ip/"><em>http://your_server_ip</em></a><em> in your browser. You should see the Apache2 default page.</em></p><h3>Step 2: MySQL Database Setup</h3><p>MySQL handles all your data storage needs. The installation process has some important security considerations.</p><p><strong>Installation</strong></p><pre>sudo apt install mysql-server</pre><p>Once the installation is complete, the MySQL server should be started automatically. You can quickly check its current status via systemd:</p><pre>sudo service mysql status</pre><p><em>Which should provide an output like the following:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNeYoLEvu-dNAH79bS20dQ.png" /></figure><p>To check the network status of the MySQL service, run the following command:</p><pre>sudo ss -tap | grep mysql</pre><p><em>output:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*_k-qgUf00bkxds4R4us_Rw.png" /></figure><pre># If the server is not running correctly, you can type the following command <br># to start it:<br><br>sudo service mysql restart</pre><p><strong>Security Hardening</strong></p><p>The most critical step that many developers skip is securing the MySQL installation:</p><pre>sudo mysql_secure_installation</pre><p>This script guides you through several security improvements:</p><ol><li><strong>Password validation plugin</strong>: I recommend enabling this with MEDIUM level (length ≥ 8, mixed case, numbers, special characters)</li></ol><p><strong>Root password</strong>: Set a strong password using something like <strong><em>openssl rand -base64 24</em></strong></p><ol><li><strong>Remove anonymous users</strong>: Always say yes</li><li><strong>Disable remote root login</strong>: Essential for security</li><li><strong>Remove test database</strong>: Eliminates unnecessary attack vectors</li></ol><pre>Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN,your <br>server will next ask you to select and confirm a password for the MySQL root <br>user. This is not to be confused with the system root. The database root user <br>is an administrative user with full privileges over the database system. Even <br>though the default authentication method for the MySQL root user doesn’t <br>involve using a password, even when one is set, you should define a strong <br>password here as an additional safety measure.</pre><pre># test whether you’re able to log in to the MySQL console by typing:<br><br>sudo mysql<br><br># This will connect to the MySQL server as the administrative database user root,<br># which is inferred by the use of sudo when running this command. <br><br># or use <br>sudo mysql -u root</pre><h3>Step 3: PHP Installation and Configuration</h3><p>PHP brings your website to life by processing server-side logic and generating dynamic content.</p><p>PHP is available on Ubuntu Linux but, unlike Python (which comes pre-installed), must be manually installed.<br>To install PHP—and the Apache PHP module:</p><pre>sudo apt install php libapache2-mod-php</pre><p><strong>Essential Extensions</strong><br>Don’t just install basic PHP. These extensions are commonly needed:</p><pre>sudo apt install php libapache2-mod-php php-mysql php-cli php-curl php-gd \<br>php-mbstring php-xml php-zip php-intl -y</pre><p>Here’s why each extension matters:</p><ul><li><strong>php-mysql</strong>: Database connectivity</li><li><strong>php-cli</strong>: Command-line PHP execution</li><li><strong>php-curl</strong>: HTTP requests to external APIs</li><li><strong>php-gd</strong>: Image manipulation</li><li><strong>php-mbstring</strong>: Multi-byte string handling</li><li><strong>php-xml</strong>: XML processing</li><li><strong>php-zip</strong>: Archive handling</li><li><strong>php-intl</strong>: Internationalization support</li></ul><p><strong>Verification</strong></p><pre># Check PHP version:<br>php -v<br><br># Restart Apache Server<br>sudo systemctl restart apache2<br><br># Test PHP Installation<br>echo &quot;&lt;?php phpinfo(); ?&gt;&quot; | sudo tee /var/www/html/phpinfo.php</pre><p>Visit <a href="http://localhost/phpinfo.php"><em>http://localhost/phpinfo.php</em></a> to see your PHP configuration.</p><p><strong>Important</strong>: Remove this file after testing for security reasons.</p><pre># Remove this file once confirmed:<br>sudo rm /var/www/html/phpinfo.php</pre><h3><strong>Step 4: Integration and Testing</strong></h3><p>The real test comes when you verify that all components work together.</p><p><strong>Database Setup</strong><br>Create a test database and user:</p><pre>sudo mysql -u root -p<br>CREATE DATABASE your_db;<br>CREATE USER &#39;db_user&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;your_secure_password&#39;;<br>GRANT ALL PRIVILEGES ON your_db.* TO &#39;db_user&#39;@&#39;localhost&#39;;<br>FLUSH PRIVILEGES;<br>EXIT;</pre><p><strong>Connection Test</strong></p><p>Create a simple PHP script to test database connectivity:</p><pre># Create a file named index.php in /var/www/html/:<br>sudo nano /var/www/html/index.php<br><br># Add the following PHP code:<br>&lt;?php<br>$connection = mysqli_connect(&#39;localhost&#39;, &#39;db_user&#39;, &#39;your_secure_password&#39;, &#39;your_db&#39;);<br>if (!$connection) {<br>    die(&quot;Connection failed: &quot; . mysqli_connect_error());<br>}<br>echo &quot;Connected successfully to MySQL&quot;;<br>mysqli_close($connection);<br>?&gt;<br><br># Save and exit.</pre><p>Test the PHP Script<br>Access the PHP script in your web browser: <a href="http://localhost/index.php"><strong><em>http://localhost/index.php</em></strong></a></p><h3>Key Lessons Learned</h3><h4><strong>1. Security First</strong></h4><p>Never skip the <strong><em>mysql_secure_installation</em></strong> step. I&#39;ve seen too many developers rush through setup only to face security issues later.</p><h4>2. Extension Planning</h4><p>Install PHP extensions based on your project needs upfront. Adding them later can cause compatibility issues.</p><h4>3. Firewall Configuration</h4><p>Properly configure UFW from the beginning. It’s easier to start secure and open ports as needed than to retrofit security.</p><h4>4. Documentation</h4><p>Keep track of passwords, database names, and user accounts. Consider using a password manager for generated credentials.</p><h3>Common Pitfalls to Avoid</h3><ul><li><strong>Skipping system updates</strong>: Always start with <strong><em>apt update &amp;&amp; apt upgrade</em></strong></li><li><strong>Weak passwords</strong>: Use generated passwords with sufficient complexity</li><li><strong>Leaving test files</strong>: Remove phpinfo.php and other test files in production</li><li><strong>Ignoring logs</strong>: Check <strong><em>/var/log/apache2/</em></strong> and <strong><em>/var/log/mysql/ </em></strong>for issues</li><li><strong>Default configurations</strong>: Customize configurations for your specific use case</li></ul><h3>Next Steps</h3><p>With your LAMP stack running, consider these enhancements:</p><ul><li><strong>SSL/TLS certificates</strong> for HTTPS</li><li><strong>Virtual hosts</strong> for multiple sites</li><li><strong>PHP-FPM</strong> for better performance</li><li><strong>Database optimization</strong> and backup strategies</li><li><strong>Monitoring tools</strong> like htop or netdata</li></ul><h3>Conclusion</h3><p>Setting up a LAMP stack might seem straightforward, but doing it correctly requires attention to security, performance, and maintainability. The time invested in proper setup pays dividends in reduced debugging and enhanced security.</p><p>This foundation provides a robust platform for PHP web development, whether you’re building a simple blog or a complex web application. The key is understanding not just the “how” but the “why” behind each configuration choice.</p><p><strong><em>Have you set up a LAMP stack recently? What challenges did you encounter? Share your experiences in the comments below.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402527ff79aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a CSV Import/Export Feature in Laravel 10: Step-by-Step Guide with No External Packages]]></title>
            <link>https://medium.com/@kanishkanuwanperera/building-a-csv-import-export-feature-in-laravel-10-step-by-step-guide-with-no-external-packages-6b73295aa0c1?source=rss-3b73ede655f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b73295aa0c1</guid>
            <category><![CDATA[laravel-10]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[csv-import]]></category>
            <category><![CDATA[import-export]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Kanishka Perera]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 04:46:53 GMT</pubDate>
            <atom:updated>2024-02-24T04:46:53.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*S3uj-615za0OUlEdPD3QbQ.png" /></figure><h3>Introduction</h3><p>In today’s data-driven world, the ability to seamlessly import and export data in CSV format is a fundamental requirement for many web applications. While there are numerous packages available in Laravel for CSV handling, there are some cases where a customised method is required. Join us as we explore CSV manipulation in Laravel and discover how to create a custom solution that properly meets the application’s requirements.</p><p>In this article, we’ll embark on a journey to develop a robust CSV import/export feature in Laravel without relying on any <strong>third-party packages</strong>. We’ll explore how to handle various data types, including <strong>long text, numbers, and JSON,</strong> ensuring that our solution is capable of accommodating diverse datasets. Additionally, we’ll address common challenges such as managing <strong>memory usage</strong>, handling <strong>values with commas</strong>, and maintaining data integrity throughout the process.</p><p><strong>Step 1: Install Laravel Project</strong></p><p>If you’re starting from scratch, you can create a new Laravel project by opening your terminal and running this command:</p><pre>composer create-project laravel/laravel custom-csv-import-export-app</pre><p>This command sets up a fresh Laravel project named “custom-csv-import-export-app” for you. If you already have a Laravel project, you can skip this step and proceed to the next one.</p><p><strong>Step 2: Generating Migration and Model</strong></p><p>To manage our employee data effectively, we’ll need a database table and a corresponding model in our Laravel project. Let’s generate these files using the artisan command:</p><pre># Generate a model and a migration, factory, seeder, and controller...<br>php artisan make:model Employee -mfsc</pre><p>This command generates several files for us:</p><ul><li>Migration file (database/migrations/yyyy_mm_dd_create_employees_table.php): defines the structure of the employees table in our database.</li><li>Model file (app/Models/Employee.php): represents the Employee model and allows us to interact with the employees table.</li><li>Factory file (database/factories/EmployeeFactory.php): helps us generate fake data for testing purposes.</li><li>Seeder file (database/seeders/EmployeeSeeder.php): populates the employees table with fake data using the factory.</li><li>Controller file (app/Http/Controllers/EmployeeController.php): handles HTTP requests related to employee data, including CSV import/export functionality.</li></ul><p>These files provide a solid foundation for building our CSV import/export feature while also facilitating the generation of fake employee data for testing.</p><p>Let’s set up the employee fields in the migration file.</p><p><em>app\database\migrations\20##_##_##_######_create_employees_table.php</em></p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br><br>    public function up(): void<br>    {<br>        Schema::create(&#39;employees&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;first_name&#39;);<br>            $table-&gt;string(&#39;last_name&#39;);<br>            $table-&gt;string(&#39;email&#39;)-&gt;unique();<br>            $table-&gt;string(&#39;phone&#39;)-&gt;nullable();<br>            $table-&gt;date(&#39;date_of_birth&#39;)-&gt;nullable();<br>            $table-&gt;enum(&#39;gender&#39;, [&#39;male&#39;, &#39;female&#39;, &#39;other&#39;])-&gt;nullable();<br>            $table-&gt;text(&#39;address&#39;)-&gt;nullable();<br>            $table-&gt;text(&#39;skills&#39;)-&gt;nullable();<br>            $table-&gt;decimal(&#39;basic_salary&#39;, 10, 2)-&gt;nullable();<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;employees&#39;);<br>    }<br>};</pre><p>This migration file indicates that we have the necessary structure to store employee data efficiently. The use of various data types like strings, dates, enums, texts, and decimals accommodates different types of information typically associated with employees.</p><p>The $fillable property in the model specifies which attributes are allowed to be mass-assigned.</p><p><em>app\Models\Employee.php</em></p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Employee extends Model<br>{<br>    use HasFactory;<br><br>    protected $fillable = [<br>        &#39;first_name&#39;,<br>        &#39;last_name&#39;,<br>        &#39;email&#39;,<br>        &#39;phone&#39;,<br>        &#39;date_of_birth&#39;,<br>        &#39;gender&#39;,<br>        &#39;address&#39;,<br>        &#39;basic_salary&#39;,<br>    ];<br>}</pre><p>The following command will create the employees database table based on the migration file you defined earlier.</p><pre>php artisan migrate</pre><h3>Export CSV files</h3><p><strong>Step 3: Make CSV export function in the controller</strong></p><p><em>app\Http\Controllers\EmployeeController.php</em></p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Models\Employee;<br>use Illuminate\Http\Request;<br><br>class EmployeeController extends Controller<br>{<br>    public function index()<br>    {<br>        $employees = Employee::paginate(10);<br>        return view(&#39;index&#39;, compact(&#39;employees&#39;));<br>    }<br><br>    public function exportCSV()<br>    {<br>        $filename = &#39;employee-data.csv&#39;;<br>    <br>        $headers = [<br>            &#39;Content-Type&#39; =&gt; &#39;text/csv&#39;,<br>            &#39;Content-Disposition&#39; =&gt; &quot;attachment; filename=\&quot;$filename\&quot;&quot;,<br>            &#39;Pragma&#39; =&gt; &#39;no-cache&#39;,<br>            &#39;Cache-Control&#39; =&gt; &#39;must-revalidate, post-check=0, pre-check=0&#39;,<br>            &#39;Expires&#39; =&gt; &#39;0&#39;,<br>        ];<br>    <br>        return response()-&gt;stream(function () {<br>            $handle = fopen(&#39;php://output&#39;, &#39;w&#39;);<br>    <br>            // Add CSV headers<br>            fputcsv($handle, [<br>                &#39;First Name&#39;,<br>                &#39;Last Name&#39;,<br>                &#39;Email&#39;,<br>                &#39;Phone Number&#39;,<br>                &#39;Date of Birth&#39;,<br>                &#39;Gender&#39;,<br>                &#39;Address&#39;,<br>                &#39;Salary&#39;,<br>                &#39;Skills&#39;<br>            ]);<br>    <br>             // Fetch and process data in chunks<br>            Employee::chunk(25, function ($employees) use ($handle) {<br>                foreach ($employees as $employee) {<br>             // Extract data from each employee.<br>                    $data = [<br>                        isset($employee-&gt;first_name)? $employee-&gt;first_name : &#39;&#39;,<br>                        isset($employee-&gt;last_name)? $employee-&gt;last_name : &#39;&#39;,<br>                        isset($employee-&gt;email)? $employee-&gt;email : &#39;&#39;,<br>                        isset($employee-&gt;phone)? $employee-&gt;phone : &#39;&#39;,<br>                        isset($employee-&gt;date_of_birth)? $employee-&gt;date_of_birth : &#39;&#39;,<br>                        isset($employee-&gt;gender)? $employee-&gt;gender : &#39;&#39;,<br>                        isset($employee-&gt;address)? $employee-&gt;address : &#39;&#39;,<br>                        isset($employee-&gt;basic_salary)? $employee-&gt;basic_salary : &#39;&#39;,<br>                        isset($employee-&gt;skills)? implode(&quot;, &quot;, json_decode($employee-&gt;skills)) : &#39;&#39;,<br>                    ];<br>    <br>             // Write data to a CSV file.<br>                    fputcsv($handle, $data);<br>                }<br>            });<br>    <br>            // Close CSV file handle<br>            fclose($handle);<br>        }, 200, $headers);<br>    }<br><br>    <br>    <br><br>}</pre><p>The exportCSV function in the EmployeeController is set up to export employee data to a CSV file. It first sets up the necessary headers for a CSV response, then streams the employee data in chunks to prevent memory issues.</p><p><strong>Step 4: Create Routes</strong></p><p><em>routes\web.php</em></p><pre>&lt;?php<br><br>use App\Http\Controllers\EmployeeController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});<br>Route::resource(&#39;employee&#39;, EmployeeController::class);<br>Route::get(&#39;export-csv&#39;, [EmployeeController::class, &#39;exportCSV&#39;])-&gt;name(&#39;export&#39;);<br>Route::post(&#39;import-csv&#39;, [EmployeeController::class, &#39;importCSV&#39;])-&gt;name(&#39;import&#39;);</pre><p><strong>Step 5: Create the index blade</strong></p><p><em>resources\views\index.blade.php</em></p><pre>&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;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; <br>        integrity=&quot;sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js&quot; <br>        integrity=&quot;sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>    &lt;style&gt;<br>        /* Your custom CSS styles go here */<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;table class=&quot;rwd-table&quot;&gt;<br>            &lt;thead&gt;<br>                &lt;th colspan=&quot;8&quot;&gt;<br>                    &lt;a href=&quot;{{ route(&#39;export&#39;) }}&quot; class=&quot;btn btn-success&quot;&gt;Export CSV&lt;/a&gt;<br>                &lt;/th&gt;<br>            &lt;/thead&gt;<br>            &lt;tbody&gt;<br>                &lt;tr&gt;<br>                &lt;th&gt;first name&lt;/th&gt;<br>                &lt;th&gt;last name&lt;/th&gt;<br>                &lt;th&gt;email&lt;/th&gt;<br>                &lt;th&gt;phone no.&lt;/th&gt;<br>                &lt;th&gt;date of birth&lt;/th&gt;<br>                &lt;th&gt;gender&lt;/th&gt;<br>                &lt;th&gt;skills&lt;/th&gt;<br>                &lt;th&gt;basic salary&lt;/th&gt;<br>                &lt;/tr&gt;<br>                <br>                @foreach ($employees as $list)<br>                &lt;tr&gt;<br>                    &lt;td&gt;{{ $list-&gt;first_name }}&lt;/td&gt;<br>                    &lt;td&gt;{{ $list-&gt;last_name }}&lt;/td&gt;<br>                    &lt;td&gt;{{ $list-&gt;email }}&lt;/td&gt;<br>                    &lt;td&gt;{{ $list-&gt;phone }}&lt;/td&gt;<br>                    &lt;td&gt;{{ $list-&gt;date_of_birth }}&lt;/td&gt;<br>                    &lt;td&gt;{{ $list-&gt;gender }}&lt;/td&gt;<br>                    &lt;td&gt;<br>                        &lt;ul&gt;<br>                            @foreach (json_decode($list-&gt;skills) as $skills)<br>                                &lt;li&gt;<br>                                    {{ $skills }}<br>                                &lt;/li&gt;<br>                            @endforeach<br>                        &lt;/ul&gt;<br>                    &lt;/td&gt;<br>                    &lt;td&gt;{{ $list-&gt;basic_salary }}&lt;/td&gt;<br>                &lt;/tr&gt;<br>                @endforeach<br>            &lt;/tbody&gt;<br>        &lt;/table&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBCtLlsARByo9ymK9vgM2Q.png" /><figcaption>index.blade.php</figcaption></figure><p>The index.blade.php file renders a table to display employee data fetched from the database. It includes a button to export the data to a CSV file, which triggers the exportCSV function in the EmployeeController.</p><h3>Import CSV file</h3><p><strong>Step 6: Make CSV import function in the controller</strong></p><p><em>app\Http\Controllers\EmployeeController.php</em></p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Models\Employee;<br>use Illuminate\Http\Request;<br><br>class EmployeeController extends Controller<br>{<br><br>    public function importCSV(Request $request)<br>    {<br>        $request-&gt;validate([<br>            &#39;import_csv&#39; =&gt; &#39;required|mimes:csv&#39;,<br>        ]);<br>        //read csv file and skip data<br>        $file = $request-&gt;file(&#39;import_csv&#39;);<br>        $handle = fopen($file-&gt;path(), &#39;r&#39;);<br><br>        //skip the header row<br>        fgetcsv($handle);<br><br>        $chunksize = 25;<br>        while(!feof($handle))<br>        {<br>            $chunkdata = [];<br><br>            for($i = 0; $i&lt;$chunksize; $i++)<br>            {<br>                $data = fgetcsv($handle);<br>                if($data === false)<br>                {<br>                    break;<br>                }<br>                $chunkdata[] = $data; <br>            }<br><br>            $this-&gt;getchunkdata($chunkdata);<br>        }<br>        fclose($handle);<br><br>        return redirect()-&gt;route(&#39;employee.create&#39;)-&gt;with(&#39;success&#39;, &#39;Data has been added successfully.&#39;);<br>    }<br><br>    public function getchunkdata($chunkdata)<br>    {<br>        foreach($chunkdata as $column){<br>            $firstname = $column[0];<br>            $lastname = $column[1];<br>            $email = $column[2];<br>            $phoneNumber = $column[3];<br>            $dateOfBirth = $column[4];<br>            $gender = $column[5];<br>            $address = $column[6];<br>            $skill = json_encode([$column[7]]);<br>            $sallary = $column[8];<br><br>            //create new employee<br>            $employee = new Employee();<br>            $employee-&gt;first_name = $firstname;<br>            $employee-&gt;last_name = $lastname;<br>            $employee-&gt;email = $email;<br>            $employee-&gt;phone = $phoneNumber;<br>            $employee-&gt;date_of_birth = $dateOfBirth;<br>            $employee-&gt;gender = $gender;<br>            $employee-&gt;address = $address;<br>            $employee-&gt;skills = $skill;<br>            $employee-&gt;basic_salary = $sallary;<br>            $employee-&gt;save();<br>        }<br>    }<br><br>}</pre><p>The importCSV function reads the uploaded CSV file, skips the header row, and processes the data in chunks to avoid memory issues. It then calls the getchunkdata function to save each chunk of data to the database as Employee records.</p><p><strong>Step 7: Make the import blade file</strong></p><p>Now that we’ve implemented the CSV import functionality in our Laravel application, let’s provide a seamless experience for users to upload their CSV files. We’ll create a dedicated view for the import feature.</p><p><em>resources\views\csvimport.blade.php</em></p><pre>&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;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; <br>        integrity=&quot;sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js&quot; <br>        integrity=&quot;sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>    &lt;style&gt;<br>        /* Your custom CSS styles go here */<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div&gt;<br>            &lt;form action=&quot;{{ route(&#39;import&#39;) }}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>                @csrf<br>                &lt;div class=&quot;messages&quot;&gt;<br>                  @if (session(&#39;success&#39;))<br>                    &lt;div class=&quot;alert alert-success&quot;&gt;<br>                      {{ session(&#39;success&#39;) }}<br>                    &lt;/div&gt;<br>                  @endif<br>                &lt;/div&gt;<br>                &lt;div class=&quot;fields&quot;&gt;<br>                    &lt;div class=&quot;input-group mb-3&quot;&gt;<br>                        &lt;input type=&quot;file&quot; class=&quot;form-control&quot; id=&quot;import_csv&quot; name=&quot;import_csv&quot; accept=&quot;.csv&quot;&gt;<br>                        &lt;label class=&quot;input-group-text&quot; for=&quot;import_csv&quot;&gt;Upload&lt;/label&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;button type=&quot;submit&quot; class=&quot;btn btn-success&quot;&gt;Import CSV&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc03PP8nHSG_3IK_vHM1SQ.png" /></figure><p>Upon successful import, any relevant feedback or success messages are displayed.</p><h3>Conclusion</h3><p>To conclude, in this tutorial, we’ve covered the entire process of creating a custom CSV import and export functionality in a Laravel application. We started by setting up the necessary database structure using migrations and models. Then, we implemented the export feature to allow users to download employee data in CSV format. Next, we developed the import functionality, enabling users to upload CSV files containing employee data and import it into the database.</p><p>Throughout the tutorial, we addressed various considerations, such as handling different data types, managing memory usage by processing data in chunks, and ensuring data integrity during import. By following these steps, you’ve gained valuable insights into working with CSV files in Laravel and have the tools to implement similar features in your own projects.</p><p>Feel free to explore further enhancements, such as adding validation, error handling, or additional features to suit your specific requirements. With this knowledge, you’re well-equipped to tackle CSV import and export tasks in your Laravel applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b73295aa0c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Image Uploads with all CRUD Operations in Laravel 10]]></title>
            <link>https://medium.com/@kanishkanuwanperera/multiple-image-uploads-with-all-crud-operations-in-laravel-10-153257909a45?source=rss-3b73ede655f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/153257909a45</guid>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[image-uploading]]></category>
            <category><![CDATA[multiple-images]]></category>
            <category><![CDATA[laravel-10]]></category>
            <dc:creator><![CDATA[Kanishka Perera]]></dc:creator>
            <pubDate>Sat, 06 May 2023 07:40:51 GMT</pubDate>
            <atom:updated>2023-05-06T08:24:06.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smMuqr3ebOG7Q-HlaC5Ptg.png" /></figure><p>In this article, we will practice multiple image uploads in Laravel 10 with all CRUD operations. Not only supporting image input, but also other input formats like numbers, text, integers, etc. in a single form. This case is mostly applicable to eCommerce websites that add product details with multiple images. In this article, you will learn how to handle eCommerce’s most useful scenario view file to edit and delete options.</p><p>Let’s learn this step by step.</p><p><strong>Step 1: Install Laravel 10</strong></p><pre>composer create-project laravel/laravel ecommerce</pre><p>Ignore this step if you have a Laravel project already. If you want to start a fresh Laravel project, you might need to go back to step 1 and provide the command to start a new project using your project name. Substitute the name of your project for “ecommerce.”</p><p>Then launch the code editor of your choice.</p><p><strong>Step 2: Create a migration and model for items</strong></p><pre>php artisan make:migration create_items_table</pre><p>We will make an “items” table at this stage. You can specify what information you wish to save in the database in this migration file.</p><p><em>database\migrations\2023_04_30_092339_create_items_table.php</em></p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    <br>    public function up()<br>    {<br>        Schema::create(&#39;items&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;text(&#39;description&#39;);<br>            $table-&gt;decimal(&#39;price&#39;, 10, 2);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    public function down()<br>    {<br>        Schema::dropIfExists(&#39;items&#39;);<br>    }<br>};</pre><p>Run the Laravel migration command at this time.</p><pre>php artisan migrate </pre><p>Next, use the command that follows to create an “item” model:</p><pre>php artisan make:model Item</pre><p><em>app\Models\Item.php</em></p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Item extends Model<br>{<br>    use HasFactory;<br><br>    protected $table = &#39;items&#39;;<br><br>    protected $fillabel = [<br>        &#39;name&#39;,<br>        &#39;description&#39;,<br>        &#39;price&#39;,<br>    ];<br>}</pre><p>The “items” table does not allow us to add multiple images. As a result, we add a new table called “images” and establish one-to-many relationships between them. Using foreign key constraints, we identify the items and their images.</p><p><strong>Step 3: Create migration and model for Images</strong></p><pre>php artisan make:migration create_images_table</pre><p>We need to specify foreign key constraints for the items table in the images table.</p><p><em>database\migrations\2023_04_30_165426_create_images_table.php</em></p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    <br>    public function up()<br>    {<br>        Schema::create(&#39;images&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;url&#39;);<br>            $table-&gt;unsignedInteger(&#39;item_id&#39;);<br>            $table-&gt;foreign(&#39;item_id&#39;)-&gt;references(&#39;id&#39;)-&gt;on(&#39;items&#39;)-&gt;onDelete(&#39;cascade&#39;)-&gt;onUpdate(&#39;cascade&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    public function down()<br>    {<br>        Schema::dropIfExists(&#39;images&#39;);<br>    }<br>};</pre><p>Run the Laravel migration command at this time.</p><pre>php artisan migrate </pre><p>Now use the following command to generate an “image” model.</p><pre>php artisan make:model Image</pre><p><em>app\Models\Image.php</em></p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Image extends Model<br>{<br>    use HasFactory;<br><br>    protected $table = &#39;images&#39;;<br><br>    protected $fillable = [<br>        &#39;url&#39;,<br>        &#39;item_id&#39;,<br>    ];<br>}</pre><p><strong>Step 4: Define relationships in model files</strong></p><p>The relationship between “items” and “images” should be linked by the functions that each model (Item, Image) creates.</p><p>The following functions can be added to each model: You can also change the names of functions.</p><p><em>app\Models\Item.php</em></p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Item extends Model<br>{<br>    use HasFactory;<br><br>    protected $table = &#39;items&#39;;<br><br>    protected $fillabel = [<br>        &#39;name&#39;,<br>        &#39;description&#39;,<br>        &#39;price&#39;,<br>    ];<br><br>    public function uploadImage()<br>    {<br>        return $this-&gt;hasMany(Image::class, &#39;item_id&#39;, &#39;id&#39;);<br>    }<br>}</pre><p><em>app\Models\Image.php</em></p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Image extends Model<br>{<br>    use HasFactory;<br><br>    protected $table = &#39;images&#39;;<br><br>    protected $fillable = [<br>        &#39;url&#39;,<br>        &#39;item_id&#39;,<br>    ];<br><br>    public function item()<br>    {<br>        return $this-&gt;belongsTo(Item::class);<br>    }<br>}</pre><p><strong>Step 5: Create the controller</strong></p><p>In this stage, we will develop an item controller to handle all tedious tasks. All crud operations could be easily managed by building a resource controller.</p><p>To construct the controller, execute the following command right away:</p><pre>php artisan make:controller ItemController -r</pre><p><strong>Step 6: Create new data</strong></p><p>To insert item details and multiple images of the item, first fulfill the “store” function in the controller as shown below. To view the blade file, you can modify the “create” function.</p><p><em>app\Http\Controllers\ItemController.php</em></p><pre>public function create()<br>    {<br>        return view(&#39;create&#39;);<br>    }<br><br><br><br>public function store(Request $request)<br>    {<br>        $request-&gt;validate([<br>            &#39;name&#39; =&gt; &#39;required&#39;,<br>            &#39;description&#39; =&gt; &#39;nullable&#39;,<br>            &#39;price&#39; =&gt; &#39;required&#39;,<br>        ]);<br><br>        $item = Item::create($request-&gt;all());<br>        $itemId = $item-&gt;id;<br><br>        if($request-&gt;hasFile(&#39;images&#39;))<br>        {<br>            $uploadPath = &#39;uploads/items&#39;;<br>            $i=1;<br>            foreach($request-&gt;file(&#39;images&#39;) as $image)<br>            {<br>                $extention = $image-&gt;getClientOriginalExtention();<br>                $filename = time().$i++.&#39;.&#39;.$extention;<br>                $image-&gt;move($uploadPath,$filename);<br>                $finalImagePath = $uploadPath.$filename;<br><br>                $newimage = new Image();<br>                $newimage-&gt;url = $finalImagePath;<br>                $newimage-&gt;item_id = $itemId;<br>                $newimage-&gt;save();<br>            }<br>        }<br><br>  return redirect()-&gt;route(&#39;item.create&#39;)<br>           -&gt;with(&#39;success&#39;,&#39;Product created successfully.&#39;);<br><br>    }</pre><p>Next, make a blade file for the design form so that new records can be entered. Name the blade file something like “create.blade.php.” You can create your blade view however you want. In order to create item records for this project, I used a simple bootstrap form.</p><p>The blade file can be seen below.</p><p><em>resources\views\create.blade.php</em></p><pre>&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;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>    <br>    &lt;!-- Bootstrap CSS --&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;!-- CSRF Token --&gt;<br>    &lt;meta name=&quot;csrf-token&quot; content=&quot;{{ csrf_token() }}&quot;&gt;<br><br><br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container mt-5&quot;&gt;<br>        @if(Session::has(&#39;success&#39;))<br>            &lt;div class=&quot;alert alert-success text-center&quot;&gt;<br>                {{Session::get(&#39;success&#39;)}}<br>            &lt;/div&gt;<br>        @endif<br>        &lt;form  method=&quot;POST&quot; action=&quot;{{ route(&#39;item.store&#39;) }}&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>            @csrf<br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;Name&lt;/label&gt;<br>                &lt;input type=&quot;text&quot; class=&quot;form-control @error(&#39;name&#39;) is-invalid @enderror&quot; name=&quot;name&quot; id=&quot;name&quot; value=&quot;&quot;&gt;<br>                @error(&#39;name&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;Description&lt;/label&gt;<br>                &lt;textarea name=&quot;description&quot; class=&quot;form-control  @error(&#39;description&#39;) is-invalid @enderror&quot; id=&quot;description&quot; rows=&quot;4&quot;&gt;&lt;/textarea&gt;<br>                <br>                @error(&#39;description&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;Price&lt;/label&gt;<br>                &lt;input type=&quot;price&quot; class=&quot;form-control @error(&#39;price&#39;) is-invalid @enderror&quot; name=&quot;price&quot; id=&quot;price&quot; value=&quot;&quot;&gt;<br>                <br>                @error(&#39;price&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br>            <br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;Upload Images&lt;/label&gt;<br>                &lt;input class=&quot;form-control&quot; type=&quot;file&quot; name=&quot;images[]&quot; id=&quot;images&quot; multiple&gt;<br>                @error(&#39;images&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br>    <br>    <br>            &lt;div class=&quot;d-grid mt-3&quot;&gt;<br>              &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; class=&quot;btn btn-dark btn-block&quot;&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yElL2EAis25IvhbjSnF_wg.png" /><figcaption>create.blade.php</figcaption></figure><p><strong>Step 7: Read the inserted data</strong></p><p>Now, we want to build an index view so that users can act and verify that inputs are correctly saved. From the front end, this blade file retrieves database information. I’d like to mention that you can change the front-end design of your project. Let’s start by creating the “index.blade.php” file.</p><p><em>resources\views\index.blade.php</em></p><pre>&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;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>    &lt;!-- Bootstrap CSS --&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;!-- CSRF Token --&gt;<br>    &lt;meta name=&quot;csrf-token&quot; content=&quot;{{ csrf_token() }}&quot;&gt;<br><br><br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br><br>    &lt;/div&gt;<br><br>    @if ($message = Session::get(&#39;success&#39;))<br>        &lt;div class=&quot;alert alert-success&quot;&gt;<br>            &lt;p&gt;{{ $message }}&lt;/p&gt;<br>        &lt;/div&gt;<br>    @endif<br><br>    &lt;table class=&quot;table table-bordered&quot;&gt;<br>        &lt;tr&gt;<br>            &lt;th&gt;No&lt;/th&gt;<br>            &lt;th width=&quot;780px&quot;&gt;Name&lt;/th&gt;<br>            &lt;th&gt;Description&lt;/th&gt;<br>            &lt;th&gt;price&lt;/th&gt;<br>            &lt;th colspan=&quot;2&quot;&gt;Action&lt;/th&gt;<br>        &lt;/tr&gt;<br><br>        &lt;tr&gt;<br><br>        @foreach ($items as $item)<br><br>            &lt;td&gt;{{ $loop-&gt;iteration }}&lt;/td&gt;<br>            &lt;td&gt;{{ $item-&gt;name }}&lt;/td&gt;<br>            &lt;td&gt;{{ $item-&gt;description }}&lt;/td&gt;<br>            &lt;td&gt;{{ $item-&gt;price }}&lt;/td&gt;<br><br>            &lt;td&gt;<br>                &lt;form action=&quot;{{ route(&#39;item.destroy&#39;,$item-&gt;id) }}&quot; method=&quot;POST&quot;&gt;<br><br><br>                    &lt;a class=&quot;btn btn-primary&quot; href=&quot;{{ route(&#39;item.edit&#39;,$item-&gt;id) }}&quot;&gt;Edit&lt;/a&gt;<br><br>                    @csrf<br>                    @method(&#39;DELETE&#39;)<br><br>                    &lt;button type=&quot;submit&quot; class=&quot;btn btn-danger&quot;&gt;Delete&lt;/button&gt;<br>                &lt;/form&gt;<br><br>            &lt;/td&gt;<br><br>            <br>        &lt;/tr&gt;<br><br>        &lt;tr&gt;<br>            &lt;td colspan=&quot;6&quot;&gt;<br>            @if ($item-&gt;uploadImage)<br>                    @foreach ($item-&gt;uploadImage as $image)<br>                        &lt;a href=&quot;{{ asset($image-&gt;url) }}&quot; target=&quot;_blank&quot;&gt;<br>                            &lt;img src=&quot;{{ asset($image-&gt;url) }}&quot; alt=&quot;&quot; style=&quot;width: 80px; height: 60px;&quot;&gt;<br>                        &lt;/a&gt;<br>                    @endforeach<br>                @else<br>                    &lt;p&gt;No images available.&lt;/p&gt;<br>                @endif<br>            &lt;/td&gt;<br>        &lt;/tr&gt;<br><br>        @endforeach<br>    &lt;/table&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjx2AJ6IsItsDOwU-ei6sw.png" /><figcaption>index.blade.php</figcaption></figure><p>The “index” function in “ItemController” can then be edited. The “index” function is shown below.</p><p><em>app\Http\Controllers\ItemController.php</em></p><pre> public function index()<br>    {<br>        $items = Item::with(&#39;uploadImage&#39;)-&gt;get();<br>        return view(&#39;index&#39;,compact(&#39;items&#39;));<br>    }</pre><p><strong>Step 8: Update the inserted data</strong></p><p>Would you like to set it up with edit permission so that values can be changed? Next, you need the code listed below.</p><p>The “edit” blade file is shown here. Create your edit view accordingly in Laravel 10.</p><p><em>resources\views\edit.blade.php</em></p><pre>&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;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>    &lt;!-- Bootstrap CSS --&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;!-- CSRF Token --&gt;<br>    &lt;meta name=&quot;csrf-token&quot; content=&quot;{{ csrf_token() }}&quot;&gt;<br><br><br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container mt-5&quot;&gt;<br>        @if(Session::has(&#39;success&#39;))<br>            &lt;div class=&quot;alert alert-success text-center&quot;&gt;<br>                {{Session::get(&#39;success&#39;)}}<br>            &lt;/div&gt;<br>        @endif<br>        &lt;form  method=&quot;POST&quot; action=&quot;{{ route(&#39;item.update&#39;, $item-&gt;id) }}&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>            @csrf<br>            @method(&#39;PUT&#39;)<br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;&lt;b&gt;Name&lt;/b&gt;&lt;/label&gt;<br>                &lt;input type=&quot;text&quot; class=&quot;form-control @error(&#39;name&#39;) is-invalid @enderror&quot; name=&quot;name&quot; id=&quot;name&quot; value=&quot;{{ $item-&gt;name }}&quot;&gt;<br>                @error(&#39;name&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;&lt;b&gt;Description&lt;/b&gt;&lt;/label&gt;<br>                &lt;textarea name=&quot;description&quot; class=&quot;form-control  @error(&#39;description&#39;) is-invalid @enderror&quot; id=&quot;description&quot; rows=&quot;4&quot;&gt;{{ $item-&gt;description }}&lt;/textarea&gt;<br><br>                @error(&#39;description&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;&lt;b&gt;Price&lt;/b&gt;&lt;/label&gt;<br>                &lt;input type=&quot;price&quot; class=&quot;form-control @error(&#39;price&#39;) is-invalid @enderror&quot; name=&quot;price&quot; id=&quot;price&quot; value=&quot;{{ $item-&gt;price }}&quot;&gt;<br><br>                @error(&#39;price&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;&lt;b&gt;Uploaded Images&lt;/b&gt;&lt;/label&gt;<br>                @if($item-&gt;uploadImage)<br>                    @foreach($item-&gt;uploadImage as $image)<br><br>                            &lt;img src=&quot;{{ asset($image-&gt;url) }}&quot; width=&quot;100&quot; height=&quot;100&quot; alt=&quot;&quot;&gt;<br>                            &lt;a href=&quot;{{ route(&#39;image.delete&#39;,$image-&gt;id) }}&quot; class=&quot;btn btn-danger btn-sm ml-2&quot;&gt;Delete&lt;/a&gt;<br>                        <br>                    @endforeach<br>                @endif<br>            &lt;/div&gt;&lt;br&gt;<br><br>            &lt;div class=&quot;form-group mb-2&quot;&gt;<br>                &lt;label&gt;&lt;b&gt;Upload Images&lt;/b&gt;&lt;/label&gt;<br>                &lt;input class=&quot;form-control&quot; type=&quot;file&quot; name=&quot;images[]&quot; id=&quot;images&quot; multiple&gt;<br>                @error(&#39;images&#39;)<br>                    &lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                        &lt;strong&gt;{{ $message }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                @enderror<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;d-grid mt-3&quot;&gt;<br>              &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; class=&quot;btn btn-dark btn-block&quot;&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRfZXMZ0NCV5nI5FbhbNtQ.png" /><figcaption>edit.blade.php</figcaption></figure><p>The “update” and “edit” functions in “ItemController” must be edited. The code is displayed below.</p><p><em>app\Http\Controllers\ItemController.php</em></p><pre>public function edit(Item $item): View<br>    {<br>        return view(&#39;edit&#39;,compact(&#39;item&#39;));<br>    }<br><br> <br>    public function update(Request $request, Item $item)<br>    {<br>        $request-&gt;validate([<br>            &#39;name&#39; =&gt; &#39;nullable&#39;,<br>            &#39;description&#39; =&gt; &#39;nullable&#39;,<br>            &#39;price&#39; =&gt; &#39;nullable&#39;,<br><br>        ]);<br><br>        $item-&gt;update($request-&gt;all());<br><br>        return redirect()-&gt;route(&#39;item.index&#39;)<br>                        -&gt;with(&#39;success&#39;,&#39;Successfully Editted!&#39;);<br>    }</pre><p><strong>Step 9: Delete the inserted data</strong></p><p>Next, we’ll perform the last CRUD operation, “delete.” The “destroy” function in our controller is shown below.</p><p><em>app\Http\Controllers\ItemController.php</em></p><pre>public function destroy(Item $item)<br>    {<br>        $item-&gt;delete();<br><br>        return redirect()-&gt;route(&#39;item.index&#39;)<br>                        -&gt;with(&#39;success&#39;,&#39;Product deleted successfully&#39;);<br>    }</pre><p><strong>Step 10: Define all routes</strong></p><p>All routes are shown below at the end of this tutorial.</p><p><em>routes\web.php</em></p><pre>&lt;?php<br><br>use App\Http\Controllers\ItemController;<br>use Illuminate\Support\Facades\Route;<br><br><br>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});<br><br>Route::resource(&#39;item&#39;, ItemController::class);<br>Route::delete(&#39;/images/{id}&#39;, [ImageController::class, &#39;delete&#39;])-&gt;name(&#39;image.delete&#39;);<br><br></pre><p>Your Laravel project’s code can now be tested.</p><p>I hope it assists you in creating a Laravel application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=153257909a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>