Search code examples
laraveleloquentlaravel-11

Laravel eloquent version change


Check https://github.com/hilal-najem3/composers.git for composers.lock

I have the following code:

$where = [
    ['warehouse_id', $warehouse->id],
    ['product_id', $product->id],
    ['section_id', $sectionId]
];
$orWhere = [
    ['to_warehouse_id', $warehouse->id],
    ['product_id', $product->id],
    ['section_id', $sectionId]
];

$transactions = InventoryTransaction::where($where)->orWhere($orWhere)->get();

So query is from print_r(InventoryTransaction::where($where)->orWhere($orWhere)->toSql());

select*from `inventory_transactions`where((`warehouse_id`=?and `product_id`=?and `section_id`=?)or(`to_warehouse_id`=?and `product_id`=?and `section_id`=?))and `inventory_transactions`.`deleted_at`is null

I did composer update and had to change the above to:

$transactions = InventoryTransaction::where($where)->get();
$t = InventoryTransaction::where($orWhere)->get();
$transactions = $transactions->merge($t);

So query became from print_r(InventoryTransaction::where($where)->orWhere($orWhere)->toSql());

select * from `inventory_transactions` where ((`warehouse_id` = ? and `product_id` = ? and `section_id` = ?) or (`to_warehouse_id` = ? or `product_id` = ? or `section_id` = ?)) and `inventory_transactions`.`deleted_at` is null

Or else I will have duplicates, I had to revert the composer for it to work!! Anything I should do to keep my app updated as in do composer update and keep the above code. Note there are tons of places that need to be changed if that is fixed. This way I can't update to future versions!!


Solution

  • The solution is to create a CustomQueryBuilder:

    <?php
    
    namespace App\Database;
    
    use Illuminate\Database\Eloquent\Builder;
    
    class CustomQueryBuilder extends Builder
    {
        public function orWhere($column, $operator = null, $value = null, $boolean = 'or')
        {
            // If $column is an array (multiple conditions), wrap it properly
            if (is_array($column)) {
                return parent::orWhere(function ($query) use ($column) {
                    $query->where($column);
                });
            }
    
            return parent::orWhere($column, $operator, $value, $boolean);
        }
    }
    
    

    And the n create a new Model called BaseModel which extends Model:

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use App\Database\CustomQueryBuilder;
    
    class BaseModel extends Model
    {
        public function newEloquentBuilder($query)
        {
            return new CustomQueryBuilder($query);
        }
    }
    

    And extend from it instead of Model like class InventoryTransaction extends BaseModel