Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.

quyle92 liked this thread

1

Have a look at this:

http://laravel-recipes.com/recipes/50/creating-a-helpers-file

You can create a helpers file where you can throw random functions in.

0

@Gouvi When I tried to do that I run into the same issue as before. Because that function is a modified increment() function which resides in Vendor/Laravel/Framework/src/Illuminate/Query/builder.php

So when I'm running it in let's say your example of App\helpers.php using that function above, it will now error to:

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

Making custom methods of my own is not a problem but extending/copy/modifying from an existing core function method doesn't seem to work outside of that builder.php path.

Last updated 9 years ago.
0

Come on! Still nobody has an answer to this? It's frustrating

0

Hopefully this helps, and not being at a computer makes it hard for me to verify, but I would do the following. I would create a class, either taking in the query builder instance or extending it. I would then create a service provider and swap out the underlying 'db' instance in the app. Additionally I would make sure I adjusted the DB facade to point to the newly created class. Then I would start making my customers i m functions and see if they as being surfaced on the facade/db in the IoC.

I'm travelling now with no laptop to try it on, but I'll check back. If you haven't figured it the problem and I can solve it like I'm thinking, I'll post the code. Good luck in the mean time!!

0

Ok, after a prolonged absence, here goes ;)

I did this all in a fresh install of L5.1

I created a file in the app folder (MyDBClass.php)

namespace App;

use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Connectors\ConnectionFactory;

class MyDBClass extends DatabaseManager
{
    public function __construct($app, ConnectionFactory $factory)
    {
        parent::__construct($app, $factory);
    }

    public function myFunction()
    {
        dd('here');
    }
}

Then in my AppServiceProvider.php (under app/Providers), in the register() function, I added the following.

$this->app->singleton('db', function ($app) {
    return new MyDBClass($app, $app['db.factory']);
});

And to test, I made a test console command, but you can use a closure as well. The code I used looked like this.

dd(\DB::myFunction());

Thinking about this, you could also create your own facade (still using the DB as your facade - see the app/config.php file) vs doing the app->singleton. This may be a more appropriate way, but both should work.

Hope this helps!

Last updated 8 years ago.
0

And re-reading this... you may want to just have a base Model. Since I'm unsure if you want a function on the DB facade (shown above) or if you want a function on all your models, I'll also show you how to make a function availabale to all your models. There's 1 of 2 ways...

Method 1: Class extension. Create a base model and make it abstract. (I made mine in the app folder)

namespace App;

use Illuminate\Database\Eloquent\Model;

abstract class BaseModel extends Model
{
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    }

    public function myFunction()
    {
        dd('inherited function');
    }
    
}

Then all you need to do is extend the base model.

class User extends BaseModel {
}

Method 2: Trait. I created mine in the app folder again (SomeTrait.php)

namespace App;

trait SomeTrait
{

    public function myFunction()
    {
        dd('function via trait');
    }

}

Then to implement...

class User extends Illuminate\Database\Eloquent\Model {
   use SomeTrait;
}

Hope this helps more :P

Good luck!

0

After some read I found this repository showing how to use the macro method of the builder. Is really simple and really clean, just create a Provider and register the macro withing the register method and call it directly by its name.

laravel-builder-macros

From the source:

namespace Kevinsimard\BuilderMacros\Providers;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\ServiceProvider;
class OrderByRandomServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register()
    {
        Builder::macro('orderByRandom', function () {
            $randomFunctions = [
                'mysql' => 'RAND()',
                'pgsql' => 'RANDOM()',
                'sqlite' => 'RANDOM()',
                'sqlsrv' => 'NEWID()',
            ];
            $driver = $this->getConnection()->getDriverName();
            return $this->orderByRaw($randomFunctions[$driver]);
        });
    }
}
Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

bustarice bustarice Joined 10 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.