churakovmike/laravel-extended-builder

Laravel extended query builder

1.0 2020-04-22 15:39 UTC

This package is auto-updated.

Last update: 2022-06-22 20:26:02 UTC


README

This package is a good way to organize subqueries of your models.

Requirements

  • laravel 5.5+

Getting started

Install

The package is available on packagist.

composer require churakovmike/laravel-extended-builder

Usage

  1. You need to create a class that will be inherited from ChurakovMike\ExtendedBuilder\ExtendedQuery as an example
<?php

namespace App;

use ChurakovMike\ExtendedBuilder\ExtendedQuery;

/**
 * Class UserQuery
 * @package App
 *
 * @property string $modelClass
 */
class UserQuery extends ExtendedQuery
{
    public function isActive()
    {
        return $this->where('status', true);
    }
    
    public function hasName($name)
    {
        return $this->where('name', $name);
    }
}
  1. Then you need to add a method to the main model that will call query builder.
<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * Class User
 * @package App
 */
class User extends Authenticatable
{
    public static function where()
    {
        return new \App\UserQuery(get_called_class());
    }
}
  1. Now you can call subqueries from extended query, as well as use regular Bulder methods, see an example
$user = User::where()
        ->isActive()
        ->first();

Function call chain example:

$user = User::where()
        ->isActive()
        ->hasName('Mike')
        ->first();