<?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 Md Habibur Rahman on Medium]]></title>
        <description><![CDATA[Stories by Md Habibur Rahman on Medium]]></description>
        <link>https://medium.com/@habibur.rahman.0927?source=rss-8a636b976b5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RFC1u5yL45GzTtYvuRbgLQ.jpeg</url>
            <title>Stories by Md Habibur Rahman on Medium</title>
            <link>https://medium.com/@habibur.rahman.0927?source=rss-8a636b976b5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:26:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@habibur.rahman.0927/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[Most developers think “System Design” means only:]]></title>
            <link>https://medium.com/@habibur.rahman.0927/most-developers-think-system-design-means-only-0f3f38c7dccf?source=rss-8a636b976b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3f38c7dccf</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Md Habibur Rahman]]></dc:creator>
            <pubDate>Wed, 13 May 2026 06:12:54 GMT</pubDate>
            <atom:updated>2026-05-13T06:16:12.862Z</atom:updated>
            <content:encoded><![CDATA[<p>❌ Microservices<br>❌ Kubernetes<br>❌ Millions of users</p><p>But real System Design starts much earlier.</p><p>It starts when you ask questions like:</p><p>→ Why is this API becoming slow?<br>→ Why does the database crash under load?<br>→ Why does one small bug affect the whole system?<br>→ Why can’t the app scale easily?</p><p>That’s where engineering actually begins.</p><p>A good engineer doesn’t only write code.<br>A good engineer designs systems that survive growth.</p><p>Even a simple food delivery app can teach you:</p><p>• Caching<br>• Queue systems<br>• Load balancing<br>• Database optimization<br>• Rate limiting<br>• Event-driven architecture</p><p>And the interesting part?</p><p>Most “simple apps” become complex because of scale, not features.</p><p>Instagram, Uber, Netflix — they all started simple.</p><p>The difference is: their architecture evolved before the problems became disasters.</p><p>Right now I’m diving deeper into: ⚡ Scalability<br>⚡ Distributed Systems<br>⚡ High-Level Architecture<br>⚡ Real-world backend engineering</p><p>Because writing working code is one thing.</p><p>Designing systems that keep working under pressure is another game entirely.</p><p>#SystemDesign #Backend #SoftwareEngineering #DistributedSystems #Scalability #Tech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3f38c7dccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Laravel CRUD Builder — Powerful Admin Panel & API Generator with Role & Permission Management]]></title>
            <link>https://medium.com/@habibur.rahman.0927/laravel-crud-builder-powerful-admin-panel-api-generator-with-role-permission-management-87f5bcf72e73?source=rss-8a636b976b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f5bcf72e73</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Md Habibur Rahman]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 14:33:23 GMT</pubDate>
            <atom:updated>2025-07-03T14:33:23.137Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Laravel CRUD Builder — Powerful Admin Panel &amp; API Generator with Role &amp; Permission Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUQdTUC1QxZd4TDevhMfUQ.png" /></figure><h3>🧩 Overview</h3><p>Laravel-11 CRUD Builder is a developer-first tool that generates full-featured admin panels, REST APIs, and CMS modules with a single command. It’s built on top of Laravel 11, offering seamless integration of role-based access control (RBAC), dynamic Swagger docs, multilingual support, and a powerful user interface for managing CRUD operations.</p><p>This tool empowers you to automate 80% of the repetitive work involved in Laravel backend development. From models, migrations, and repositories to front-end views and validation logic — everything is handled out of the box.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1r9CWeTUwF0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1r9CWeTUwF0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1r9CWeTUwF0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/437135e962d473f662e7612a780f908f/href">https://medium.com/media/437135e962d473f662e7612a780f908f/href</a></iframe><h3>📘 Documentation</h3><p>We’ve published <strong>complete and detailed documentation</strong> that covers:</p><ul><li>System Requirements</li><li>Installation Steps</li><li>Folder Structure</li><li>Dashboard Overview</li><li>Admin Panel Setup</li><li>User, Role, Permission Management</li><li>Language &amp; Localization</li><li>CRUD Generator</li><li>API Authentication</li><li>Swagger UI Integration</li><li>Create Action Architecture</li><li>Release Logs</li></ul><p>This documentation serves as your ultimate reference for setup, usage, and customization of the builder.</p><h3>📎 Key Highlights</h3><ul><li><strong>Laravel 11.9 + PHP 8.3 Ready</strong></li><li>One-command CRUD Generation</li><li>Role &amp; Permission Management</li><li>Dynamic API Generation + Swagger UI</li><li>Built-in Multi-language Support</li><li>Admin Panel with Export, Import, Pagination</li><li>Model Relationships and Validation Config</li><li>Modular, Clean, and Extendable Codebase</li></ul><h3>📎 Source Code + Docs</h3><p>The entire project is documented with code examples, folder permissions, Artisan command usage, API endpoints, and more.</p><p>👉 <strong>Read the full documentation and get started today!</strong></p><blockquote>Source Code: <a href="https://github.com/Habibur-Rahman0927/laravel-curd-builder-pro">https://github.com/Habibur-Rahman0927/laravel-curd-builder-pro</a></blockquote><blockquote>Source Code: <a href="https://github.com/Habibur-Rahman0927/lavavel-curd-api-builder">https://github.com/Habibur-Rahman0927/lavavel-curd-api-builder</a></blockquote><blockquote>Docs Link: <a href="https://habibur-rahman0927.github.io/laravel-curd-builder-pro-documents/">https://habibur-rahman0927.github.io/laravel-curd-builder-pro-documents/</a></blockquote><h3>📅 Release</h3><p><strong>Version 1.0</strong> — Released: <em>29th December 2024</em><br> © 2025 <strong>Habib Dev</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f5bcf72e73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern File Manager in Laravel with Folder Structures like Google Drive]]></title>
            <link>https://medium.com/@habibur.rahman.0927/building-a-modern-file-manager-in-laravel-with-folder-structures-like-google-drive-c4307fd0a1fe?source=rss-8a636b976b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4307fd0a1fe</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Md Habibur Rahman]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 16:24:01 GMT</pubDate>
            <atom:updated>2025-04-19T16:24:01.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idGdzgeCsZ5w2HR-hVjd4A.png" /></figure><p>In today’s digital world, file management is a crucial feature for many web applications. Whether you’re building a content management system, a document sharing platform, or just need robust file handling for your application, a well-structured file manager can make all the difference. In this article, I’ll walk you through building a complete file manager in Laravel with:</p><ol><li>Folder hierarchy management</li><li>File uploads and downloads</li><li>ZIP file extraction</li><li>Chunked uploads for large files</li><li>A clean, responsive UI</li></ol><h3>The Architecture</h3><p>Our file manager will have two main database tables and routes:</p><h4>1. Routes</h4><pre>Route::get(&#39;/drive&#39;, [FileManagerController::class, &#39;index&#39;])-&gt;name(&#39;drive.index&#39;);<br>Route::get(&#39;/drive/folder/{folder}&#39;, [FileManagerController::class, &#39;browseFolder&#39;])-&gt;name(&#39;drive.folder.browse&#39;);<br>Route::post(&#39;/drive/folder&#39;, [FileManagerController::class, &#39;createFolder&#39;])-&gt;name(&#39;drive.folder.create&#39;);<br>Route::put(&#39;/drive/folder/{folder}&#39;, [FileManagerController::class, &#39;renameFolder&#39;])-&gt;name(&#39;drive.folder.rename&#39;);<br>Route::delete(&#39;/drive/folder/{folder}&#39;, [FileManagerController::class, &#39;deleteFolder&#39;])-&gt;name(&#39;drive.folder.delete&#39;);<br><br>Route::post(&#39;/drive/upload&#39;, [FileManagerController::class, &#39;uploadFile&#39;])-&gt;name(&#39;drive.upload&#39;);<br>Route::get(&#39;/drive/download/{file}&#39;, [FileManagerController::class, &#39;downloadFile&#39;])-&gt;name(&#39;drive.download&#39;);<br>Route::get(&#39;/drive/folder/{folder}/download&#39;, [FileManagerController::class, &#39;downloadFolder&#39;])-&gt;name(&#39;drive.folder.download&#39;);<br>Route::delete(&#39;/drive/file/{file}&#39;, [FileManagerController::class, &#39;deleteFile&#39;])-&gt;name(&#39;drive.file.delete&#39;);<br><br>Route::post(&#39;/drive/large-file-upload&#39;, [FileManagerController::class, &#39;largeFileUpload&#39;])-&gt;name(&#39;drive.large.fileUpload&#39;);<br>Route::post(&#39;/drive/chunked-upload&#39;, [FileManagerController::class, &#39;uploadChunk&#39;]);<br>Route::post(&#39;/drive/finalize-upload&#39;, [FileManagerController::class, &#39;finalizeUpload&#39;]);</pre><h4>2. Folders Table</h4><pre>Schema::create(&#39;folders&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;name&#39;, 255);<br>    $table-&gt;foreignId(&#39;user_id&#39;)-&gt;nullable()-&gt;constrained(&#39;users&#39;);<br>    $table-&gt;foreignId(&#39;parent_id&#39;)-&gt;nullable()-&gt;constrained(&#39;folders&#39;);<br>    $table-&gt;timestamps();<br>});</pre><h4>3. Files Table</h4><pre>Schema::create(&#39;files&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;original_name&#39;);<br>    $table-&gt;string(&#39;file_path&#39;);<br>    $table-&gt;foreignId(&#39;folder_id&#39;)-&gt;nullable()-&gt;constrained(&#39;folders&#39;);<br>    $table-&gt;foreignId(&#39;user_id&#39;)-&gt;nullable()-&gt;constrained(&#39;users&#39;);<br>    $table-&gt;timestamps();<br>});</pre><h4>4. Models and Relations</h4><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\BelongsTo;<br><br>class Folder extends Model<br>{<br> /**<br>  * The attributes that are mass assignable.<br>  *<br>  * @var array<br>  */<br> protected $fillable = [<br>  &#39;name&#39;,<br>  &#39;user_id&#39;,<br>  &#39;parent_id&#39;<br> ];<br><br>    public function children() {<br>        return $this-&gt;hasMany(Folder::class, &#39;parent_id&#39;);<br>    }<br><br>    public function parent() {<br>        return $this-&gt;belongsTo(Folder::class, &#39;parent_id&#39;);<br>    }<br><br>   public function user(): BelongsTo<br>   {<br>    return $this-&gt;belongsTo(User::class, &#39;user_id&#39;);<br>   }<br><br>    public function files() {<br>        return $this-&gt;hasMany(File::class);<br>    }<br>}<br><br>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\BelongsTo;<br><br>class File extends Model<br>{<br> /**<br>  * The attributes that are mass assignable.<br>  *<br>  * @var array<br>  */<br> protected $fillable = [<br>  &#39;original_name&#39;,<br>  &#39;file_path&#39;,<br>  &#39;folder_id&#39;,<br>  &#39;user_id&#39;<br> ];<br><br> /**<br>  * Define a BelongsTo relationship.<br>  *<br>  * @return BelongsTo<br>  */<br> public function folder(): BelongsTo<br> {<br>  return $this-&gt;belongsTo(Folder::class, &#39;folder_id&#39;);<br> }<br><br> /**<br>  * Define a BelongsTo relationship.<br>  *<br>  * @return BelongsTo<br>  */<br> public function user(): BelongsTo<br> {<br>  return $this-&gt;belongsTo(User::class, &#39;user_id&#39;);<br> }<br>}</pre><p>This structure allows for:</p><ul><li>Nested folder hierarchies (through the parent_id self-referential relationship)</li><li>File organization within folders</li><li>User ownership of files and folders</li></ul><h3>Core Features Implementation</h3><h4>1. Folder Management</h4><p>The controller handles all folder operations:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Admin;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\File;<br>use App\Models\Folder;<br>use Exception;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Auth;<br>use Illuminate\Support\Facades\DB;<br>use Illuminate\Support\Facades\Storage;<br>use ZipArchive;<br>use Illuminate\Support\Str;<br><br>class FileManagerController extends Controller<br>{<br><br>    public function index()<br>    {<br>        return $this-&gt;browseFolder(null);<br>    }<br><br>    public function browseFolder($id = null)<br>    {<br>        $folders = Folder::where(&#39;parent_id&#39;, $id)-&gt;get();<br>        $files = File::where(&#39;folder_id&#39;, $id)-&gt;get();<br><br>        $currentFolder = $id ? Folder::findOrFail($id) : null;<br>        $breadcrumbs = $this-&gt;getBreadcrumbs($currentFolder);<br><br>        return view(&#39;admin.drive.index&#39;, compact(&#39;folders&#39;, &#39;files&#39;, &#39;currentFolder&#39;, &#39;breadcrumbs&#39;));<br>    }<br><br>    protected function getBreadcrumbs($folder)<br>    {<br>        $breadcrumbs = [];<br>        while ($folder) {<br>            array_unshift($breadcrumbs, $folder);<br>            $folder = $folder-&gt;parent;<br>        }<br>        return $breadcrumbs;<br>    }<br><br>    public function createFolder(Request $request)<br>    {<br>        $request-&gt;validate([&#39;name&#39; =&gt; &#39;required|string&#39;]);<br><br>        Folder::create([<br>            &#39;name&#39; =&gt; $request-&gt;name,<br>            &#39;parent_id&#39; =&gt; $request-&gt;parent_id,<br>            &#39;user_id&#39; =&gt; Auth::id(),<br>        ]);<br><br>        return back()-&gt;with(&#39;success&#39;, &#39;Folder created&#39;);<br>    }<br><br>    public function renameFolder(Request $request, Folder $folder)<br>    {<br>        $folder-&gt;update([&#39;name&#39; =&gt; $request-&gt;name]);<br>        return back()-&gt;with(&#39;success&#39;, &#39;Folder renamed&#39;);<br>    }<br><br>    public function deleteFolder(Folder $folder)<br>    {<br>        try {<br>            // Start a database transaction<br>            DB::beginTransaction();<br><br>            // Recursively delete all contents<br>            $this-&gt;deleteFolderContents($folder);<br><br>            // Delete the folder record itself<br>            $folder-&gt;delete();<br><br>            // Commit the transaction<br>            DB::commit();<br><br>            return back()-&gt;with(&#39;success&#39;, &#39;Folder and all its contents deleted successfully&#39;);<br>        } catch (\Exception $e) {<br>            // Rollback on error<br>            DB::rollBack();<br><br>            return back()-&gt;with(&#39;error&#39;, &#39;Failed to delete folder: &#39; . $e-&gt;getMessage());<br>        }<br>    }<br><br>    protected function deleteFolderContents(Folder $folder)<br>    {<br>        // Delete all files in this folder<br>        foreach ($folder-&gt;files as $file) {<br>            try {<br>                // Delete physical file<br>                if (Storage::exists($file-&gt;file_path)) {<br>                    Storage::delete($file-&gt;file_path);<br>                }<br><br>                // Delete file record<br>                $file-&gt;delete();<br>            } catch (\Exception $e) {<br>                throw $e;<br>            }<br>        }<br><br>        // Recursively delete subfolders<br>        foreach ($folder-&gt;children as $subfolder) {<br>            $this-&gt;deleteFolderContents($subfolder); // Delete subfolder contents first<br>            $subfolder-&gt;delete(); // Then delete the subfolder itself<br>        }<br>    }<br><br>    public function deleteFile(File $file)<br>    {<br>        $file-&gt;delete();<br>        return back()-&gt;with(&#39;success&#39;, &#39;File deleted&#39;);<br>    }<br><br>    public function downloadFile(File $file)<br>    {<br>        return Storage::disk(&#39;public&#39;)-&gt;download(<br>            str_replace(&#39;public/&#39;, &#39;&#39;, $file-&gt;file_path),<br>            $file-&gt;original_name<br>        );<br>    }<br><br>    public function uploadFile(Request $request)<br>    {<br>        $request-&gt;validate([<br>            &#39;file.*&#39; =&gt; &#39;required|file|max:20480&#39;, // 20MB max per file<br>        ]);<br><br>        $uploadedFiles = [];<br>        $folderId = $request-&gt;folder_id;<br>        $userId = Auth::id();<br><br>        foreach ((array) $request-&gt;file(&#39;file&#39;) as $file) {<br>            try {<br>                $originalName = $file-&gt;getClientOriginalName();<br>                $extension = $file-&gt;getClientOriginalExtension();<br>                $filename = pathinfo($originalName, PATHINFO_FILENAME);<br>                $safeName = Str::slug($filename) . &#39;-&#39; . uniqid() . &#39;.&#39; . $extension;<br><br>                $path = $file-&gt;storeAs(<br>                    &#39;user_uploads/&#39; . $userId . &#39;/&#39; . ($folderId ?: &#39;root&#39;),<br>                    $safeName,<br>                    &#39;public&#39;<br>                );<br><br>                if (strtolower($extension) === &#39;zip&#39;) {<br>                    $this-&gt;extractZipFile(storage_path(&#39;app/public/&#39; . $path), $userId, $folderId);<br>                }<br><br>                $uploadedFiles[] = File::create([<br>                    &#39;original_name&#39; =&gt; $originalName,<br>                    &#39;file_path&#39; =&gt; &#39;public/&#39; . $path,<br>                    &#39;public_url&#39; =&gt; Storage::disk(&#39;public&#39;)-&gt;url(https://medium.com/$path),<br>                    &#39;folder_id&#39; =&gt; $folderId,<br>                    &#39;user_id&#39; =&gt; $userId,<br>                ]);<br><br>            } catch (\Exception $e) {<br>                \Log::error(&quot;File upload failed: &quot; . $e-&gt;getMessage());<br>                continue;<br>            }<br>        }<br><br>        return back()-&gt;with(&#39;success&#39;, count($uploadedFiles) . &#39; file(s) uploaded successfully&#39;);<br>    }<br><br>    private function extractZipFile($zipPath, $userId, $parentFolderId)<br>    {<br>        $zip = new ZipArchive();<br>        if ($zip-&gt;open($zipPath) !== true) {<br>            \Log::error(&quot;Failed to open ZIP file: &quot; . $zipPath);<br>            return;<br>        }<br><br>        $extractTo = storage_path(&#39;app/public/user_uploads/&#39; . $userId . &#39;/extracted/&#39; . basename($zipPath, &#39;.zip&#39;));<br>        if (!file_exists($extractTo)) {<br>            mkdir($extractTo, 0755, true);<br>        }<br><br>        $zip-&gt;extractTo($extractTo);<br>        $zip-&gt;close();<br><br>        // Process extracted files<br>        $files = new \RecursiveIteratorIterator(<br>            new \RecursiveDirectoryIterator($extractTo),<br>            \RecursiveIteratorIterator::LEAVES_ONLY<br>        );<br><br>        foreach ($files as $file) {<br>            if ($file-&gt;isDir()) continue;<br><br>            $relativePath = substr($file-&gt;getPathname(), strlen($extractTo) + 1);<br>            $newPath = &#39;user_uploads/&#39; . $userId . &#39;/&#39; . ($parentFolderId ?: &#39;root&#39;) . &#39;/&#39; . $relativePath;<br><br>            // Ensure directory exists<br>            $newDir = dirname(storage_path(&#39;app/public/&#39; . $newPath));<br>            if (!file_exists($newDir)) {<br>                mkdir($newDir, 0755, true);<br>            }<br><br>            rename($file-&gt;getPathname(), storage_path(&#39;app/public/&#39; . $newPath));<br><br>            File::create([<br>                &#39;original_name&#39; =&gt; basename($file-&gt;getPathname()),<br>                &#39;file_path&#39; =&gt; &#39;public/&#39; . $newPath,<br>                &#39;public_url&#39; =&gt; Storage::disk(&#39;public&#39;)-&gt;url(https://medium.com/$newPath),<br>                &#39;folder_id&#39; =&gt; $parentFolderId,<br>                &#39;user_id&#39; =&gt; $userId,<br>            ]);<br>        }<br>    }<br><br>    public function downloadFolder(Folder $folder)<br>    {<br>        $zipFileName = &#39;folder_&#39; . $folder-&gt;id . &#39;_&#39; . time() . &#39;.zip&#39;;<br>        $zipPath = storage_path(&#39;app/public/temp_zips/&#39; . $zipFileName);<br><br>        // Ensure temp directory exists<br>        if (!file_exists(dirname($zipPath))) {<br>            mkdir(dirname($zipPath), 0755, true);<br>        }<br><br>        $zip = new ZipArchive();<br>        if ($zip-&gt;open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {<br>            abort(500, &#39;Could not create ZIP file&#39;);<br>        }<br><br>        // Add all content recursively from public disk<br>        $this-&gt;addFolderContentToZip($zip, $folder);<br><br>        if ($zip-&gt;numFiles === 0) {<br>            $zip-&gt;addFromString(&#39;README.txt&#39;, &#39;This folder is empty&#39;);<br>        }<br><br>        $zip-&gt;close();<br><br>        if (!file_exists($zipPath)) {<br>            abort(500, &#39;Failed to create ZIP file&#39;);<br>        }<br><br>        return response()-&gt;download($zipPath, $folder-&gt;name . &#39;.zip&#39;)<br>            -&gt;deleteFileAfterSend(true);<br>    }<br><br>    private function addFolderContentToZip(ZipArchive $zip, Folder $folder, $currentPath = &#39;&#39;)<br>    {<br>        $currentPath .= $folder-&gt;name . &#39;/&#39;;<br><br>        // Add files from this folder (using public disk)<br>        foreach ($folder-&gt;files as $file) {<br>            $relativePath = str_replace(&#39;public/&#39;, &#39;&#39;, $file-&gt;file_path);<br>            $filePath = storage_path(&#39;app/public/&#39; . $relativePath);<br><br>            if (file_exists($filePath)) {<br>                $zip-&gt;addFile($filePath, $currentPath . $file-&gt;original_name);<br>            }<br>        }<br><br>        foreach ($folder-&gt;children as $subfolder) {<br>            $this-&gt;addFolderContentToZip($zip, $subfolder, $currentPath);<br>        }<br>    }<br><br>    public function largeFileUpload()<br>    {<br>        return back()-&gt;with(&#39;success&#39;, &#39;Large file uploaded Successfully!&#39;);<br>    }<br><br>    public function uploadChunk(Request $request)<br>    {<br>        try {<br>            $request-&gt;validate([<br>                &#39;file&#39; =&gt; &#39;required|file&#39;,<br>                &#39;chunkIndex&#39; =&gt; &#39;required|numeric&#39;,<br>                &#39;totalChunks&#39; =&gt; &#39;required|numeric&#39;,<br>                &#39;uploadId&#39; =&gt; &#39;required|string&#39;,<br>                &#39;originalName&#39; =&gt; &#39;required|string&#39;,<br>                &#39;folder_id&#39; =&gt; &#39;nullable|exists:folders,id&#39;<br>            ]);<br><br>            $chunk = $request-&gt;file(&#39;file&#39;);<br>            $chunkIndex = $request-&gt;input(&#39;chunkIndex&#39;);<br>            $uploadId = $request-&gt;input(&#39;uploadId&#39;);<br><br>            $tempPath = &quot;chunks/{$uploadId}&quot;;<br>            $chunkPath = &quot;{$tempPath}/{$chunkIndex}.part&quot;;<br><br>            // Ensure directory exists<br>            Storage::disk(&#39;local&#39;)-&gt;makeDirectory($tempPath);<br><br>            // Store the chunk<br>            $chunk-&gt;storeAs($tempPath, &quot;{$chunkIndex}.part&quot;);<br><br>            return response()-&gt;json([<br>                &#39;success&#39; =&gt; true,<br>                &#39;chunkIndex&#39; =&gt; $chunkIndex<br>            ]);<br><br>        } catch (\Exception $e) {<br>            return response()-&gt;json([<br>                &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                &#39;trace&#39; =&gt; $e-&gt;getTrace()<br>            ], 500);<br>        }<br>    }<br><br>    public function finalizeUpload(Request $request)<br>    {<br>        try {<br>            $request-&gt;validate([<br>                &#39;uploadId&#39; =&gt; &#39;required|string&#39;,<br>                &#39;fileName&#39; =&gt; &#39;required|string&#39;,<br>                &#39;folder_id&#39; =&gt; &#39;nullable|exists:folders,id&#39;<br>            ]);<br><br>            $uploadId = $request-&gt;input(&#39;uploadId&#39;);<br>            $fileName = $request-&gt;input(&#39;fileName&#39;);<br>            $folderId = $request-&gt;input(&#39;folder_id&#39;);<br>            $userId = Auth::id();<br><br>            $tempPath = &quot;chunks/{$uploadId}&quot;;<br>            $finalPath = &#39;user_uploads/&#39; . $userId . &#39;/&#39; . ($folderId ?: &#39;root&#39;) . &#39;/&#39; . $fileName;<br><br>            // Get all chunks and sort them<br>            $chunks = Storage::disk(&#39;local&#39;)-&gt;files($tempPath);<br>            natsort($chunks);<br><br>            // Create final file<br>            $finalStoragePath = Storage::disk(&#39;public&#39;)-&gt;path($finalPath);<br>            Storage::disk(&#39;public&#39;)-&gt;makeDirectory(dirname($finalPath));<br><br>            $finalFile = fopen($finalStoragePath, &#39;wb&#39;);<br><br>            foreach ($chunks as $chunkPath) {<br>                $chunk = Storage::disk(&#39;local&#39;)-&gt;get($chunkPath);<br>                fwrite($finalFile, $chunk);<br>            }<br><br>            fclose($finalFile);<br><br>            // Clean up<br>            Storage::disk(&#39;local&#39;)-&gt;deleteDirectory($tempPath);<br><br>            // Create file record<br>            $file = File::create([<br>                &#39;original_name&#39; =&gt; $fileName,<br>                &#39;file_path&#39; =&gt; &#39;public/&#39; . $finalPath,<br>                &#39;folder_id&#39; =&gt; $folderId,<br>                &#39;user_id&#39; =&gt; $userId,<br>            ]);<br><br>            return response()-&gt;json([<br>                &#39;success&#39; =&gt; true,<br>                &#39;path&#39; =&gt; &#39;public/&#39; . $finalPath,<br>                &#39;file&#39; =&gt; $file<br>            ]);<br><br>        } catch (\Exception $e) {<br>            return response()-&gt;json([<br>                &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                &#39;trace&#39; =&gt; $e-&gt;getTrace()<br>            ], 500);<br>        }<br>    }<br>}</pre><h4>2. The User Interface</h4><p>The UI features:</p><ol><li><strong>Breadcrumb navigation</strong> for easy folder traversal</li><li><strong>Grid view</strong> of files and folders</li><li><strong>Context menus</strong> for each item with actions</li><li><strong>Progress indicators</strong> for uploads</li><li><strong>Responsive design</strong> that works on all devices</li></ol><pre>@extends(&#39;layouts/layout&#39;)<br><br>@section(&#39;title&#39;, __(&#39;folder_module.create_list_edit.create_page_title&#39;))<br><br>@section(&#39;page-style&#39;)<br>    @vite([<br><br>    ])<br>    &lt;style&gt;<br>        .drive-container {<br>            padding: 20px;<br>            background-color: #f5f5f5;<br>            min-height: calc(100vh - 60px);<br>        }<br>        .drive-header {<br>            display: flex;<br>            justify-content: space-between;<br>            align-items: center;<br>            padding: 10px 20px;<br>            background: white;<br>            border-radius: 8px;<br>            box-shadow: 0 1px 2px rgba(0,0,0,0.1);<br>            margin-bottom: 20px;<br>        }<br>        .drive-actions {<br>            display: flex;<br>            gap: 10px;<br>        }<br>        .drive-content {<br>            background: white;<br>            border-radius: 8px;<br>            box-shadow: 0 1px 2px rgba(0,0,0,0.1);<br>            padding: 20px;<br>        }<br>        .item-grid {<br>            display: grid;<br>            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));<br>            gap: 16px;<br>        }<br>        .drive-item {<br>            padding: 16px;<br>            border-radius: 8px;<br>            text-align: center;<br>            cursor: pointer;<br>            transition: all 0.2s;<br>            position: relative;<br>            border: 1px solid #e0e0e0;<br>            height: 160px;<br>            display: flex;<br>            flex-direction: column;<br>            align-items: center;<br>            justify-content: center;<br>        }<br>        .drive-item:hover {<br>            background-color: #f1f3f4;<br>            box-shadow: 0 1px 3px 0 rgba(60,64,67,0.302), 0 4px 8px 3px rgba(60,64,67,0.149);<br>        }<br>        .drive-item-icon {<br>            width: 80px;<br>            height: 64px;<br>            margin-bottom: 12px;<br>            display: flex;<br>            align-items: center;<br>            justify-content: center;<br>            position: relative;<br>        }<br>        .folder-icon {<br>            color: #5f6368;<br>            position: relative;<br>        }<br>        .folder-icon svg {<br>            width: 100%;<br>            height: 100%;<br>        }<br>        .file-icon {<br>            color: #5f6368;<br>            position: relative;<br>        }<br>        .file-icon svg {<br>            width: 48px;<br>            height: 64px;<br>        }<br>        .file-icon::after {<br>            content: &quot;&quot;;<br>            position: absolute;<br>            bottom: 0;<br>            left: 0;<br>            right: 0;<br>            height: 8px;<br>            background-color: #e8f0fe;<br>            border-radius: 0 0 4px 4px;<br>        }<br>        .drive-item-name {<br>            font-size: 14px;<br>            word-break: break-word;<br>            color: #202124;<br>            font-weight: 500;<br>            padding: 0 8px;<br>            width: 100%;<br>            text-align: center;<br>            display: -webkit-box;<br>            -webkit-line-clamp: 2;<br>            -webkit-box-orient: vertical;<br>            overflow: hidden;<br>            text-overflow: ellipsis;<br>        }<br>        .drive-item-actions {<br>            position: absolute;<br>            top: 8px;<br>            right: 8px;<br>            opacity: 0;<br>            transition: opacity 0.2s;<br>        }<br>        .drive-item:hover .drive-item-actions {<br>            opacity: 1;<br>        }<br>        .breadcrumb {<br>            background: none;<br>            padding: 0;<br>            margin-bottom: 20px;<br>        }<br>        .upload-btn-wrapper {<br>            position: relative;<br>            overflow: hidden;<br>            display: inline-block;<br>        }<br>        .upload-btn-wrapper input[type=file] {<br>            font-size: 100px;<br>            position: absolute;<br>            left: 0;<br>            top: 0;<br>            opacity: 0;<br>        }<br>        .search-box {<br>            max-width: 400px;<br>            margin-left: auto;<br>        }<br>        .dropdown-menu {<br>            border-radius: 8px;<br>            box-shadow: 0 2px 10px rgba(0,0,0,0.2);<br>            border: none;<br>            padding: 8px 0;<br>        }<br>        .dropdown-item {<br>            padding: 8px 16px;<br>            font-size: 14px;<br>        }<br>        .dropdown-item:hover {<br>            background-color: #f1f3f4;<br>        }<br>    &lt;/style&gt;<br>@endsection<br><br>@section(&#39;page-script&#39;)<br>    @vite([<br><br>    ])<br>@endsection<br><br>@section(&#39;content&#39;)<br>    &lt;div class=&quot;drive-container&quot;&gt;<br>        &lt;!-- Header with search and actions --&gt;<br>        &lt;div class=&quot;drive-header&quot;&gt;<br>            &lt;h2 class=&quot;page-title mb-0&quot;&gt;{{ __(&#39;folder_module.create_list_edit.create_page_title&#39;) }}&lt;/h2&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Breadcrumbs --&gt;<br>        &lt;nav aria-label=&quot;breadcrumb&quot;&gt;<br>            &lt;ol class=&quot;breadcrumb&quot;&gt;<br>                &lt;li class=&quot;breadcrumb-item&quot;&gt;&lt;a href=&quot;{{ route(&#39;drive.index&#39;) }}&quot;&gt;&lt;i class=&quot;fas fa-home&quot;&gt;&lt;/i&gt; My Drive&lt;/a&gt;&lt;/li&gt;<br>                @if($breadcrumbs ?? false)<br>                    @foreach($breadcrumbs as $crumb)<br>                        &lt;li class=&quot;breadcrumb-item&quot;&gt;<br>                            &lt;a href=&quot;{{ route(&#39;drive.folder.browse&#39;, $crumb-&gt;id) }}&quot;&gt;{{ $crumb-&gt;name }}&lt;/a&gt;<br>                        &lt;/li&gt;<br>                    @endforeach<br>                @endif<br>            &lt;/ol&gt;<br>        &lt;/nav&gt;<br><br>        &lt;!-- Action buttons --&gt;<br>        &lt;div class=&quot;drive-actions mb-4&quot;&gt;<br>            &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;drive.folder.create&#39;) }}&quot; class=&quot;d-flex gap-2&quot;&gt;<br>                @csrf<br>                &lt;input type=&quot;text&quot; name=&quot;name&quot; class=&quot;form-control&quot; placeholder=&quot;New folder name&quot; required style=&quot;width: 200px;&quot;&gt;<br>                &lt;input type=&quot;hidden&quot; name=&quot;parent_id&quot; value=&quot;{{ $currentFolder-&gt;id ?? &#39;&#39; }}&quot;&gt;<br>                &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;<br>                    &lt;i class=&quot;fas fa-folder-plus me-1&quot;&gt;&lt;/i&gt; New Folder<br>                &lt;/button&gt;<br>            &lt;/form&gt;<br><br>            &lt;div class=&quot;upload-btn-wrapper&quot;&gt;<br>                &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;drive.upload&#39;) }}&quot; enctype=&quot;multipart/form-data&quot; id=&quot;uploadForm&quot;&gt;<br>                    @csrf<br>                    &lt;input type=&quot;file&quot; name=&quot;file[]&quot; id=&quot;fileInput&quot; multiple required&gt;<br>                    &lt;input type=&quot;hidden&quot; name=&quot;folder_id&quot; value=&quot;{{ $currentFolder-&gt;id ?? &#39;&#39; }}&quot;&gt;<br>                    &lt;button class=&quot;btn btn-success&quot; type=&quot;button&quot; onclick=&quot;document.getElementById(&#39;fileInput&#39;).click()&quot;&gt;<br>                        &lt;i class=&quot;fas fa-upload me-1&quot;&gt;&lt;/i&gt; Upload Files<br>                    &lt;/button&gt;<br>                &lt;/form&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;upload-btn-wrapper&quot;&gt;<br>                &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;drive.large.fileUpload&#39;) }}&quot; enctype=&quot;multipart/form-data&quot; id=&quot;uploadFormForLarge&quot;&gt;<br>                    @csrf<br>                    &lt;input type=&quot;file&quot; name=&quot;file_name&quot; class=&quot;form-control @error(&#39;file_name&#39;) is-invalid @enderror&quot;<br>                           id=&quot;file_name&quot; accept=&quot;.zip,application/zip,application/x-zip,application/x-zip-compressed&quot; required&gt;<br>                    &lt;input type=&quot;hidden&quot; name=&quot;folder_id&quot; value=&quot;{{ $currentFolder-&gt;id ?? &#39;&#39; }}&quot;&gt;<br>                    &lt;button class=&quot;btn btn-success&quot; id=&quot;submitBtn&quot; type=&quot;button&quot;&gt;<br>                        &lt;i class=&quot;fas fa-upload me-1&quot;&gt;&lt;/i&gt; Large Zip Upload<br>                    &lt;/button&gt;<br>                &lt;/form&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;progress mb-3&quot; style=&quot;display: none;&quot;&gt;<br>            &lt;div class=&quot;progress-bar&quot; role=&quot;progressbar&quot; style=&quot;width: 0%;&quot;&gt;0%&lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Main content area --&gt;<br>        &lt;div class=&quot;drive-content&quot;&gt;<br>            @if($errors-&gt;any())<br>                &lt;div class=&quot;alert alert-danger&quot;&gt;<br>                    &lt;ul class=&quot;mb-0&quot;&gt;<br>                        @foreach($errors-&gt;all() as $error)<br>                            &lt;li&gt;{{ $error }}&lt;/li&gt;<br>                        @endforeach<br>                    &lt;/ul&gt;<br>                &lt;/div&gt;<br>            @endif<br><br>            @if(session(&quot;success&quot;))<br>                &lt;div class=&quot;alert alert-success alert-dismissible fade show&quot; role=&quot;alert&quot;&gt;<br>                    {{ session(&#39;success&#39;) }}<br>                    &lt;button type=&quot;button&quot; class=&quot;btn-close&quot; data-bs-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>            @endif<br><br>            @if(session(&#39;error&#39;))<br>                &lt;div class=&quot;alert alert-danger alert-dismissible fade show&quot; role=&quot;alert&quot;&gt;<br>                    {{ session(&#39;error&#39;) }}<br>                    &lt;button type=&quot;button&quot; class=&quot;btn-close&quot; data-bs-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>            @endif<br><br>            &lt;!-- Items grid --&gt;<br>            &lt;div class=&quot;item-grid&quot;&gt;<br>                @foreach($folders as $folder)<br>                    &lt;div class=&quot;drive-item&quot;&gt;<br>                        &lt;a href=&quot;{{ route(&#39;drive.folder.browse&#39;, $folder-&gt;id) }}&quot; class=&quot;text-decoration-none d-block&quot;&gt;<br>                            &lt;div class=&quot;drive-item-icon folder-icon&quot;&gt;<br>                                &lt;svg viewBox=&quot;0 0 24 24&quot;&gt;<br>                                    &lt;g transform=&quot;translate(2, 3)&quot;&gt;<br>                                        &lt;path d=&quot;M1 4.5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1v-12a1 1 0 0 1 1-1z&quot; fill=&quot;#FFD04E&quot;&gt;&lt;/path&gt;<br>                                        &lt;path d=&quot;M1 4.5h18a1 1 0 0 1 1 1v1H0v-1a1 1 0 0 1 1-1z&quot; fill=&quot;#F6B352&quot;&gt;&lt;/path&gt;<br>                                    &lt;/g&gt;<br>                                &lt;/svg&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;drive-item-name&quot;&gt;{{ $folder-&gt;name }}&lt;/div&gt;<br>                        &lt;/a&gt;<br>                        &lt;div class=&quot;drive-item-actions&quot;&gt;<br>                            &lt;div class=&quot;dropdown&quot;&gt;<br>                                &lt;button class=&quot;btn btn-sm btn-light rounded-circle&quot; type=&quot;button&quot; data-bs-toggle=&quot;dropdown&quot;&gt;<br>                                    &lt;i class=&quot;fas fa-ellipsis-vertical&quot;&gt;&lt;/i&gt;<br>                                &lt;/button&gt;<br>                                &lt;ul class=&quot;dropdown-menu&quot;&gt;<br>                                    &lt;li&gt;<br>                                        &lt;button class=&quot;dropdown-item&quot; onclick=&quot;openRenameModal({{ $folder-&gt;id }}, &#39;{{ $folder-&gt;name }}&#39;)&quot;&gt;<br>                                            &lt;i class=&quot;fas fa-pen me-2&quot;&gt;&lt;/i&gt; Rename<br>                                        &lt;/button&gt;<br>                                    &lt;/li&gt;<br>                                    &lt;li&gt;<br>                                        &lt;a class=&quot;dropdown-item&quot; href=&quot;{{ route(&#39;drive.folder.download&#39;, $folder) }}&quot;&gt;<br>                                            &lt;i class=&quot;fas fa-file-archive me-2&quot;&gt;&lt;/i&gt; Download<br>                                        &lt;/a&gt;<br>                                    &lt;/li&gt;<br>                                    &lt;li&gt;<br>                                        &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;drive.folder.delete&#39;, $folder-&gt;id) }}&quot; onsubmit=&quot;return confirm(&#39;Are you sure you want to delete this folder?&#39;)&quot;&gt;<br>                                            @csrf<br>                                            @method(&#39;DELETE&#39;)<br>                                            &lt;button type=&quot;submit&quot; class=&quot;dropdown-item text-danger&quot;&gt;<br>                                                &lt;i class=&quot;fas fa-trash me-2&quot;&gt;&lt;/i&gt; Delete<br>                                            &lt;/button&gt;<br>                                        &lt;/form&gt;<br>                                    &lt;/li&gt;<br>                                &lt;/ul&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                @endforeach<br><br>                @foreach($files as $file)<br>                    &lt;div class=&quot;drive-item&quot;&gt;<br>                        &lt;a href=&quot;{{ route(&#39;drive.download&#39;, $file) }}&quot; class=&quot;text-decoration-none d-block&quot;&gt;<br>                            &lt;div class=&quot;drive-item-icon file-icon&quot;&gt;<br>                                &lt;svg viewBox=&quot;0 0 24 24&quot;&gt;<br>                                    &lt;path d=&quot;M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z&quot; fill=&quot;#E8F0FE&quot;&gt;&lt;/path&gt;<br>                                    &lt;path d=&quot;M14 2v6h6&quot; fill=&quot;#D2E3FC&quot;&gt;&lt;/path&gt;<br>                                    &lt;path d=&quot;M14 2v6h6&quot; stroke=&quot;#4285F4&quot; stroke-width=&quot;1.5&quot; fill=&quot;none&quot;&gt;&lt;/path&gt;<br>                                    &lt;path d=&quot;M6 4v16h12V8h-6V4H6z&quot; stroke=&quot;#4285F4&quot; stroke-width=&quot;1.5&quot; fill=&quot;none&quot;&gt;&lt;/path&gt;<br>                                &lt;/svg&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;drive-item-name&quot;&gt;{{ $file-&gt;original_name }}&lt;/div&gt;<br>                        &lt;/a&gt;<br>                        &lt;div class=&quot;drive-item-actions&quot;&gt;<br>                            &lt;div class=&quot;dropdown&quot;&gt;<br>                                &lt;button class=&quot;btn btn-sm btn-light rounded-circle&quot; type=&quot;button&quot; data-bs-toggle=&quot;dropdown&quot;&gt;<br>                                    &lt;i class=&quot;fas fa-ellipsis-vertical&quot;&gt;&lt;/i&gt;<br>                                &lt;/button&gt;<br>                                &lt;ul class=&quot;dropdown-menu&quot;&gt;<br>                                    &lt;li&gt;<br>                                        &lt;a class=&quot;dropdown-item&quot; href=&quot;{{ route(&#39;drive.download&#39;, $file) }}&quot;&gt;<br>                                            &lt;i class=&quot;fas fa-download me-2&quot;&gt;&lt;/i&gt; Download<br>                                        &lt;/a&gt;<br>                                    &lt;/li&gt;<br>                                    &lt;li&gt;<br>                                        &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;drive.file.delete&#39;, $file-&gt;id) }}&quot; onsubmit=&quot;return confirm(&#39;Are you sure you want to delete this file?&#39;)&quot;&gt;<br>                                            @csrf<br>                                            @method(&#39;DELETE&#39;)<br>                                            &lt;button type=&quot;submit&quot; class=&quot;dropdown-item text-danger&quot;&gt;<br>                                                &lt;i class=&quot;fas fa-trash me-2&quot;&gt;&lt;/i&gt; Delete<br>                                            &lt;/button&gt;<br>                                        &lt;/form&gt;<br>                                    &lt;/li&gt;<br>                                &lt;/ul&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                @endforeach<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- Rename Modal --&gt;<br>    &lt;div class=&quot;modal fade&quot; id=&quot;renameModal&quot; tabindex=&quot;-1&quot; aria-labelledby=&quot;renameModalLabel&quot; aria-hidden=&quot;true&quot;&gt;<br>        &lt;div class=&quot;modal-dialog&quot;&gt;<br>            &lt;form method=&quot;POST&quot; id=&quot;renameForm&quot;&gt;<br>                @csrf<br>                @method(&#39;PUT&#39;)<br>                &lt;div class=&quot;modal-content&quot;&gt;<br>                    &lt;div class=&quot;modal-header&quot;&gt;<br>                        &lt;h5 class=&quot;modal-title&quot; id=&quot;renameModalLabel&quot;&gt;Rename Folder&lt;/h5&gt;<br>                        &lt;button type=&quot;button&quot; class=&quot;btn-close&quot; data-bs-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot;&gt;&lt;/button&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;modal-body&quot;&gt;<br>                        &lt;input type=&quot;text&quot; name=&quot;name&quot; id=&quot;renameFolderName&quot; class=&quot;form-control&quot; required&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;modal-footer&quot;&gt;<br>                        &lt;button type=&quot;button&quot; class=&quot;btn btn-secondary&quot; data-bs-dismiss=&quot;modal&quot;&gt;Cancel&lt;/button&gt;<br>                        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Rename&lt;/button&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br><br>@endsection<br><br>@push(&#39;scripts&#39;)<br>&lt;script&gt;<br>    function openRenameModal(id, name) {<br>        document.getElementById(&#39;renameFolderName&#39;).value = name;<br>        document.getElementById(&#39;renameForm&#39;).action = `/admin/drive/folder/${id}`;<br>        new bootstrap.Modal(document.getElementById(&#39;renameModal&#39;)).show();<br>    }<br>&lt;/script&gt;<br>&lt;script&gt;<br>    // Auto submit the upload form when files are selected<br>    document.getElementById(&#39;fileInput&#39;).addEventListener(&#39;change&#39;, function() {<br>        if(this.files.length &gt; 0) {<br>            document.getElementById(&#39;uploadForm&#39;).submit();<br>        }<br>    });<br>&lt;/script&gt;<br><br>&lt;script&gt;<br>    document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br>    const form = document.getElementById(&#39;uploadFormForLarge&#39;);<br>    const fileInput = document.getElementById(&#39;file_name&#39;);<br>    const progressBar = document.querySelector(&#39;.progress-bar&#39;);<br>    const progressContainer = document.querySelector(&#39;.progress&#39;);<br>    const submitBtn = document.getElementById(&#39;submitBtn&#39;);<br>    const folderIdInput = document.querySelector(&#39;input[name=&quot;folder_id&quot;]&#39;);<br><br>    fileInput.addEventListener(&#39;change&#39;, async function(e) {<br>        const file = fileInput.files[0];<br>        if (!file) return;<br><br>        submitBtn.disabled = true;<br>        progressContainer.style.display = &#39;block&#39;;<br><br>        try {<br>            const result = await uploadFileInChunks(file, progressBar);<br>            console.log(&#39;Upload complete:&#39;, result);<br><br>            // Create a hidden input with the file path if needed<br>            const hiddenInput = document.createElement(&#39;input&#39;);<br>            hiddenInput.type = &#39;hidden&#39;;<br>            hiddenInput.name = &#39;file_path&#39;;<br>            hiddenInput.value = result.path;<br>            form.appendChild(hiddenInput);<br><br>            // Submit the form normally<br>            form.submit();<br>        } catch (error) {<br>            console.error(&#39;Upload failed:&#39;, error);<br>            alert(&#39;File upload failed: &#39; + error.message);<br>        } finally {<br>            submitBtn.disabled = false;<br>            progressContainer.style.display = &#39;none&#39;;<br>        }<br>    });<br><br>    async function uploadFileInChunks(file, progressBar) {<br>        const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB chunks<br>        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);<br>        const folderId = folderIdInput ? folderIdInput.value : null;<br><br>        // Generate unique upload ID<br>        const uploadId = &#39;upload-&#39; + Date.now() + &#39;-&#39; + Math.random().toString(36).substr(2, 9);<br><br>        for (let chunkIndex = 0; chunkIndex &lt; totalChunks; chunkIndex++) {<br>            const start = chunkIndex * CHUNK_SIZE;<br>            const end = Math.min(start + CHUNK_SIZE, file.size);<br>            const chunk = file.slice(start, end);<br><br>            const formData = new FormData();<br>            formData.append(&#39;file&#39;, chunk);<br>            formData.append(&#39;chunkIndex&#39;, chunkIndex);<br>            formData.append(&#39;totalChunks&#39;, totalChunks);<br>            formData.append(&#39;uploadId&#39;, uploadId);<br>            formData.append(&#39;originalName&#39;, file.name);<br>            if (folderId) formData.append(&#39;folder_id&#39;, folderId);<br><br>            const response = await fetch(&#39;/admin/drive/chunked-upload&#39;, {<br>                method: &#39;POST&#39;,<br>                body: formData,<br>                headers: {<br>                    &#39;X-CSRF-TOKEN&#39;: document.querySelector(&#39;meta[name=&quot;csrf-token&quot;]&#39;).content,<br>                    &#39;Accept&#39;: &#39;application/json&#39;<br>                }<br>            });<br><br>            if (!response.ok) {<br>                const error = await response.json();<br>                throw new Error(error.message || &#39;Chunk upload failed&#39;);<br>            }<br><br>            // Update progress<br>            const percent = Math.round((chunkIndex + 1) / totalChunks * 100);<br>            progressBar.style.width = percent + &#39;%&#39;;<br>            progressBar.textContent = percent + &#39;%&#39;;<br>        }<br><br>        // Finalize the upload<br>        const response = await fetch(&#39;/admin/drive/finalize-upload&#39;, {<br>            method: &#39;POST&#39;,<br>            body: JSON.stringify({<br>                uploadId: uploadId,<br>                fileName: file.name,<br>                folder_id: folderId<br>            }),<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                &#39;X-CSRF-TOKEN&#39;: document.querySelector(&#39;meta[name=&quot;csrf-token&quot;]&#39;).content,<br>                &#39;Accept&#39;: &#39;application/json&#39;<br>            }<br>        });<br><br>        if (!response.ok) {<br>            const error = await response.json();<br>            throw new Error(error.message || &#39;Finalization failed&#39;);<br>        }<br><br>        return await response.json();<br>    }<br>});<br>&lt;/script&gt;<br>@endpush</pre><h3>Key Takeaways</h3><ol><li><strong>Database Design</strong>: The self-referential relationship in the folders table enables nested folder structures while maintaining data integrity.</li><li><strong>Recursive Operations</strong>: Folder deletion requires careful recursive handling to ensure all child folders and files are properly deleted.</li><li><strong>File Handling</strong>: Laravel’s Storage facade provides a clean abstraction for file operations while supporting multiple drivers.</li><li><strong>Large File Uploads and Downloads</strong>: Chunking files makes large uploads more reliable and provides better progress feedback, and downloads the whole folder and files.</li><li><strong>User Experience</strong>: Features like breadcrumbs, context menus, and progress indicators significantly improve usability.</li></ol><p>Here is the Demo video link:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPgWsesRtpeA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPgWsesRtpeA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPgWsesRtpeA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c98689123955a20cd1d9cec3122f9a/href">https://medium.com/media/22c98689123955a20cd1d9cec3122f9a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4307fd0a1fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upload Large Files (500MB+) in Laravel Without Using Any Packages]]></title>
            <link>https://medium.com/@habibur.rahman.0927/how-to-upload-large-files-500mb-in-laravel-without-using-any-packages-ade17ee7245d?source=rss-8a636b976b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade17ee7245d</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Md Habibur Rahman]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 20:04:29 GMT</pubDate>
            <atom:updated>2025-04-06T20:04:29.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5H2ooGs5_YY9ks8vvIEwTg.png" /></figure><p>Uploading large files in web applications can be challenging due to server limitations, timeouts, and memory constraints. In this article, I’ll show you how to implement a robust large file upload solution in Laravel (500MB+) without relying on any external packages.</p><h3>Why Chunked Uploads?</h3><p>Traditional file uploads send the entire file in one request, which can fail for large files due to:</p><ul><li>Server timeout limitations</li><li>PHP memory limits</li><li>Network instability</li><li>Server upload size restrictions</li></ul><p>Chunked uploading solves these problems by breaking the file into smaller pieces (e.g., 5MB chunks) and uploading them sequentially.</p><h3>Implementation Steps</h3><h3>1. Server Configuration</h3><p>First, ensure your server can handle large uploads:</p><p><strong>Nginx Configuration</strong>:</p><p>client_max_body_size 512M;</p><p><strong>PHP Configuration (php.ini)</strong>:</p><p>upload_max_filesize = 512M<br>post_max_size = 512M<br>memory_limit = 1G<br>max_execution_time = 300<br>max_input_time = 300</p><h3>2. Frontend Implementation</h3><p>Create a form with JavaScript that handles chunked uploading:</p><pre>&lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;fileupload.store&#39;) }}&quot; enctype=&quot;multipart/form-data&quot; id=&quot;uploadForm&quot;&gt;<br>    @csrf<br>    &lt;input type=&quot;hidden&quot; name=&quot;upload_result&quot; id=&quot;uploadResult&quot;&gt;<br>    <br>    &lt;div class=&quot;form-group&quot;&gt;<br>        &lt;label for=&quot;project_id&quot;&gt;Project&lt;/label&gt;<br>        &lt;select name=&quot;project_id&quot; id=&quot;project_id&quot; required&gt;<br>            &lt;option value=&quot;&quot;&gt;Select Project&lt;/option&gt;<br>            @foreach ($projects as $project)<br>                &lt;option value=&quot;{{ $project-&gt;id }}&quot;&gt;{{ $project-&gt;name }}&lt;/option&gt;<br>            @endforeach<br>        &lt;/select&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;form-group&quot;&gt;<br>        &lt;label for=&quot;file_name&quot;&gt;File (ZIP only)&lt;/label&gt;<br>        &lt;input type=&quot;file&quot; name=&quot;file_name&quot; id=&quot;file_name&quot; accept=&quot;.zip&quot; required&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;progress&quot; style=&quot;display: none;&quot;&gt;<br>        &lt;div class=&quot;progress-bar&quot; role=&quot;progressbar&quot; style=&quot;width: 0%&quot;&gt;0%&lt;/div&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;button type=&quot;submit&quot; id=&quot;submitBtn&quot;&gt;Upload&lt;/button&gt;<br>&lt;/form&gt;<br><br>&lt;script&gt;<br>document.getElementById(&#39;uploadForm&#39;).addEventListener(&#39;submit&#39;, async function(e) {<br>    e.preventDefault();<br>    const fileInput = document.getElementById(&#39;file_name&#39;);<br>    const file = fileInput.files[0];<br>    const submitBtn = document.getElementById(&#39;submitBtn&#39;);<br>    <br>    if (!file) return;<br>    <br>    submitBtn.disabled = true;<br>    const progressBar = document.querySelector(&#39;.progress-bar&#39;);<br>    const progressContainer = document.querySelector(&#39;.progress&#39;);<br>    progressContainer.style.display = &#39;block&#39;;<br>    <br>    try {<br>        const result = await uploadFileInChunks(file, progressBar);<br>        document.getElementById(&#39;uploadResult&#39;).value = result.path;<br>        this.submit();<br>    } catch (error) {<br>        alert(&#39;Upload failed: &#39; + error.message);<br>        submitBtn.disabled = false;<br>        progressContainer.style.display = &#39;none&#39;;<br>    }<br>});<br><br>async function uploadFileInChunks(file, progressBar) {<br>    const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB chunks<br>    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);<br>    const projectId = document.getElementById(&#39;project_id&#39;).value;<br>    const uploadId = &#39;upload-&#39; + Date.now() + &#39;-&#39; + Math.random().toString(36).substr(2, 9);<br>    <br>    // Upload each chunk<br>    for (let chunkIndex = 0; chunkIndex &lt; totalChunks; chunkIndex++) {<br>        const start = chunkIndex * CHUNK_SIZE;<br>        const end = Math.min(start + CHUNK_SIZE, file.size);<br>        const chunk = file.slice(start, end);<br>        <br>        const formData = new FormData();<br>        formData.append(&#39;file&#39;, chunk);<br>        formData.append(&#39;chunkIndex&#39;, chunkIndex);<br>        formData.append(&#39;totalChunks&#39;, totalChunks);<br>        formData.append(&#39;uploadId&#39;, uploadId);<br>        formData.append(&#39;originalName&#39;, file.name);<br>        formData.append(&#39;project_id&#39;, projectId);<br>        <br>        const response = await fetch(&#39;/admin/chunked-upload&#39;, {<br>            method: &#39;POST&#39;,<br>            body: formData,<br>            headers: {<br>                &#39;X-CSRF-TOKEN&#39;: document.querySelector(&#39;meta[name=&quot;csrf-token&quot;]&#39;).content,<br>                &#39;Accept&#39;: &#39;application/json&#39;<br>            }<br>        });<br>        <br>        if (!response.ok) {<br>            const error = await response.json();<br>            throw new Error(error.message || &#39;Chunk upload failed&#39;);<br>        }<br>        <br>        // Update progress<br>        const percent = Math.round((chunkIndex + 1) / totalChunks * 100);<br>        progressBar.style.width = percent + &#39;%&#39;;<br>        progressBar.textContent = percent + &#39;%&#39;;<br>    }<br>    <br>    // Finalize upload<br>    const response = await fetch(&#39;/admin/finalize-upload&#39;, {<br>        method: &#39;POST&#39;,<br>        body: JSON.stringify({<br>            uploadId: uploadId,<br>            fileName: file.name,<br>            project_id: projectId<br>        }),<br>        headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;X-CSRF-TOKEN&#39;: document.querySelector(&#39;meta[name=&quot;csrf-token&quot;]&#39;).content,<br>            &#39;Accept&#39;: &#39;application/json&#39;<br>        }<br>    });<br>    <br>    if (!response.ok) {<br>        const error = await response.json();<br>        throw new Error(error.message || &#39;Finalization failed&#39;);<br>    }<br>    <br>    return await response.json();<br>}<br>&lt;/script&gt;</pre><h3>3. Backend Routes</h3><p>Add these routes to your web.php:</p><pre>Route::post(&#39;/chunked-upload&#39;, [FileUploadController::class, &#39;uploadChunk&#39;]);<br>Route::post(&#39;/finalize-upload&#39;, [FileUploadController::class, &#39;finalizeUpload&#39;]);<br>Route::resource(&#39;fileupload&#39;, FileUploadController::class);</pre><h3>4. Controller Implementation</h3><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Storage;<br>use App\Http\Requests\UploadChunkRequest;<br>use App\Http\Requests\FinalizeUploadRequest;<br><br>class FileUploadController extends Controller<br>{<br>    public function uploadChunk(UploadChunkRequest $request)<br>    {<br>        try {<br>            $chunk = $request-&gt;file(&#39;file&#39;);<br>            $chunkIndex = $request-&gt;input(&#39;chunkIndex&#39;);<br>            $uploadId = $request-&gt;input(&#39;uploadId&#39;);<br><br>            $tempPath = &quot;temp/uploads/{$uploadId}&quot;;<br>            $chunkPath = &quot;{$tempPath}/{$chunkIndex}&quot;;<br><br>            // Ensure directory exists<br>            Storage::disk(&#39;local&#39;)-&gt;makeDirectory($tempPath);<br><br>            // Store the chunk<br>            Storage::disk(&#39;local&#39;)-&gt;put($chunkPath, file_get_contents($chunk-&gt;path()));<br><br>            return response()-&gt;json([<br>                &#39;message&#39; =&gt; &#39;Chunk uploaded successfully&#39;,<br>                &#39;chunkIndex&#39; =&gt; $chunkIndex<br>            ]);<br><br>        } catch (\Exception $e) {<br>            return response()-&gt;json([<br>                &#39;error&#39; =&gt; $e-&gt;getMessage(),<br>                &#39;details&#39; =&gt; [<br>                    &#39;upload_max&#39; =&gt; ini_get(&#39;upload_max_filesize&#39;),<br>                    &#39;post_max&#39; =&gt; ini_get(&#39;post_max_size&#39;),<br>                    &#39;disk_free&#39; =&gt; disk_free_space(&#39;/&#39;),<br>                    &#39;file_size&#39; =&gt; $request-&gt;file(&#39;file&#39;)-&gt;getSize()<br>                ]<br>            ], 500);<br>        }<br>    }<br><br>    public function finalizeUpload(FinalizeUploadRequest $request)<br>    {<br>        try {<br>            $uploadId = $request-&gt;input(&#39;uploadId&#39;);<br>            $fileName = $request-&gt;input(&#39;fileName&#39;);<br>            $projectId = $request-&gt;input(&#39;project_id&#39;);<br><br>            $tempPath = &quot;temp/uploads/{$uploadId}&quot;;<br>            $chunks = Storage::disk(&#39;local&#39;)-&gt;files($tempPath);<br><br>            if (empty($chunks)) {<br>                throw new \Exception(&#39;No chunks found&#39;);<br>            }<br><br>            // Sort chunks numerically<br>            natsort($chunks);<br>            $chunks = array_values($chunks);<br><br>            // Create final file path<br>            $timestamp = now()-&gt;format(&#39;Y-m-d_h_i_A&#39;);<br>            $finalPath = &quot;projects/project_{$projectId}/files/{$timestamp}/{$fileName}&quot;;<br>            <br>            // Ensure directory exists<br>            Storage::disk(&#39;public&#39;)-&gt;makeDirectory(dirname($finalPath));<br><br>            // Combine chunks<br>            $finalStoragePath = Storage::disk(&#39;public&#39;)-&gt;path($finalPath);<br>            $finalFile = fopen($finalStoragePath, &#39;wb&#39;);<br><br>            foreach ($chunks as $chunkPath) {<br>                $chunkContent = Storage::disk(&#39;local&#39;)-&gt;get($chunkPath);<br>                fwrite($finalFile, $chunkContent);<br>            }<br>            fclose($finalFile);<br><br>            // Clean up<br>            Storage::disk(&#39;local&#39;)-&gt;deleteDirectory($tempPath);<br><br>            return response()-&gt;json([<br>                &#39;success&#39; =&gt; true,<br>                &#39;path&#39; =&gt; $finalPath,<br>                &#39;file_name&#39; =&gt; $fileName<br>            ]);<br><br>        } catch (\Exception $e) {<br>            return response()-&gt;json([<br>                &#39;error&#39; =&gt; $e-&gt;getMessage()<br>            ], 500);<br>        }<br>    }<br><br>    public function store(Request $request)<br>    {<br>        $validated = $request-&gt;validate([<br>            &#39;project_id&#39; =&gt; &#39;required|exists:projects,id&#39;,<br>            &#39;upload_result&#39; =&gt; &#39;required|string&#39;<br>        ]);<br><br>        // Save to database<br>        $fileUpload = FileUpload::create([<br>            &#39;project_id&#39; =&gt; $validated[&#39;project_id&#39;],<br>            &#39;file_path&#39; =&gt; $validated[&#39;upload_result&#39;],<br>            &#39;status&#39; =&gt; &#39;completed&#39;<br>        ]);<br><br>        return redirect()-&gt;route(&#39;fileupload.index&#39;)<br>            -&gt;with(&#39;success&#39;, &#39;File uploaded successfully&#39;);<br>    }<br>}</pre><p>Demo Implementation Video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyZn-hWCMZwI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyZn-hWCMZwI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyZn-hWCMZwI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/355595f8f812db31569925cd1f22cb00/href">https://medium.com/media/355595f8f812db31569925cd1f22cb00/href</a></iframe><h3>Key Features of This Solution</h3><ol><li><strong>Chunked Uploading</strong>: Files are split into manageable 5MB chunks</li><li><strong>Progress Tracking</strong>: Real-time progress bar shows upload status</li><li><strong>Resumable Uploads</strong>: If a chunk fails, it can be retried without restarting</li><li><strong>Server-Side Validation</strong>: Each chunk is validated before processing</li><li><strong>Memory Efficient</strong>: Processes one chunk at a time</li><li><strong>Cleanup</strong>: Temporary files are removed after successful upload</li></ol><h3>Handling Edge Cases</h3><ol><li><strong>Network Failures</strong>: The client can retry failed chunks</li><li><strong>Duplicate Uploads</strong>: Each upload gets a unique ID to prevent conflicts</li><li><strong>Large File Support</strong>: Server configuration allows files up to 512MB</li><li><strong>Security</strong>: CSRF protection and file validation are implemented</li></ol><h3>Performance Considerations</h3><ul><li>Adjust chunk size based on your network conditions (5MB is a good starting point)</li><li>Consider adding client-side file hash verification for integrity checking</li><li>For very large files (&gt;1GB), consider adding a pause/resume feature</li></ul><p>This solution provides a robust way to handle large file uploads in Laravel without external dependencies. The chunked approach ensures reliability even with unstable connections, while the server configuration changes accommodate larger files.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade17ee7245d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Way to Implement Repository Pattern in Laravel]]></title>
            <link>https://medium.com/@habibur.rahman.0927/best-way-to-implement-repository-pattern-in-laravel-c3da491a63e0?source=rss-8a636b976b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3da491a63e0</guid>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Md Habibur Rahman]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 08:12:33 GMT</pubDate>
            <atom:updated>2025-01-26T08:12:33.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><ul><li>Briefly introduce the concept of the repository pattern and its purpose.</li><li>Explain why using repositories can help in abstracting the data access logic and make the application more maintainable, testable, and scalable.</li></ul><p><strong>1. Create the Base Repository and IBase Repository</strong></p><p>You already have a BaseRepository class. Discuss how it implements common methods for CRUD operations, and explain the purpose of the IBaseRepository interface.</p><ul><li><strong>Methods included</strong>: create, findById, findFirstByConditions, findAll, findAllWithPagination, etc.</li><li><strong>Advantages</strong>: Keeps your repository code DRY (Don’t Repeat Yourself) by centralizing common database operations.</li></ul><pre>&lt;?php<br><br>namespace App\Repositories;<br><br>use Illuminate\Database\Eloquent\Collection;<br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Pagination\LengthAwarePaginator;<br><br>interface IBaseRepository<br>{<br>    /**<br>     * Create a new resource.<br>     *<br>     * @param array $attributes<br>     * @return Model<br>     */<br>    public function create(array $attributes): Model;<br><br>    /**<br>     * Find a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @param string[] $columns<br>     * @return Model<br>     */<br>    public function findById(int|string $id, array $columns = [&#39;*&#39;]): ?Model;<br><br>    /**<br>     * Find a resource by its conditions.<br>     *<br>     * @param array $conditions<br>     * @param array $columns<br>     * @return Model|null<br>     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<br>     */<br>    public function findFirstByConditions(array $conditions, array $columns = [&#39;*&#39;]): ?Model;<br><br>    /**<br>     * Get all resources with optional filters.<br>     *<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return Collection|array<br>     */<br>    public function findAll(array $conditions = [], array $columns = [&#39;*&#39;]): Collection|array;<br><br>    /**<br>     * Get resources with pagination based on filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return LengthAwarePaginator<br>     */<br>    public function findAllWithPagination(array $conditions = [], array $columns = [&#39;*&#39;],  int $limit): LengthAwarePaginator;<br><br>    /**<br>     * Get a limited set of resources with optional filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return Collection<br>     */<br>    public function findByLimit(int $limit, array $conditions = [], array $columns = [&#39;*&#39;]): Collection;<br><br>    /**<br>     * Update a resource by its ID.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return int<br>     */<br>    public function update(array $conditions, array $attributes): int;<br><br>    /**<br>     * Update or create a resource.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function updateOrCreate(array $conditions, array $attributes): mixed;<br><br>    /**<br>     * Delete a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @return int<br>     */<br>    public function deleteById(int|string $id): int;<br>    <br>    /**<br>     * Delete multiple resources based on conditions.<br>     *<br>     * @param array $conditions<br>     * @return int The number of deleted records.<br>     */<br>    public function deleteAll(array $conditions): int;<br>}</pre><pre>&lt;?php<br><br>namespace App\Repositories;<br><br>use Illuminate\Database\Eloquent\Collection;<br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Pagination\LengthAwarePaginator;<br><br>abstract class BaseRepository implements IBaseRepository<br>{<br>    protected $model;<br><br>    public function __construct(Model $model)<br>    {<br>        $this-&gt;model = $model;<br>    }<br><br>    /**<br>     * Create a new resource.<br>     *<br>     * @param array $attributes<br>     * @return Model<br>     */<br>    public function create(array $attributes): Model<br>    {<br>        return $this-&gt;model-&gt;create($attributes);<br>    }<br><br>    /**<br>     * Find a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @param array $columns<br>     * @return Model|null<br>     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<br>     */<br>    public function findById(int|string $id, array $columns = [&#39;*&#39;]): ?Model<br>    {<br>        return $this-&gt;model-&gt;findOrFail($id, $columns);<br>    }<br><br>    /**<br>     * Find a resource by its conditions.<br>     *<br>     * @param array $conditions<br>     * @param array $columns<br>     * @return Model|null<br>     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<br>     */<br>    public function findFirstByConditions(array $conditions, array $columns = [&#39;*&#39;]): ?Model<br>    {<br>        return $this-&gt;model-&gt;where($conditions)-&gt;select($columns)-&gt;first();<br>    }<br><br>    /**<br>     * Get all resources with optional filters.<br>     *<br>     * @param array $conditions<br>     * @param array $columns<br>     * @return Collection|array<br>     */<br>    public function findAll(array $conditions = [], array $columns = [&#39;*&#39;]): Collection|array<br>    {<br>        return $this-&gt;model-&gt;where($conditions)-&gt;get($columns);<br>    }<br><br>    /**<br>     * Get resources with pagination based on filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param array $columns<br>     * @return LengthAwarePaginator<br>     */<br>    public function findAllWithPagination(array $conditions = [], array $columns = [&#39;*&#39;], int $limit): LengthAwarePaginator<br>    {<br>        return $this-&gt;model-&gt;where($conditions)-&gt;paginate($limit);<br>    }<br><br>    /**<br>     * Get a limited set of resources with optional filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param array $columns<br>     * @return Collection<br>     */<br>    public function findByLimit(int $limit, array $conditions = [], array $columns = [&#39;*&#39;]): Collection<br>    {<br>        return $this-&gt;model-&gt;where($conditions)-&gt;limit($limit)-&gt;get($columns);<br>    }<br><br>    /**<br>     * Update a resource by its ID.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return int<br>     */<br>    public function update(array $conditions, array $attributes): int<br>    {<br>        return $this-&gt;model-&gt;where($conditions)-&gt;update($attributes);<br>    }<br><br>    /**<br>     * Update or create a resource.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return Model<br>     */<br>    public function updateOrCreate(array $conditions, array $attributes): Model<br>    {<br>        return $this-&gt;model-&gt;updateOrCreate($conditions, $attributes);<br>    }<br><br>    /**<br>     * Delete a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @return int<br>     */<br>    public function deleteById(int|string $id): int<br>    {<br>        return $this-&gt;model-&gt;destroy($id);<br>    }<br>    <br>    /**<br>     * Delete multiple resources based on conditions.<br>     *<br>     * @param array $conditions<br>     * @return int The number of deleted records.<br>     */<br>    public function deleteAll(array $conditions): int<br>    {<br>        return $this-&gt;model-&gt;where($conditions)-&gt;delete();<br>    }<br>}</pre><p><strong>2. Create a Repository for Specific Models</strong></p><ul><li>Show how to extend the BaseRepository for specific models, such as UserRepository or any other model.</li><li>Demonstrate custom methods such as fetching users with specific roles or any related relations if needed.</li></ul><pre>&lt;?php <br><br><br>namespace App\Repositories\User;<br><br>use App\Repositories\IBaseRepository;<br>use Illuminate\Database\Eloquent\Collection;<br><br>interface IUserRepository extends IBaseRepository<br>{<br>    public function getUserWithRole(array $conditions = [], array $columns = [&#39;*&#39;]): Collection|array;<br>}</pre><pre>&lt;?php <br><br><br>namespace App\Repositories\User;<br><br>use App\Models\User;<br>use App\Repositories\BaseRepository;<br>use Illuminate\Database\Eloquent\Collection;<br><br>class UserRepository extends BaseRepository implements IUserRepository<br>{<br>    public function __construct(User $model)<br>    {<br>        parent::__construct($model);<br>    }<br><br>    /**<br>     * Get all User resources with optional filters.<br>     *<br>     * @param array $conditions<br>     * @param array $columns<br>     * @return Collection|array<br>     */<br>    public function getUserWithRole(array $conditions = [], array $columns = [&#39;*&#39;]): Collection|array<br>    {<br>        return $this-&gt;model<br>                    -&gt;with([&#39;role&#39;])<br>                    -&gt;where($conditions)-&gt;get($columns);<br>    }<br>}</pre><h4>3. Service Layer for Business Logic</h4><ul><li>Introduce the Service Layer to further abstract the business logic from controllers. This ensures that the controller remains thin.</li><li>Show how a service class interacts with the repository to execute business logic.</li></ul><pre>&lt;?php<br><br>namespace App\Services;<br><br>use Illuminate\Database\Eloquent\Collection;<br>use Illuminate\Http\Request;<br>use Illuminate\Http\JsonResponse;<br><br>interface IBaseService<br>{<br>    /**<br>     * Create a new resource.<br>     *<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function create(array $attributes): mixed;<br><br>    /**<br>     * Find a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findById(int|string $id, array $columns = [&#39;*&#39;]): mixed;<br><br>    /**<br>     * Find a resource by its conditions.<br>     *<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findFirstByConditions(array $conditions, array $columns = [&#39;*&#39;]): mixed;<br><br>    /**<br>     * Get all resources with optional filters.<br>     *<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return Collection|array<br>     */<br>    public function findAll(array $conditions = [], array $columns = [&#39;*&#39;]): Collection|array;<br><br>    /**<br>     * Get resources with pagination based on filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findAllWithPagination(array $conditions = [], array $columns = [&#39;*&#39;], int $limit): mixed;<br><br>    /**<br>     * Get a limited set of resources with optional filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findByLimit(int $limit, array $conditions = [], array $columns = [&#39;*&#39;]): mixed;<br><br>    /**<br>     * Update a resource by its ID.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function update(array $conditions, array $attributes): mixed;<br><br>    /**<br>     * Update or create a resource.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function updateOrCreate(array $conditions, array $attributes): mixed;<br><br>    /**<br>     * Delete a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @return mixed<br>     */<br>    public function deleteById(int|string $id): mixed;<br><br>    /**<br>     * Delete multiple resources based on conditions.<br>     *<br>     * @param array $conditions<br>     * @return int The number of deleted records.<br>     */<br>    public function deleteAll(array $conditions): int;<br><br>    /**<br>     * Get a list of resources for DataTables.<br>     *<br>     * @param Request $request<br>     * @return JsonResponse|array<br>     */<br>    public function dataTableList(Request $request): JsonResponse|array;<br>}</pre><pre>&lt;?php<br><br>namespace App\Services;<br><br>use Illuminate\Database\Eloquent\Collection;<br>use Illuminate\Http\JsonResponse;<br>use Illuminate\Http\Request;<br><br>abstract class BaseService implements IBaseService<br>{<br>    private object $modelRepository;<br><br>    public function __construct($modelRepository)<br>    {<br>        $this-&gt;modelRepository = $modelRepository;<br>    }<br><br>    /**<br>     * Create a new resource.<br>     *<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function create(array $attributes): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;create($attributes);<br>    }<br><br>    /**<br>     * Find a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findById(int|string $id, $columns = [&#39;*&#39;]): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;findById($id, $columns);<br>    }<br><br>    /**<br>     * Find a resource by its conditions.<br>     *<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findFirstByConditions(array $conditions, array $columns = [&#39;*&#39;]): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;findFirstByConditions($conditions, $columns);<br>    }<br><br>    /**<br>     * Get all resources with optional filters.<br>     *<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return Collection|array<br>     */<br>    public function findAll(array $conditions = [], array $columns = [&#39;*&#39;]): Collection|array<br>    {<br>        return $this-&gt;modelRepository-&gt;findAll($conditions, $columns);<br>    }<br><br>    /**<br>     * Get resources with pagination based on filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findAllWithPagination(array $conditions = [], array $columns = [&#39;*&#39;], int $limit): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;findAllWithPagination($conditions, $columns, $limit);<br>    }<br><br>    /**<br>     * Get a limited set of resources with optional filters.<br>     *<br>     * @param int $limit<br>     * @param array $conditions<br>     * @param string[] $columns<br>     * @return mixed<br>     */<br>    public function findByLimit(int $limit, array $conditions = [], array $columns = [&#39;*&#39;]): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;findByLimit($limit, $conditions, $columns);<br>    }<br><br>    /**<br>     * Update a resource by its ID.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function update(array $conditions, array $attributes): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;update($conditions, $attributes);<br>    }<br><br>    /**<br>     * Update or create a resource.<br>     *<br>     * @param array $conditions<br>     * @param array $attributes<br>     * @return mixed<br>     */<br>    public function updateOrCreate(array $conditions, array $attributes): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;updateOrCreate($conditions, $attributes);<br>    }<br><br>    /**<br>     * Delete a resource by its ID.<br>     *<br>     * @param int|string $id<br>     * @return mixed<br>     */<br>    public function deleteById(int|string $id): mixed<br>    {<br>        return $this-&gt;modelRepository-&gt;deleteById($id);<br>    }<br><br>    /**<br>     * Delete multiple resources based on conditions.<br>     *<br>     * @param array $conditions<br>     * @return int The number of deleted records.<br>     */<br>    public function deleteAll(array $conditions): int<br>    {<br>        return $this-&gt;modelRepository-&gt;deleteAll($conditions);<br>    }<br><br>    /**<br>     * Get a list of resources for DataTables.<br>     *<br>     * @param Request $request<br>     * @return JsonResponse|array<br>     */<br>    public function dataTableList(Request $request): JsonResponse|array<br>    {<br>        return []; // Implement DataTables logic here.<br>    }<br>}</pre><pre>&lt;?php <br><br><br>namespace App\Services\User;<br>use App\Services\IBaseService;<br><br>interface IUserService extends IBaseService<br>{<br>    public function getUserData();<br>}</pre><pre>&lt;?php <br><br><br>namespace App\Services\User;<br><br>use App\Repositories\User\IUserRepository;<br>use App\Services\BaseService;<br>use Exception;<br>use Illuminate\Http\JsonResponse;<br>use Yajra\DataTables\Facades\DataTables;<br><br>class UserService extends BaseService implements IUserService<br>{<br>    public function __construct(private IUserRepository $userRepository)<br>    {<br>        parent::__construct($userRepository);<br>    }<br><br>    /**<br>     * Retrieve user data for DataTables.<br>     *<br>     * @return \Illuminate\Http\JsonResponse<br>     */<br>    public function getUserData(): JsonResponse<br>    {<br>        try {<br>            $data = $this-&gt;userRepository-&gt;getUserWithRole([], [&#39;id&#39;, &#39;name&#39;, &#39;email&#39;, &#39;created_at&#39;, &#39;role_id&#39;]);<br>            return DataTables::of($data)<br>                -&gt;addColumn(&#39;role_name&#39;, function($data) {<br>                    return $data-&gt;role-&gt;name;<br>                })<br>                -&gt;addColumn(&#39;action&#39;, function($data){<br>                    return $data-&gt;id;<br>                })-&gt;toJson();<br>        } catch (Exception $e) {<br>            return response()-&gt;json([<br>                &#39;success&#39; =&gt; false,<br>                &#39;message&#39; =&gt; &#39;Could not retrieve data. Please try again later.&#39; . $e-&gt;getMessage(),<br>            ]);<br>        }<br>    }<br>}</pre><h4>4. Bind Repository and Service in provider more optimized way</h4><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use App\Repositories\User\IUserRepository;<br>use App\Repositories\User\UserRepository;<br>use App\Services\User\IUserService;<br>use App\Services\User\UserService;<br>use Illuminate\Support\ServiceProvider;<br><br>class ServiceRepositoryServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * Register services.<br>     */<br>    public function register(): void<br>    {<br>        $repositories = [<br>            IUserRepository::class =&gt; UserRepository::class,<br>        ];<br><br>        $services = [<br>            IUserService::class =&gt; UserService::class,<br>        ];<br>        $bindings = array_merge($repositories, $services);<br>        $this-&gt;bindServiceRepositories($bindings);<br>    }<br><br>    /**<br>     * Helper function to bind repository interfaces to their implementations<br>     */<br>    protected function bindServiceRepositories(array $repositories): void<br>    {<br>        foreach ($repositories as $interface =&gt; $implementation) {<br>            $this-&gt;app-&gt;bind($interface, $implementation);<br>        }<br>    }<br><br>    /**<br>     * Bootstrap services.<br>     */<br>    public function boot(): void<br>    {<br>        //<br>    }<br>}</pre><h4>5. Call Service into Controller</h4><pre>&lt;?php <br><br><br>namespace App\Http\Controllers\Admin;<br><br>use App\Http\Controllers\Controller;<br>use App\Services\User\IUserService;<br>use Illuminate\Http\Request;<br>use Symfony\Component\HttpFoundation\Response as ResponseAlias;<br>use Illuminate\View\View;<br>use Illuminate\Http\RedirectResponse;<br>use App\Http\Requests\CreateUserRequest;<br>use App\Http\Requests\UpdateUserRequest;<br>use Illuminate\Http\JsonResponse;<br>use Exception;<br>use Illuminate\Support\Facades\DB;<br><br>class UserController extends Controller<br>{<br><br>    public function __construct(private IUserService $userService)<br>    {<br><br>    }<br><br>    /**<br>     * Display a listing of the resource.<br>     *<br>     * @return View<br>     */<br>     public function index(): View<br>    {<br>        return view(&#39;admin.user.index&#39;)-&gt;with([]);<br>    }<br><br>    /**<br>     * Get user data for DataTables.<br>     *<br>     * @param \Illuminate\Http\Request $request<br>     * @return \Illuminate\Http\JsonResponse<br>     */<br>    public function getDatatables(Request $request): JsonResponse<br>    {<br>        if ($request-&gt;ajax()) {<br>            return $this-&gt;userService-&gt;getUserData();<br>        }<br>        return response()-&gt;json([<br>            &#39;success&#39; =&gt; false,<br>            &#39;message&#39; =&gt; &#39;Invalid request.&#39;,<br>        ]);<br>    }<br><br>    /**<br>     * Show the form for creating a new resource.<br>     *<br>     * @return View<br>     */<br>    public function create(): View<br>    {<br>        return view(&#39;admin.user.create&#39;)-&gt;with([]);<br>    }<br><br>    /**<br>     * Store a newly created resource in storage.<br>     *<br>     * @param UserRequest $request<br>     * @return RedirectResponse<br>     */<br>    public function store(CreateUserRequest $request): RedirectResponse<br>    {<br>        DB::beginTransaction();<br>        try {<br>            $response = $this-&gt;userService-&gt;create($request-&gt;all());<br><br>            DB::commit();<br>            return redirect()-&gt;back()-&gt;with(&#39;success&#39;, __(&#39;user_module.create_list_edit.user&#39;) . __(&#39;standard_curd_common_label.success&#39;));<br><br>        } catch (Exception $e) {<br>            DB::rollBack();<br>            return redirect()-&gt;back()-&gt;with(&#39;error&#39;,  __(&#39;standard_curd_common_label.error&#39;));<br>        }<br><br>        return redirect()-&gt;back()-&gt;with(&#39;error&#39;,  __(&#39;standard_curd_common_label.error&#39;));<br>    }<br><br>    /**<br>     * Display the specified resource.<br>     *<br>     * @param string $id<br>     * @return View<br>     */<br>    public function show(string $id) // : View<br>    {<br>        // You can add logic to fetch and return data for the specific resource here.<br>    }<br><br>    /**<br>     * Show the form for editing the specified resource.<br>     *<br>     * @param string $id<br>     * @return View<br>     */<br>    public function edit(string $id): View<br>    {<br>        try {<br>            $response = $this-&gt;userService-&gt;findById($id);<br>            return view(&#39;admin.user.edit&#39;)-&gt;with([<br>                &#39;data&#39; =&gt; $response,<br>            ]);<br>        } catch (Exception $e) {<br>            return redirect()-&gt;back()-&gt;with(&#39;error&#39;, __(&#39;standard_curd_common_label.error&#39;));<br>        }<br>    }<br><br>    /**<br>     * Update the specified resource in storage.<br>     *<br>     * @param UpdateUserRequest $request<br>     * @param string $id<br>     * @return RedirectResponse<br>     */<br>    public function update(UpdateUserRequest $request, string $id): RedirectResponse<br>    {<br>        try {<br>            $data = $request-&gt;except([&#39;_token&#39;, &#39;_method&#39;]);<br><br>            if (!empty($data[&#39;password&#39;])) {<br>                $data[&#39;password&#39;] = bcrypt($data[&#39;password&#39;]);<br>            } else {<br>                unset($data[&#39;password&#39;]);<br>            }<br><br>            $this-&gt;userService-&gt;update([&#39;id&#39; =&gt; $id], $data);<br>            return redirect()-&gt;back()-&gt;with(&#39;success&#39;, __(&#39;user_module.create_list_edit.user&#39;) . __(&#39;standard_curd_common_label.update_success&#39;));<br>        } catch (Exception $e) {<br>            return redirect()-&gt;back()-&gt;with(&#39;error&#39;, __(&#39;standard_curd_common_label.error&#39;));<br>        }<br>    }<br><br>    /**<br>     * Remove the specified resource from storage.<br>     *<br>     * @param string $id<br>     * @return JsonResponse<br>     */<br>    public function destroy(string $id): JsonResponse<br>    {<br>        try {<br>            $data = $this-&gt;userService-&gt;deleteById($id);<br><br>            if ($data) {<br>                return response()-&gt;json([<br>                    &#39;message&#39; =&gt; __(&#39;user_module.create_list_edit.user&#39;) . __(&#39;standard_curd_common_label.delete&#39;),<br>                    &#39;status_code&#39; =&gt; ResponseAlias::HTTP_OK,<br>                    &#39;data&#39; =&gt; []<br>                ], ResponseAlias::HTTP_OK);<br>            }<br><br>            return response()-&gt;json([<br>                &#39;message&#39; =&gt; __(&#39;user_module.create_list_edit.user&#39;) . __(&#39;standard_curd_common_label.delete_is_not&#39;),<br>                &#39;status_code&#39; =&gt; ResponseAlias::HTTP_BAD_REQUEST,<br>                &#39;data&#39; =&gt; []<br>            ], ResponseAlias::HTTP_BAD_REQUEST);<br>        } catch (Exception $e) {<br>            return response()-&gt;json([<br>                &#39;message&#39; =&gt; __(&#39;standard_curd_common_label.error&#39;),<br>                &#39;status_code&#39; =&gt; ResponseAlias::HTTP_INTERNAL_SERVER_ERROR,<br>                &#39;data&#39; =&gt; []<br>            ], ResponseAlias::HTTP_INTERNAL_SERVER_ERROR);<br>        }<br>    }<br>}</pre><h4>Best Practices</h4><ul><li><strong>Use Dependency Injection</strong>: Avoid directly instantiating repositories inside controllers. Inject them via constructor injection.</li><li><strong>Separation of Concerns</strong>: Keep repositories focused on data handling, and services focused on business logic.</li><li><strong>Use of Interfaces</strong>: Always define interfaces for repositories to improve flexibility and make your code easily testable.</li><li><strong>Testable Code</strong>: Utilize PHPUnit to test repositories by mocking database queries.</li></ul><h4>Conclusion</h4><p>Summarize the benefits of the repository pattern:</p><ul><li><strong>Scalability</strong>: As your application grows, you can easily add more methods to repositories without affecting other parts of the code.</li><li><strong>Code Quality</strong>: Following design patterns such as the repository pattern leads to cleaner, more maintainable code.</li><li><strong>Laravel’s Eloquent Integration</strong>: You can leverage Laravel’s Eloquent ORM in your repository to handle data access while keeping your code structured.</li></ul><p>You can also mention how the repository pattern fits well with other design patterns like the service and factory patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3da491a63e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global Exception Handling and API Response Setup in Laravel 12]]></title>
            <link>https://medium.com/@habibur.rahman.0927/global-exception-handling-and-api-response-setup-in-laravel-11-bc014b7b8880?source=rss-8a636b976b5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc014b7b8880</guid>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Md Habibur Rahman]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 05:21:09 GMT</pubDate>
            <atom:updated>2025-10-19T04:01:20.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Laravel 11 introduces several enhancements to the way developers handle exceptions and set up consistent API responses. This article provides a step-by-step guide on how to manage global exception handling for APIs and implement a standardized response structure.</p><h3>Why Global Exception Handling and Standardized Responses?</h3><p>When building APIs, consistency in error handling and response structure is critical. It improves developer experience and ensures that API consumers have a predictable way to handle success and error responses. Laravel provides powerful tools to make this process efficient and seamless.</p><h3>Setting Up Global Exception Handling</h3><p>Laravel allows you to define global exception handling logic in the render method of the exception handler. Here&#39;s how you can customize it specifically for APIs.</p><h4>Step 1: Customizing the App\Exceptions\Handler</h4><p>Modify the render method of the Handler class to provide a custom response for different types of exceptions.</p><pre>namespace App\Exceptions;<br><br>use Illuminate\Auth\AuthenticationException;<br>use Illuminate\Validation\ValidationException;<br>use Symfony\Component\HttpKernel\Exception\HttpException;<br>use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;<br>use Symfony\Component\HttpKernel\Exception\RouteNotFoundException;<br>use Throwable;<br>use Illuminate\Http\JsonResponse;<br>use Symfony\Component\HttpFoundation\Response;<br><br>class Handler extends \Illuminate\Foundation\Exceptions\Handler<br>{<br>    public function render($request, Throwable $e): JsonResponse<br>    {<br>        if ($request-&gt;is(&#39;api/*&#39;)) {<br>            return match (true) {<br>                $e instanceof AuthenticationException =&gt; response()-&gt;json([<br>                    &#39;success&#39; =&gt; false,<br>                    &#39;message&#39; =&gt; &#39;Unauthorized Request.&#39;,<br>                ], Response::HTTP_UNAUTHORIZED),<br><br>                $e instanceof ValidationException =&gt; response()-&gt;json([<br>                    &#39;success&#39; =&gt; false,<br>                    &#39;message&#39; =&gt; &#39;Validation failed.&#39;,<br>                    &#39;errors&#39; =&gt; $e-&gt;errors(),<br>                ], Response::HTTP_UNPROCESSABLE_ENTITY),<br><br>                $e instanceof NotFoundHttpException =&gt; response()-&gt;json([<br>                    &#39;success&#39; =&gt; false,<br>                    &#39;message&#39; =&gt; &#39;Resource not found.&#39;,<br>                ], Response::HTTP_NOT_FOUND),<br><br>                $e instanceof HttpException =&gt; response()-&gt;json([<br>                    &#39;success&#39; =&gt; false,<br>                    &#39;message&#39; =&gt; $e-&gt;getMessage(),<br>                ], $e-&gt;getStatusCode()),<br><br>                $e instanceof RouteNotFoundException =&gt; response()-&gt;json([<br>                    &#39;success&#39; =&gt; false,<br>                    &#39;message&#39; =&gt; &#39;Route not found.&#39;,<br>                ], Response::HTTP_NOT_FOUND),<br><br>                default =&gt; response()-&gt;json([<br>                    &#39;success&#39; =&gt; false,<br>                    &#39;message&#39; =&gt; &#39;An unexpected error occurred.&#39;,<br>                    &#39;details&#39; =&gt; $e-&gt;getMessage(),<br>                ], Response::HTTP_INTERNAL_SERVER_ERROR),<br>            };<br>        }<br><br>        return parent::render($request, $e);<br>    }<br>}</pre><ol><li>AuthenticationException</li></ol><h4>Explanation:</h4><ul><li>This handles cases where a user attempts to access a protected resource without proper authentication.</li><li>The API responds with a 401 Unauthorized status code.</li><li>The success field is set to false, and a message is included to inform the client that the request is unauthorized.</li></ul><p>2. ValidationException</p><h4>Explanation:</h4><ul><li>This is triggered when validation rules fail during a request (e.g., missing required fields, invalid data format).</li><li>The API responds with a 422 Unprocessable Entity status code.</li><li>The response includes:</li><li>message: General information about the validation failure.</li><li>errors: Detailed errors from the validation process, showing which fields failed and why.</li></ul><p>3. NotFoundHttpException</p><h4>Explanation:</h4><ul><li>This handles cases where a client requests a resource that does not exist.</li><li>The API responds with a 404 Not Found status code.</li><li>A generic message is returned, indicating the resource was not found.</li></ul><p>4. HttpException</p><h4>Explanation:</h4><ul><li>This handles HTTP exceptions (errors explicitly thrown with an HTTP status code).</li><li>The API responds with the status code specified in the exception ($e-&gt;getStatusCode()).</li><li>The message is dynamically set to the exception&#39;s message, allowing more specific error details.</li></ul><p>5. RouteNotFoundException</p><h4>Explanation:</h4><ul><li>This handles cases where the requested route is not defined in the application.</li><li>The API responds with a 404 Not Found status code.</li><li>A message is returned to inform the client that the requested route does not exist.</li></ul><p>6. Default Case (Unexpected Errors)</p><h4>Explanation:</h4><ul><li>This handles any unhandled or unexpected exceptions.</li><li>The API responds with a 500 Internal Server Error status code.</li><li>The response includes:</li><li>message: A generic message indicating an unexpected error.</li><li>details: The actual error message from the exception, which can help with debugging.</li></ul><h3>How It Works</h3><ul><li>The Handler class intercepts all exceptions thrown during API requests.</li><li>Using a match expression, it evaluates the exception type and determines the appropriate response.</li><li>For each exception:</li><li>It constructs a standardized JSON response.</li><li>The success field is always set to false for errors.</li><li>HTTP status codes are accurately assigned based on the exception type.</li></ul><h3>Centralized API Response Methods</h3><p>To ensure a consistent response format across your application, create methods to handle success and error responses in a base controller.</p><h4>Step 2: Abstract Base Controller</h4><p>Create a Controller class in App\Http\Controllers that includes success and error methods.</p><pre>namespace App\Http\Controllers;<br><br>use Illuminate\Foundation\Auth\Access\AuthorizesRequests;<br>use Illuminate\Foundation\Validation\ValidatesRequests;<br>use Illuminate\Http\JsonResponse;<br>use Illuminate\Http\Response;<br><br>abstract class Controller<br>{<br>    use AuthorizesRequests, ValidatesRequests;<br><br>    /**<br>     * Handle a successful response.<br>     *<br>     * @param mixed $result<br>     * @param string $message<br>     * @param int $code<br>     * @return JsonResponse<br>     */<br>    public function success($result, string $message, int $code = Response::HTTP_OK): JsonResponse<br>    {<br>        $response = [<br>            &#39;success&#39; =&gt; true,<br>            &#39;data&#39; =&gt; $result,<br>            &#39;message&#39; =&gt; $message,<br>        ];<br>        return response()-&gt;json($response, $code);<br>    }<br><br>    /**<br>     * Handle an error response.<br>     *<br>     * @param string $errorMessage<br>     * @param array $errors<br>     * @param int $code<br>     * @return JsonResponse<br>     */<br>    public function error(string $errorMessage, array $errors = [], int $code = Response::HTTP_BAD_REQUEST): JsonResponse<br>    {<br>        $response = [<br>            &#39;success&#39; =&gt; false,<br>            &#39;message&#39; =&gt; $errorMessage,<br>            &#39;errors&#39; =&gt; $errors,<br>        ];<br>        return response()-&gt;json($response, $code);<br>    }<br>}</pre><h3>Using the Response Methods in Controllers</h3><p>Now, you can use the success and error methods in any controller that extends the base Controller.</p><pre>namespace App\Http\Controllers\Api;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\User;<br>use Illuminate\Http\Request;<br><br>class UserController extends Controller<br>{<br>    public function index()<br>    {<br>        $users = User::all();<br><br>        return $this-&gt;success($users, &#39;Users retrieved successfully.&#39;);<br>    }<br><br>    public function show($id)<br>    {<br>        $user = User::find($id);<br><br>        if (!$user) {<br>            return $this-&gt;error(&#39;User not found.&#39;);<br>        }<br><br>        return $this-&gt;success($user, &#39;User retrieved successfully.&#39;);<br>    }<br>}</pre><h3>Conclusion</h3><p>By implementing global exception handling and standardized response methods in Laravel 11, you simplify error management and provide a clean, predictable interface for API consumers. This approach improves maintainability and sets the foundation for scalable API development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc014b7b8880" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>