pdc

Eloquent query picking wrong database for the User model

Posted 5 months ago by pdc

I'm currently setting up my own role-based access-control-system on my website.

You can add Entities (eg. an Artist).
        |
    permissions
        |
You can add Roles (eg. Administrator, Blogger, Developer).
        |
    role_user
        |
The users are located within another database (the Internal database) in order to reuse the authentication

I'm able to assign a role to a user (eazy peazy), to assign a permission for an entity to a role (eazy peazy).

But when I'm trying to check the permission for a user, odd things happen.

config/database.php

mysql       ->  MusicDemons
mysql_auth  ->  Internal (contains the users-table)

User-model

protected $connection = 'mysql_auth';

Code to check if the current user has permission to do something with the Entity

$result = 
    Entity::where('model_name','=',$model_name)
        ->whereHas('permissions', function($query) use ($action) {
            $query->where($action,'=',true);
            $query->whereHas('allowed_users',function($query){
                return $query->where('id','=',Auth::user()->id);
            });
        });

dd($result->toSql());

This code is being called through a webroute, for testing purposes

Route::get('test',function() {
    $perm = App\Helpers\RbacPermission::has_permission('App\Entities\MusicDemons\Artist','create');
    dd($perm);
});

You can see the result of this query in action at https://musicdemons.com/test

The raw SQL query is: select * from entities where model_name = "App\Entities\MusicDemons\Artist" and exists (select * from roles inner join MusicDemons.permissions on roles.id = MusicDemons.permissions.role_id where entities.id = MusicDemons.permissions.entity_id and create = '1' and exists (select * from users inner join MusicDemons.role_user on users.id = MusicDemons.role_user.user_id where roles.id = MusicDemons.role_user.role_id and id = '1') and roles.deleted_at is null) and entities.deleted_at is null

For some reason the eloquent query is picking the wrong database for the User-model (read: users.id doesn't have the database prefix and should actually be Internal.users.id). The odd thing is that the User-model has the $connection explicitly defined, and anyway picks the wrong database to select the data from!

How do I solve this problem? In my opinion this is a bug in Laravel... but is there a way around this bug?

The entire project is hosted at https://github.com/PieterjanDeClippel/LaravelProjects .

The Internal project is just to manage the database containing the users and password_resets. The MusicDemons project contains the main project.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.