An extended laravel eloquent WHERE method to work with sql LIKE operator.

Overview

Laravel Eloquent WhereLike

An extended laravel eloquent WHERE method to work with sql LIKE operator.

Inspiration

The idea of this package comes from one of the Freek's Blog Post. I had developed this macro, which is a slightly different variation of what is described there and using it for years. So I have decided to release this as a package, so that I don't have to copy paste same code again and again and at the same time others can use this to save a little bit of their time.

Installation

Require the package using composer:

composer require touhidurabir/eloquent-wherelike

To publish the config file:

php artisan vendor:publish --provider="Touhidurabir\EloquentWherelike\EloquentWherelikeServiceProvider" --tag=config

Configurations

The config file contains one important configuration option; the operator which defines the SQL operator that will be used to perform the query. By default it's set to LIKE, but you can update it as you see fit. For example, for PostgreSQL, it should be set to ILIKE.

Usage

As this whereLike method is defined as a macro, just use it like any eloquent method.

$users = User::whereLike(['email', 'name'], 'search_term')->get();

The first param will be the targeted columns to search for and second one is the actual search term.

One big advantage of this package is that is allows searches based on model relations. For example, say a user as one profile, and the profile table has first_name and last_name columns. In order to search users whose first name match, we can do following:

$users = User::whereLike(
    [
        'email', 
        'name',
        '.profile[first, last_name]'
    ], 'search_term'
)->get();

Here, notice the syntax

'.profile[first, last_name]'

the initial dot(.) defines what is the relation, where the opeing and closing third bracked([]) define the columns of that relation model/table. In this example, we are also looking into the profile relations first_name and last_name columns.

A more advance example from one of my projects:

$campaigns = $campaigns->whereLike(
    [
        'title', 
        'description',
        '.user.profile[first_name, last_name]',
        '.categories[name]',
        '.campaigntype[title]',
        '.team[name]'
    ], 
    $search
)->get();

In the above example, we are searching for all campaigns based on, not only from campaigns table column, but from it's relation models' columns also.

Now, if we want to write the whole thing without using this package, we would have to write:

$campaigns = $campaigns->where(function ($query) use ($search) {
    $query
        ->where('title', 'LIKE', '%' . $search . '%')
        ->orWhere('description', 'LIKE', '%' . $search . '%')
        ->orWhereHas('user', function($query) use ($search) {
            $query->whereHas('profile', function($query) use ($search) {
                $query->where('first_name', 'LIKE', '%' . $search . '%')
                ->orWhere('last_name', 'LIKE', '%' . $search . '%');
            });
        })
        ->orWhereHas('categories', function($query) use ($search) {
            $query->where('name', 'LIKE', '%' . $search . '%');
        })
        ->orWhereHas('campaigntype', function($query) use ($search) {
            $query->where('title', 'LIKE', '%' . $search . '%');
        })
        ->orWhereHas('team', function($query) use ($search) {
            $query->where('name', 'LIKE', '%' . $search . '%');
        });
})->get();

This whereLike saves us so much time this way! 🎉

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

You might also like...
Sqlcommenter is a plugin/middleware/wrapper to augment SQL statements from laravel

sqlcommenter is a plugin/middleware/wrapper to augment SQL statements from laravel with comments that can be used later to correlate user code with SQL statements.

Projeto de um sistema de pedidos de uma Pizzaria. Feito durante o curso
Projeto de um sistema de pedidos de uma Pizzaria. Feito durante o curso "SQL - Básico ao Avançado" Dísponível na Udemy pelo instrutor Matheus Baptisti

PJ-Pizzaria Este projeto é um sistema de pedidos de uma Pizzaria. O objeto de estudo aqui é a conexão de PHP + BD, PHP e a WEB, Regras de negócio comp

Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model-myPoint = new Point(1,2); //lat

A simple to use opinionated ERP package to work with Laravel

Laravel ERP A simple to use opinionated ERP package to work with Laravel Installation You can install the package via composer: composer require justs

laravel-wallet - Easy work with virtual wallet.
laravel-wallet - Easy work with virtual wallet.

laravel-wallet - Easy work with virtual wallet. [Documentation] [Get Started] [Документация] [Как начать] Vendor: bavix Package: laravel-wallet Versio

Laravel package to work with geospatial data types and functions.

Laravel Spatial Laravel package to work with geospatial data types and functions. For now it supports only MySql Spatial Data Types and Functions. Sup

This package allows you to easily work with NanoID in your Laravel models.
This package allows you to easily work with NanoID in your Laravel models.

Laravel Model UUIDs Introduction Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses

Localization Helper - Package for convenient work with Laravel's localization features and fast language files generation
Localization Helper - Package for convenient work with Laravel's localization features and fast language files generation

Localization Helper Package for convenient work with Laravel's localization features and fast language files generation. Installation Via Composer $ c

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Releases(2.0.1)
Owner
Touhidur Rahman
Husband, father, big time documentary tv series lover and software engineer . Passionate about PHP, Laravel, Ruby on Rails, Vue.js and C/C++ . Learning Rust .
Touhidur Rahman
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022
This package provides extended support for our spatie/enum package in Laravel.

Laravel support for spatie/enum This package provides extended support for our spatie/enum package in Laravel. Installation You can install the packag

Spatie 264 Dec 23, 2022
A collection of classes to be extended/used in laravel apps for quick development

laraquick A collection of classes to be extended/used in laravel applications for quick development. Introduction The library contains traits with wel

Ezra Obiwale 35 Dec 13, 2022
Scout Extended: The Full Power of Algolia in Laravel

Documentation • Community Forum • Stack Overflow • Report a bug • FAQ • Support To dig right in, visit the Scout Extended documentation. Scout Extende

Algolia 378 Dec 1, 2022
cybercog 996 Dec 28, 2022
A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

Λгi 25 Aug 31, 2022
`dd` is a helper method in Laravel. This package will add the `dd` to your application.

dd dd is a helper method in Laravel. This package will add the dd to your application. Install Run composer require larapack/dd 1.* For Laravel Larave

Larapack 109 Dec 26, 2022
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
A Laravel Artisan SQL Interactive Interface

sqli A Laravel 4 & 5 Artisan SQL Interactive Interface, plus a handful of Artisan commands to execute SQL queries. sqli It's like tinker for SQL, just

Antonio Carlos Ribeiro 61 Apr 18, 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