-2

I want to add custom methods for Laravel Query Builder.

I want to have something like this (Methods will be more complicated in further)

<?php

namespace App\Helpers;


class Builder extends \Illuminate\Database\Query\Builder
{
    /**
     * @return $this
     */
    public function whenWhere(): self
    {
        return $this;
    }
}

In code I have

DB::table('items')->select('id')->whenWhere()->get()

And I'm getting error

Call to undefined method Illuminate\\Database\\Query\\Builder::whenWhere()

I know there is a way to use macros in query providers, but I don't want use it because IDE don't see macros, so it is the main reason why I need to accomplish this in another way
*I'm not using models in project.

Kostya GL
  • 62
  • 6
  • I know you said *"I'm not using models in this project"*, but if you do decide to use them, this is trivial; on your `Item` model, you'd use [Model Scopes](https://laravel.com/docs/9.x/eloquent#query-scopes). To add this to the Builder, you probably need to extend it, something like what is being discussed here: https://stackoverflow.com/questions/24555025/how-to-customize-laravels-database-query-builder-make-better-subquery. If you search for "Laravel extend Query Builder", you should be able to find more results/solutions/discussions too. – Tim Lewis Feb 09 '23 at 15:40

1 Answers1

0

You can add public function with prefix scope:

public function scopeWhenWhere($query)
{
    return $query->where('something', 'something');
}

It should let you call like this:

 Builder::select(['column1', 'column2'])->whenWhere()->get();

Also you can extend the function with addition parameters:

public function scopeWhenWhere($query, $param)
{
    return $query->where('something', $param);
}

Now you can put function param like this:

Builder::select(['column1', 'column2'])->whenWhere('ifsomething')->get();
Vasyl Zhuryk
  • 1,228
  • 10
  • 23
  • What is `Builder` in this context? Is it a Model? The question explicitly states *"I'm not using models in project"*... Running this code results in `Class Builder not found`. If that is supposed to be the `Illuminate\Database\Query\Builder`, then you get the error: `Non-static method Illuminate\Database\Query\Builder::select() cannot be called statically`. This does not work, sorry. – Tim Lewis Feb 09 '23 at 16:22