Eloquent is injecting statement to query by default

Posted 2 years ago by anonymox

I have users table and roles and also user_role tables - which my User Model contain :

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Auth;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'role', 'sex', 'fullname', 'mobile', 'mobile_prefix', 'email', 'co_name', 'tel', 'tel_prefix',
        'password', 'balance', 'last_login_time', 'last_ip',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
    }
}

My Role model is :

namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
    public function users(){
        return $this->belongsToMany('App\User', 'user_role' , 'role_id', 'user_id'); //fixed
    }
}

And this is my userTableSeeder :

use Illuminate\Database\Seeder;
use App\Role;
use App\User;

class UserTableSeeder extends Seeder
{
    public function run()
    {
        $role_admin = Role::where('name', 'ADMIN')->first();
        $role_manager = Role::where('name', 'MANAGER')->first();

        $admin = new User();
        $admin->role = 'ADMIN';
        $admin->fullname = 'fox brain';
        $admin->password = bcrypt('ali');
        $admin->save();
        $admin->roles()->attach($role_admin);

        $manager = new User();
        $manager->role = 'MANAGER';
        $manager->fullname = 'alex parker';
        $manager->password = bcrypt('alex');
        $manager->save();
        $manager->roles()->attach($role_manager);
    }
}

My problem is when I test my code in artisan tinker with :

$role = new Role();
$role->users()->get();

What I get when I check this query is :

string(212) "select `users`.*, `user_role`.`role_id` as `pivot_role_id`, `user_role`.`user_id` as `pivot_user_id` from `users` inner join `user_role` on `users`.`id` = `user_role`.`user_id` where `user_role`.`role_id` is null"

The part which is auto injecting to my query is :

where `user_role`.`role_id` is null

Which make my code not to work and return null ! Any Idea how to solve this problem ?

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

Reply to

Use Markdown with GitHub-flavored code blocks.