seonppc's avatar

DB instance without using Facade

Hello,

I have searched everywhere but could not found any solution, what i have done so far...

I have installed Lumen. Filled credentials in .env file and migrated I have create a UserRepository class which has find and delete method.

I want to use Lumen basic mysql database query in my repository class without using any support like facade or Eloquent..

I can use following...

$users = DB::select('select * from users where active = ?', [1]);

But how can i use some thing like db->select() without activating facade and eloquent.

Please help. @bashy @JarekTkaczyk @pmall @bobbybouwmann @mstnorris

Thanks

0 likes
6 replies
Kryptonit3's avatar
use Illuminate\Database\DatabaseManager;

class Myclass
{
    public function __construct(DatabaseManager $database)
    {
        $this->db = $database;
    }

  public function blah()
  {
    $this->db->connection()->table('table')->select('*');
  }
}

Something like that.

seonppc's avatar

@Kryptonit3 Thanks for your answer, i was looking for something similar but got following i used this approach...

BindingResolutionException in Container.php line 823:
Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class Illuminate\Database\DatabaseManager
seonppc's avatar

@RachidLaasri Got following error...

ReflectionException in Container.php line 790:
Class Illuminate\Contracts\Database does not exist
Kryptonit3's avatar

Make a helper file with this

function db()
{
    return app()->make('db');
}

Then you can do this

db()->select('select * from users')

Which would output your users in an array

array:4 [▼
  0 => {#449 ▼
    +"id": 1
    +"username": "user"
    +"email": "user282815@user.com"
    +"password": "$2y$10$pflf89ev8RU/fxnUWEoRNObAqQPNu066a6eQldcoTzSfi6Zy9zdcG"
    +"remember_token": null
    +"deleted_at": null
    +"created_at": "2015-06-29 19:41:44"
    +"updated_at": "2015-06-29 19:41:44"
  }
  1 => {#450 ▶}
  2 => {#451 ▶}
  3 => {#452 ▶}
]

General idea on how to load helper file - http://laravel-recipes.com/recipes/50/creating-a-helpers-file (for L4, but similar for L5)

Mike-e's avatar

Hi @seonppc ,

You can do this natively

    // Return an instance of \Illuminate\Database\DatabaseManager
    app('db')->...

Regards.

2 likes

Please or to participate in this conversation.