Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

I created a solution with a seperate function

In my user model:

    public function allroles()
    {
        //
        $roles=Role::select('id','name','filename','description')->get();
        foreach ($roles as $role) {
            $ru=RoleUser::select('id')
            ->where('user_id','=',$this->id)
            ->where('role_id','=',$role->id)
            ->count();
            if($ru){
                $role->selected=TRUE;
            }else{
                $role->selected=FALSE;
            }
            $data[]=$role;
        }
        
        return $data;
    }

To call this function in my eloquent model (Employee has one user ...)

So in my EmployeeController:

$e=Employee::where('id','=',$id)->with('user')->first(); 
//I add it to the object
$e->roles=$e->user->allroles();

But maybe it can be done easier? With a direct eloquent function?

Last updated 2 years ago.
0

Maybe you colud use a union of those having it true and false.

$yes = $this->roles()->select(DB::Raw('*, TRUE as extra');//don't get
$no = Roles::select(DB::Raw('*, FALSE as extra')->whereNotIn('id', function($query){
$query->select('role_id')->from('role_user')->where('user_id', $this->id);
});//don't get
return $yes->union($no)->get();//get now
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

synbits synbits Joined 17 Apr 2014

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.