<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Joton Sutradhar</title>
    <description>The latest articles on DEV Community by Joton Sutradhar (@jotonsutradhar).</description>
    <link>https://dev.to/jotonsutradhar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1229164%2F929178a2-9581-4ba1-b237-28f0309bb7df.jpg</url>
      <title>DEV Community: Joton Sutradhar</title>
      <link>https://dev.to/jotonsutradhar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jotonsutradhar"/>
    <language>en</language>
    <item>
      <title>Creating A Laravel CRUD Application With The Repository Pattern</title>
      <dc:creator>Joton Sutradhar</dc:creator>
      <pubDate>Sat, 01 Feb 2025 14:19:24 +0000</pubDate>
      <link>https://dev.to/jotonsutradhar/creating-a-laravel-crud-application-with-the-repository-pattern-505o</link>
      <guid>https://dev.to/jotonsutradhar/creating-a-laravel-crud-application-with-the-repository-pattern-505o</guid>
      <description>&lt;p&gt;Laravel is a powerful PHP framework that simplifies web application development. When building a CRUD (Create, Read, Update, Delete) application, using the Repository Pattern can make your code cleaner, more maintainable, and easier to test. In this blog, we'll guide you through setting up a Laravel project with the Repository Pattern for a CRUD operation.&lt;/p&gt;

&lt;h1&gt;
  
  
  Project Structure
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;laravel-crud-repository/
│── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── ProductController.php
│   ├── Models/
│   │   ├── Product.php
│   ├── Providers/
│   │   ├── RepositoryServiceProvider.php
│   ├── Repositories/
│   │   ├── Interfaces/
│   │   │   ├── ProductRepositoryInterface.php
│   │   ├── Eloquent/
│   │   │   ├── ProductRepository.php
│── database/
│   ├── migrations/
│   │   ├── xxxx_xx_xx_create_products_table.php
│── routes/
│   ├── api.php
│── .env
│── composer.json
│── artisan

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Step 1: Install Laravel
&lt;/h1&gt;

&lt;p&gt;If you haven't installed Laravel yet, run the following command to create a new Laravel project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer create-project laravel/laravel laravel-crud-repository
cd laravel-crud-repository
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Step 2: Configure Database
&lt;/h1&gt;

&lt;p&gt;Update your &lt;code&gt;.env&lt;/code&gt; file with your database credentials:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud_repository
DB_USERNAME=root
DB_PASSWORD=
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run migrations to set up the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Step 3: Create a Model and Migration
&lt;/h1&gt;

&lt;p&gt;Generate a model with migration for a sample entity, like Product:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:model Product -m
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Modify the migration file in &lt;code&gt;database/migrations/xxxx_xx_xx_xxxxxx_create_products_table.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table-&amp;gt;id();
        $table-&amp;gt;string('name');
        $table-&amp;gt;text('description')-&amp;gt;nullable();
        $table-&amp;gt;decimal('price', 8, 2);
        $table-&amp;gt;timestamps();
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the migration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Step 4: Implement the Repository Pattern
&lt;/h1&gt;

&lt;h2&gt;
  
  
  1. Create the Interface in Interfaces Folder
&lt;/h2&gt;

&lt;p&gt;Create a new folder &lt;code&gt;app/Repositories/Interfaces/&lt;/code&gt; and then the &lt;code&gt;ProductRepositoryInterface.php&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Repositories\Interfaces;

interface ProductRepositoryInterface
{
    public function getAll();
    public function getById($id);
    public function create(array $data);
    public function update($id, array $data);
    public function delete($id);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  2. Implement the Repository in the Eloquent Folder
&lt;/h1&gt;

&lt;p&gt;Create the &lt;code&gt;Eloquent&lt;/code&gt; folder inside &lt;code&gt;Repositories/&lt;/code&gt; and create &lt;code&gt;ProductRepository.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Repositories\Eloquent;

use App\Models\Product;
use App\Repositories\Interfaces\ProductRepositoryInterface;

class ProductRepository implements ProductRepositoryInterface
{
    public function getAll()
    {
        return Product::all();
    }

    public function getById($id)
    {
        return Product::findOrFail($id);
    }

    public function create(array $data)
    {
        return Product::create($data);
    }

    public function update($id, array $data)
    {
        $product = Product::findOrFail($id);
        $product-&amp;gt;update($data);
        return $product;
    }

    public function delete($id)
    {
        return Product::destroy($id);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  3. Bind the Repository in the Service Provider
&lt;/h1&gt;

&lt;p&gt;Run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:provider RepositoryServiceProvider
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Modify &lt;code&gt;app/Providers/RepositoryServiceProvider.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Repositories\Interfaces\ProductRepositoryInterface;
use App\Repositories\Eloquent\ProductRepository;

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this-&amp;gt;app-&amp;gt;bind(ProductRepositoryInterface::class, ProductRepository::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the provider in &lt;code&gt;config/app.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;App\Providers\RepositoryServiceProvider::class,
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Create a Controller and Inject the Repository
&lt;/h2&gt;

&lt;p&gt;Modify &lt;code&gt;app/Http/Controllers/ProductController.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Http\Controllers;

use App\Repositories\Interfaces\ProductRepositoryInterface;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    protected $productRepository;

    public function __construct(ProductRepositoryInterface $productRepository)
    {
        $this-&amp;gt;productRepository = $productRepository;
    }

    public function index()
    {
        return response()-&amp;gt;json($this-&amp;gt;productRepository-&amp;gt;getAll());
    }

    public function store(Request $request)
    {
        $data = $request-&amp;gt;validate([
            'name' =&amp;gt; 'required|string|max:255',
            'description' =&amp;gt; 'nullable|string',
            'price' =&amp;gt; 'required|numeric',
        ]);

        return response()-&amp;gt;json($this-&amp;gt;productRepository-&amp;gt;create($data));
    }

    public function show($id)
    {
        return response()-&amp;gt;json($this-&amp;gt;productRepository-&amp;gt;getById($id));
    }

    public function update(Request $request, $id)
    {
        $data = $request-&amp;gt;validate([
            'name' =&amp;gt; 'sometimes|string|max:255',
            'description' =&amp;gt; 'nullable|string',
            'price' =&amp;gt; 'sometimes|numeric',
        ]);

        return response()-&amp;gt;json($this-&amp;gt;productRepository-&amp;gt;update($id, $data));
    }

    public function destroy($id)
    {
        return response()-&amp;gt;json(['deleted' =&amp;gt; $this-&amp;gt;productRepository-&amp;gt;delete($id)]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 6: Define API Routes
&lt;/h2&gt;

&lt;p&gt;Modify &lt;code&gt;routes/api.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Http\Controllers\ProductController;

Route::apiResource('products', ProductController::class);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 7: Test the API
&lt;/h2&gt;

&lt;p&gt;Run the Laravel development server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Test using Postman or cURL:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get all products:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X GET http://127.0.0.1:8000/api/products
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Create a product:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X POST -H "Content-Type: application/json" \
  -d '{"name": "Laptop", "description": "A gaming laptop", "price": 1500}' \
  http://127.0.0.1:8000/api/products
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Final Thoughts
&lt;/h1&gt;

&lt;p&gt;By organizing repositories into separate &lt;code&gt;Interfaces&lt;/code&gt; and &lt;code&gt;Eloquent&lt;/code&gt; folders, this approach makes your Laravel project more scalable and structured. This Repository Pattern ensures loose coupling, making it easier to switch to a different data source in the future.&lt;/p&gt;

&lt;p&gt;Now you have a Laravel project following the Repository Pattern for CRUD operations! 🚀 Let me know if you have any questions!&lt;/p&gt;

&lt;p&gt;Checkout my portfolio here&lt;br&gt;
&lt;a href="https://jotonsutradhar.com/" rel="noopener noreferrer"&gt;Joton Sutradhar&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>mysql</category>
      <category>programming</category>
    </item>
    <item>
      <title>Check changes with isDirty() &amp; getChanges() in Laravel Eloquent Model</title>
      <dc:creator>Joton Sutradhar</dc:creator>
      <pubDate>Wed, 20 Dec 2023 05:45:53 +0000</pubDate>
      <link>https://dev.to/jotonsutradhar/check-changes-with-isdirty-getchanges-in-laravel-eloquent-model-18ef</link>
      <guid>https://dev.to/jotonsutradhar/check-changes-with-isdirty-getchanges-in-laravel-eloquent-model-18ef</guid>
      <description>&lt;p&gt;Before diving into &lt;code&gt;isDirty()&lt;/code&gt; &amp;amp; &lt;code&gt;getChanges()&lt;/code&gt;, let's have some brief about Laravel Eloquent Model.&lt;/p&gt;

&lt;h2&gt;
  
  
  Laravel Eloquent Model
&lt;/h2&gt;

&lt;p&gt;Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with a database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well. To see more, checkout &lt;a href="https://laravel.com/docs/10.x/eloquent" rel="noopener noreferrer"&gt;Laravel Eloquent&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  isDirty()
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;isDirty()&lt;/code&gt; is used BEFORE save, to see what attributes were changed between the time when it was retrieved from the database and the time of the call. If there is any change the &lt;code&gt;isDirty()&lt;/code&gt; method will return &lt;code&gt;true&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
* Determine if the model or any of the given attribute(s) have been modified.
*
* @param  array|string|null  $attributes
* @return bool
*/
public function isDirty($attributes = null)
{
    return $this-&amp;gt;hasChanges(
       $this-&amp;gt;getDirty(), is_array($attributes) ? $attributes : func_get_args()
    );
}

/**
* Determine if any of the given attributes were changed.
*
* @param  array  $changes
* @param  array|string|null  $attributes
* @return bool
*/
protected function hasChanges($changes, $attributes = null) {
   // If no specific attributes were provided, we will just see if the dirty array
   // already contains any attributes. If it does we will just return that this
   // count is greater than zero. Else, we need to check specific attributes.
   if (empty($attributes)) {
       return count($changes) &amp;gt; 0;
   }

   // Here we will spin through every attribute and see if this is in the array of
   // dirty attributes. If it is, we will return true and if we make it through
   // all of the attributes for the entire array we will return false at end.
   foreach (Arr::wrap($attributes) as $attribute) {
       if (array_key_exists($attribute, $changes)) {
           return true;
       }
   }


   return false;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  getChanges()
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;getChanges()&lt;/code&gt; is used AFTER save, to see that attributes were changed/updated in the last save. Eloquent models have two protected arrays, &lt;code&gt;$original&lt;/code&gt; and &lt;code&gt;$changes&lt;/code&gt;, which contain the attributes as they were when fetched from storage and the attrbirutes which have been modified, respectively. The &lt;code&gt;getChanges()&lt;/code&gt; method returns the modified changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
* Get the attributes that were changed.
*
* @return array
 */
public function getChanges()
{
   return $this-&amp;gt;changes;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To get more details checkout &lt;a href="https://github.com/laravel/framework/blob/1bbe5528568555d597582fdbec73e31f8a818dbc/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L1066" rel="noopener noreferrer"&gt;this!&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Example
&lt;/h2&gt;

&lt;p&gt;let's have an example of &lt;code&gt;isDirty()&lt;/code&gt; &amp;amp; &lt;code&gt;getChanges()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Fetch user data from User model
$user = User::findOrFail(1);
$user-&amp;gt;name = "Updated Name";
$user-&amp;gt;email = "updated@email.com";

// check the model has changed
if ($user-&amp;gt;isDirty()) {
    $user-&amp;gt;save();
}

// check the model attribute has changed
if ($user-&amp;gt;isDirty('email')) {
    $user-&amp;gt;save();
}

// wasChanged() is a boolean indicating if the model was modified during the current request lifecycle.
if (!$user-&amp;gt;wasChanged()) {
   $changes = $user-&amp;gt;getChanges();
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, isDirty() &amp;amp; getChanges() methods help you to track and manage the changes in Eloquent Model. Xdddddd teda🤓.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
