根据laravel中已认证用户的托钵,显示托钵的用户列表。

问题描述 投票:0回答:1

我有一个托儿所管理应用程序,我想根据认证用户所属的托儿所来显示用户列表。

在这之前,我可以用下面的代码根据给定的托儿所来显示用户。

$user = Auth::user();

    if ($user->roles()->where('title', 'admin','user')->exists()) {
        $users = User::whereHas( 'roles', function($q)
        { 
            $q->where('title','<>', 'superAdmin'); 

        } )

        ->whereHas('creches', function ($q) {
            $q->where('nom', 'e-creche');
        })


        ->get();
    } else {
        $users = User::all();
    } 

    return view('admin.users.index', compact('users'));

我的问题是,我不想指定上面的 "e-crèche "的名称,我想直接恢复认证用户所属的creche。

谢谢有反应的朋友

laravel
1个回答
0
投票

你可以直接使用这样的关系

Auth::user()->creche

但你必须在User.php和Creche.php之间建立关系,比如这样

User.php

class User extends Authenticatable
{
    public function creche(){
        return $this->belongsTo('App\Creche');
    }
}


Creche.php

class Creche extends Model
{
    public function users(){
        return $this->hasMany('App\User');
    }
}

然后,你可能会得到认证用户的骨灰盒。更多关于关系的内容在这里: Laravel关系

© www.soinside.com 2019 - 2024. All rights reserved.