a Laravel package help you to execute more effective databases queries.

Overview

logo

Laravel Query Helper

Laravel Query Helper was developed for laravel 7.2+ to help you optimizing sql queries, this package will contain all advanced sql queries to Help us write better and faster queries and clean code.

Features

  • Update multi records in one query.
  • Chunk a large query to smaller pieces.

Installation

1 - Dependency

The first step is using composer to install the package and automatically update your composer.json file, you can do this by running:

composer require kmlaravel/laravel-query-helper
  • Laravel uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.

2 - Copy the package providers to your local config with the publish command, this will publish asset and config:
php artisan vendor:publish --provider="KMLaravel\\KMLaravel\QueryHelper\Facade\QueryHelperFacade\Providers\\KMLaravel\QueryHelper\Facade\QueryHelperFacadeServiceProviders"
  • or you may publish asset and config separately.

php artisan vendor:publish --tag=query-helper-config

Basic usage

Suppose we have a group of users who have an id and a name and we have an array to update each user with a new name as in the following example

    $usersDataBeforeUpdate = [
        ['id'  => 1, 'name' => 'example before update 1'],
        ['id'  => 2, 'name' => 'example before update 2'],
        ['id'  => 3, 'name' => 'example before update 2'],
     ];
    $usersDataToUpdate = [
        ['id'  => 1, 'name' => 'example after update 1'],
        ['id'  => 2, 'name' => 'example after update 2'],
        ['id'  => 3, 'name' => 'example after update 2'],
    ];

    // so the traditional way to that,
    // loop through $usersDataBeforeUpdate and fetch each user with specific (id, name)
    // and update his name with new name
    // and this will execute a query for each record, for the above array, the request will execute 3 queries
    //  what if we want to update 1000 records previously? 
    
    foreah($usersDataToUpdate as $user){
        User::find($user['id'])->update(['name' => $user['name']]);
    }

So the query helper will help you optimize this process, see the following explanation:

setIds($ids) ->setValues($values) ->setTableName($tableName) // change this parameter value to your database table name. ->setFieldToUpdate($columnToUpdate) // change this parameter value to your database column name. ->bindIdsWithValues() ->executeUpdateMultiRows(); // this will execute only one query. ">
    $usersDataBeforeUpdate = [
        ['id'  => 1, 'name' => 'example before update 1'],
        ['id'  => 2, 'name' => 'example before update 2'],
        ['id'  => 3, 'name' => 'example before update 2'],
     ];

    $usersDataToUpdate = [
        ['id'  => 1, 'name' => 'example after update 1'],
        ['id'  => 2, 'name' => 'example after update 2'],
        ['id'  => 3, 'name' => 'example after update 2'],
    ];

    $ids = [];
    $values = [];
    $cases = [];
    $tableName = 'users';
    $columnToUpdate = 'name';
    foreach($usersDataToUpdate as $user){

       array_push($ids , $user['id']);

       array_push($values , $user['name']);

       // if you want to set your cases in query.
       $cases[] = "WHEN id = {$user['id']} then ".$user['name'];
    }

    // if you want to set your cases in query.
    $cases = implode(' ', $cases);

    \KMLaravel\QueryHelper\Facade\QueryHelperFacade::updateInOneQueryInstance()
            ->setIds($ids)
            ->setValues($values)
            ->setTableName($tableName) // change this parameter value to your database table name.
            ->setFieldToUpdate($columnToUpdate) // change this parameter value to your database column name.
            ->bindIdsWithValues()
            ->executeUpdateMultiRows();

    // this will execute only one query.

What if you want to put your own Cases ? okay we support that.

    $query = \KMLaravel\QueryHelper\Facade\QueryHelperFacade::updateInOneQueryInstance()
            ->setIds($ids)
            ->setCasues($cases)
            ->setTableName($tableName) // change this parameter value to your database table name.
            ->setFieldToUpdate($columnToUpdate) // change this parameter value to your database column name.
            ->executeUpdateMultiRows();

What if you want dump the query which will execute ? okay we support that.

    $query = \KMLaravel\QueryHelper\Facade\QueryHelperFacade::updateInOneQueryInstance()
            ->setIds($ids)
            ->setValues($values)
            ->setTableName($tableName) // change this parameter value to your database table name.
            ->setFieldToUpdate($columnToUpdate) // change this parameter value to your database column name.
            ->buildStatement()
            ->getQuery();
    dd($query);

What if you want to reduce these lines in one line ? okay we support that.

    $query = \KMLaravel\QueryHelper\Facade\QueryHelperFacade::updateInOneQueryInstance()
            ->fastUpdate($tableName , $ids , $values , $columnToUpdate);
    dd($query);

In some databases, you can't do any process that require more than 65K of parameters, so we have to chunk your large query to smaller pieces, and we can do that for you ar effective way.

    // Suppose we have a group of users, let say's we have 100k items to insert.
    $users = [
    ['name' => 'example 1'],
    ['name' => 'example 2'],
    ['name' => 'example 3'],
    ['name' => 'example 4'],
    ...
    ];   
    \KMLaravel\QueryHelper\Facade\QueryHelperFacade::updateInOneQueryInstance()
        ->setAllowedWhereInQueryNumber(2000) // chunk size and you can update the default value from query_helper.php config file
        ->checkIfQueryAllowed($users , function ($data){
            User::insert($data);
        });

Changelog

Please see the CHANGELOG for more information about what has changed or updated or added recently.

Security

If you discover any security related issues, please email them first to [email protected], if we do not fix it within a short period of time please open new issue describe your problem.

Credits

karam mustafa

You might also like...
You already have your dream house? Sam Building will help you find the perfect home.
You already have your dream house? Sam Building will help you find the perfect home.

SAM BUILDING Setup Fork or clone this repo! git clone github.com/Igorballo/Real-Estate-App.git Installation des dépendances npm install #or yarn insta

Electrik is a full-featured, open-source, starter-kit to help you build you your SaaS application.
Electrik is a full-featured, open-source, starter-kit to help you build you your SaaS application.

Electrik Electrik is a full-featured and open-source stater-kit for for your next SaaS application. It's built on top of Laravel, Livewire, neerajsoha

this package can help you to test race condition in Laravel Feature Test
this package can help you to test race condition in Laravel Feature Test

Laravel Async Testing this package can help you to test race condition in Laravel Feature Test Requirements Laravel versions 5.7, 6.x, 7.x and 8.x PHP

This package should help you with creating and managing a Laravel DDD Application

This package should help you with creating and managing a Laravel DDD Application. This package is heavily inspired by "Laravel beyond CRUD" from Spatie.

Relational Metrics - lararvel package help you to make your metrics easier
Relational Metrics - lararvel package help you to make your metrics easier

Relational Metrics This package will help you to make your metrics easier, You could get metrics about your Models, Models depending on their relation

This package aims to help you standardize all your API responses in a simple and structured way.

Laravel API Response This package aims to help you standardize all your API responses in a simple and structured way. By default, the stucture of the

Fullstack komponents to write Forms, Queries and Menus in Laravel

kompo.io • Documentation • Demos • Twitter kompo/kompo kompo/kompo is a library of Fullstack Komponents to help you write forms, queries and menus in

Trait for Laravel testing to count/assert about database queries

counts_database_queries Trait for Laravel testing to count/assert about database queries Installing composer require ohffs/counts-database-queries-tra

This template should help get you started developing with laravel 9 + Vue 3 in Vite + Tailwind

simple-project This template should help get you started developing with laravel 9 + Vue 3 in Vite + Tailwind

Releases(v1.4.0)
Owner
karam mustafa
Full Stack Web Developer, I work on large and small projects and love creating packages, and all about open source.
karam mustafa
Laravel Query Helper was developed for laravel 7.2+ to help you optimize sql queries

Laravel Query Helper Laravel Query Helper was developed for laravel 7.2+ to help you optimize sql queries, this package will contain all advanced SQL

Syrian Open Source 15 Nov 20, 2022
Log executed Laravel SQL queries and their line number and more

A lightweight laravel package for logging executed SQL queries, line number and more

Md.Harun-Ur-Rashid 31 Dec 21, 2022
Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily.

DevMakerLab/Laravel-Filters Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily. Insta

DevMakerLab 19 Feb 20, 2022
Deploy and execute non-PHP AWS Lambda functions from your Laravel application.

Sidecar for Laravel Deploy and execute non-PHP AWS Lambda functions from your Laravel application. Read the full docs at hammerstone.dev/sidecar/docs.

Hammerstone 624 Dec 30, 2022
Laravel 4.* and 5.* service providers to handle PHP errors, dump variables, execute PHP code remotely in Google Chrome

Laravel 4.* service provider for PHP Console See https://github.com/barbushin/php-console-laravel/releases/tag/1.2.1 Use "php-console/laravel-service-

Sergey 73 Jun 1, 2022
Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Artisan Api There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API

Alireza 11 Sep 7, 2022
Testbench Component is the de-facto package that has been designed to help you write tests for your Laravel package

Laravel Testing Helper for Packages Development Testbench Component is the de-facto package that has been designed to help you write tests for your La

Orchestra Platform 1.9k Dec 29, 2022
The missing laravel helper that allows you to inspect your eloquent queries with it's bind parameters

Laravel Query Inspector The missing laravel helper that allows you to ispect your eloquent queries with it's bind parameters Motivations Let's say you

Mouad ZIANI 59 Sep 25, 2022
Extend Laravel PHP framework to make working with Aiven databases simpler

Aiven Commands for Laravel ✨ Add some Aiven magic to your Laravel project ✨ This Laravel package provides some aiven commands for artisan to help with

Aiven 8 Aug 19, 2022
Simple Laravel 5 package to dump all running queries on the page.

Abandoned: Use this package instead Laravel QueryDumper Introduction Simple Laravel 5 package to dump all running queries on the page. If it's SELECT

Sarfraz Ahmed 24 May 14, 2020