Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

NaOumy's avatar

How to display the list of users of a creche according to the creche of the authenticated user in laravel

I have a creche management application and I would like to display the list of users according to the creche to which the authenticated user belongs. For this I have three tables: user, creche and creche_user

Until then I manage to display users according to a given creche with the following code:

'''

$user = Auth::user();

if ($user->roles()->where('title', 'admin'')->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'));

'''

My problem is that I do not want to specify the name of the creche as above "e-crèche". I want to directly recover the creche to which the authenticated user belongs.

Thank you to those who respond!

0 likes
5 replies
MichalOravec's avatar
Level 75

@naoumy Relationship between user and creche is many to many right?

$user = Auth::user();

$user->load('creches');

if ($user->roles()->where('title', 'admin')->exists()) {
    $users = User::whereHas('roles', function($query) { 
        $query->where('title', '<>', 'superAdmin'); 
    })->whereHas('creches', function ($query) use ($user) {
        $query->where('nom', $user->creches->first()->nom);
    })->get();
} else {
    $users = User::all();
} 

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

In fact my question is how can I display the users of a creche according to the creche of the authenticated user?

MichalOravec's avatar

@naoumy For more cretches propably like this

$user = Auth::user();

$user->load('creches');

if ($user->roles()->where('title', 'admin')->exists()) {
    $users = User::whereHas('roles', function($query) { 
        $query->where('title', '<>', 'superAdmin'); 
    })->whereHas('creches', function ($query) use ($user) {
        $query->whereIn('nom', $user->creches->pluck('nom'));
    })->get();
} else {
    $users = User::all();
} 

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

Thank you very much it was the right answer!

1 like

Please or to participate in this conversation.