You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laratrust按用户角色调用数据库数据至视图及Eloquent关系解惑

Solution to Get Users with 'perusahaan' Role & Eloquent Relationships Explained

Hey there! Let's break this down step by step—first, we'll tackle how to display users with the perusahaan role, then I'll explain Eloquent relationships so you understand the "why" behind it all.

Part 1: Fetch & Display Users with 'perusahaan' Role (ID 3)

Since you're using Laratrust, it already sets up the many-to-many relationship between User and Role models out of the box. Here's how to use it:

Step 1: Confirm the Relationship in Your User Model

First, double-check that your User model has the roles() relationship defined (Laratrust usually adds this automatically, but it's good to verify):

// app/Models/User.php
use Illuminate\Database\Eloquent\Model;
use Laratrust\Traits\LaratrustUserTrait;

class User extends Model
{
    use LaratrustUserTrait; // This adds the roles() relationship

    // ... other model code

    // If for some reason the trait isn't handling it, define it manually:
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

Step 2: Query the Users in Your Controller

You have two straightforward ways to get users with the perusahaan role:

Option A: Filter Users by Role (Using whereHas)

This lets you fetch users directly from the User model, filtering those who have the role with ID 3:

// In your controller method (e.g., UserController.php)
use App\Models\User;

public function showPerusahaanUsers()
{
    // Fetch only the names of users with role ID 3
    $perusahaanUsers = User::whereHas('roles', function ($query) {
        $query->where('id', 3);
        // Alternatively, use the role name for clarity:
        // $query->where('name', 'perusahaan');
    })->pluck('name');

    return view('perusahaan-users', compact('perusahaanUsers'));
}

Option B: Fetch from the Role Model

You can also find the perusahaan role first, then get all its associated users:

// In your controller method
use App\Models\Role;

public function showPerusahaanUsers()
{
    $perusahaanRole = Role::find(3);
    $perusahaanUsers = $perusahaanRole->users->pluck('name');

    return view('perusahaan-users', compact('perusahaanUsers'));
}

Step 3: Display in Your View

Pass the $perusahaanUsers variable to your Blade view, then loop through it to show the names:

<!-- resources/views/perusahaan-users.blade.php -->
<h2>Users with Perusahaan Role</h2>
<ul>
    @foreach($perusahaanUsers as $userName)
        <li>{{ $userName }}</li>
    @endforeach
</ul>

Part 2: Eloquent Relationships Explained

Let's demystify what Eloquent relationships are and why they matter for your use case.

What Are Eloquent Relationships?

Eloquent is Laravel's ORM (Object-Relational Mapper)—it turns database tables into PHP objects. Relationships are how we define and interact with the connections between these objects (e.g., a user can have multiple roles, a role can belong to multiple users).

Common Relationship Types (Relevant to Your Case)

Your User and Role setup uses a many-to-many relationship:

  • A single user can have multiple roles (e.g., one user might be both administrator and perusahaan).
  • A single role can be assigned to multiple users (e.g., hundreds of users might have the perusahaan role).

For many-to-many relationships, Laravel uses a "pivot table" (Laratrust creates this as laratrust_role_user) to store the links between users and roles (it has user_id and role_id columns).

How to Use Relationships

  1. Define the Relationship: As we saw in the User model, the roles() method uses belongsToMany() to tell Eloquent about the many-to-many link. Similarly, your Role model should have a users() method:

    // app/Models/Role.php
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
    
  2. Access Related Data:

    • Get all roles for a user: $user->roles (returns a collection of Role objects).
    • Get all users for a role: $role->users (returns a collection of User objects).
    • Filter main models by related data: Use whereHas() (like we did earlier) to fetch only users who have a specific role.

Why use this instead of raw SQL? It's cleaner, more readable, and Laravel handles all the join logic and pivot table interactions for you.

内容的提问来源于stack exchange,提问作者aldi N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:57:38